Compare commits
63
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d43aa02b01 | ||
|
|
5b4d099d80 | ||
|
|
5507fbcb29 | ||
|
|
176cc08a6b | ||
|
|
5953c3cf75 | ||
|
|
0952a482fb | ||
|
|
c7f1d25e98 | ||
|
|
841eab0556 | ||
|
|
ac065fa911 | ||
|
|
70d8128bfb | ||
|
|
8c8ae66c7d | ||
|
|
c8a3f35b0a | ||
|
|
e5c83e87fe | ||
|
|
eb17c8e284 | ||
|
|
459f8b59fe | ||
|
|
e6c705cef7 | ||
|
|
19c4bb451d | ||
|
|
f71b79a17f | ||
|
|
e3eb7ca205 | ||
|
|
2e54163d9e | ||
|
|
344f79039f | ||
|
|
02fe634944 | ||
|
|
7b1f64d727 | ||
|
|
d53e38a48f | ||
|
|
740e738fca | ||
|
|
ee90284129 | ||
|
|
de42b3126b | ||
|
|
71dccbc590 | ||
|
|
4c6127786f | ||
|
|
bf082c59fe | ||
|
|
ee35c10454 | ||
|
|
1651fd00a2 | ||
|
|
d9e4447903 | ||
|
|
f59dd6ebec | ||
|
|
10413547c1 | ||
|
|
2f178db2c6 | ||
|
|
28485d51f7 | ||
|
|
24362b89d7 | ||
|
|
159e4a4cbf | ||
|
|
13a7919c91 | ||
|
|
d670690816 | ||
|
|
62c58c7c89 | ||
|
|
0b4d9a8463 | ||
|
|
51ca8c7e34 | ||
|
|
64047054b8 | ||
|
|
3f5258a76c | ||
|
|
3b93308b71 | ||
|
|
bf53f2e17c | ||
|
|
c2eca11a3b | ||
|
|
4c3f8de1fb | ||
|
|
b3e1869724 | ||
|
|
624f58c723 | ||
|
|
aedc0f6979 | ||
|
|
1e53ceeda6 | ||
|
|
f08ed0c22c | ||
|
|
ee0f877d97 | ||
|
|
b3d4e08914 | ||
|
|
ec9dd83e77 | ||
|
|
4930e2a870 | ||
|
|
5e21cc76fc | ||
|
|
529110a693 | ||
|
|
0b5f2a88cc | ||
|
|
ff6f04fe46 |
No files matched your search
@@ -13,8 +13,10 @@ jobs:
|
||||
- name: Run deploy.sh from within the scripts folder
|
||||
env:
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
DEPLOY_SHA: ${{ github.sha }}
|
||||
SUPPORT_CHAT_KEY: ${{ secrets.SUPPORT_CHAT_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی
|
||||
echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts
|
||||
export http_proxy=""
|
||||
@@ -25,8 +27,8 @@ jobs:
|
||||
|
||||
# 2. دانلود و اجرای اسکریپت deploy.sh بر اساس برنچ جاری
|
||||
mkdir -p scripts
|
||||
wget --no-proxy -qO scripts/deploy.sh https://git.parsaaghayi.ir/parsa/canina/raw/branch/${BRANCH}/scripts/deploy.sh
|
||||
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}
|
||||
./deploy.sh "${BRANCH}"
|
||||
@@ -0,0 +1,24 @@
|
||||
name: Hermes runtime contract review (NO DEPLOY)
|
||||
on:
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
contract-review:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
cache-dependency-path: backend/package-lock.json
|
||||
- run: npm ci --ignore-scripts --no-audit
|
||||
working-directory: backend
|
||||
- run: npm test -- --runInBand hermes-management
|
||||
working-directory: backend
|
||||
- run: npx tsc -p src/hermes-management/tsconfig.contract.json --noEmit
|
||||
working-directory: backend
|
||||
- run: npx tsc -p src/hermes-management/tsconfig.contract.json
|
||||
working-directory: backend
|
||||
# No SSH, Docker socket, secrets, deployments, dispatch or runtime mutation.
|
||||
@@ -2,6 +2,7 @@ FROM node:20-alpine AS builder
|
||||
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
|
||||
WORKDIR /app
|
||||
ENV PRISMA_HIDE_UPDATE_MESSAGE=true
|
||||
ENV PRISMA_SKIP_POSTINSTALL_GENERATE=true
|
||||
ENV PRISMA_ENGINES_MIRROR=https://registry.npmmirror.com/-/binary/prisma
|
||||
ENV DISABLE_OPENCOLLECTIVE=1
|
||||
@@ -33,6 +34,7 @@ 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 && chown node:node /app/uploads
|
||||
WORKDIR /app
|
||||
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
|
||||
COPY --chown=node:node --from=builder /app/eslint.config.mjs ./eslint.config.mjs
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Prisma migration history and Orchestration v4 rollout boundary
|
||||
|
||||
The checked-in history is **not a complete baseline of the current Prisma schema**. Do not assume that replaying it into an empty database can recreate the application, or that existing production tables imply corresponding migration records. Never use `prisma db push`, reset, or edit applied SQL to reconcile this.
|
||||
|
||||
## Actual tracked history
|
||||
|
||||
| Migration | What its SQL actually does |
|
||||
| --- | --- |
|
||||
| `20260526145407_init` | Creates users, addresses, wallets, products, product ingredients/symptoms, pets and medical conditions, reminders/completions, health logs, coupons, orders and order items, with their indexes/foreign keys. |
|
||||
| `20260526160916_add_ui_texts_and_scientific_terms` | Creates `ui_texts` and `scientific_terms`. |
|
||||
| `20261013210253_add_admin_modules` | Creates only `competitor_price_logs`, `b2b_leads`, `price_suggestions`, and `sms_campaigns`, with indexes and product foreign keys. It does **not** create legacy approvals, department tasks or audit logs. |
|
||||
| `20261015000000_add_support_conversations` | Creates support conversations/messages and their foreign keys. |
|
||||
| `20261020000000_add_blog_freshness_authorship` | Adds three columns to an assumed-existing `blogs` table. No earlier tracked migration creates `blogs`; fresh replay is therefore incomplete before v4. |
|
||||
| `20261022000000_add_orchestration_v4_core` | Additively creates nine `orchestration_*` tables, indexes and internal foreign keys; it neither creates nor copies legacy governance tables. |
|
||||
|
||||
There is no checked-in CREATE TABLE migration for `approval_requests`, `department_tasks`, or `audit_logs`. Their models/controllers are not evidence that either live environment has these tables, nor proof of how any historical database acquired them. The broader missing legacy schema must be reconciled separately. This document does not certify live table existence or migration status.
|
||||
|
||||
## Required rollout safeguards (not authorization to deploy)
|
||||
|
||||
1. Back up each environment and verify restore capability. Capture its actual schema and `_prisma_migrations` history read-only; compare those independently against all tracked SQL, including prerequisites such as `blogs`.
|
||||
2. Rehearse the exact planned chain on a disposable database restored from a reviewed baseline. A failed empty replay is a legacy-history gap, not evidence that the additive v4 SQL alone is faulty. Resolve the missing baseline through a separately reviewed migration/baseline plan, never by skipping errors.
|
||||
3. `prisma migrate resolve --applied <name>` only records history; it creates no objects. Use it only for a specifically verified, fully matching existing migration and reviewed environment-specific plan. Never mark the whole chain applied or mark missing tables as applied.
|
||||
4. After baseline reconciliation and rehearsal pass, apply reviewed pending migrations through CI/CD only using `prisma migrate deploy`. Verify all nine v4 tables, constraints, migration records and application health before considering the read surface ready.
|
||||
5. Keep v4 mutations, chat and runtime capabilities denied. Retiring legacy mutation routes does not authorize a replacement execution path.
|
||||
|
||||
No deployment, live DDL, baseline resolution or migration SQL change is part of this hardening milestone. Schema rollout remains a separate gate, not full-system completion.
|
||||
|
||||
Rollback is application-first: stop use of the new module while retaining append-only records. Do not drop tables in automated rollback; removal requires separately reviewed archival migration.
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_team VARCHAR(200);
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS author_role VARCHAR(200);
|
||||
ALTER TABLE blogs ADD COLUMN IF NOT EXISTS content_updated_at TIMESTAMPTZ;
|
||||
@@ -0,0 +1,211 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_tasks" (
|
||||
"id" UUID NOT NULL,
|
||||
"key" VARCHAR(120) NOT NULL,
|
||||
"title" VARCHAR(255) NOT NULL,
|
||||
"department" VARCHAR(50) NOT NULL,
|
||||
"state" VARCHAR(40) NOT NULL DEFAULT 'DRAFT',
|
||||
"operation_mode" VARCHAR(30) NOT NULL,
|
||||
"model_tier" VARCHAR(2),
|
||||
"budget_limit_cents" INTEGER NOT NULL,
|
||||
"version" INTEGER NOT NULL DEFAULT 1,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL,
|
||||
|
||||
CONSTRAINT "orchestration_tasks_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_runs" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"attempt" INTEGER NOT NULL DEFAULT 1,
|
||||
"status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
|
||||
"commit_sha" VARCHAR(64) NOT NULL,
|
||||
"environment" VARCHAR(50) NOT NULL,
|
||||
"retry_class" VARCHAR(30),
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"started_at" TIMESTAMPTZ,
|
||||
"finished_at" TIMESTAMPTZ,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_runs_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_artifacts" (
|
||||
"id" UUID NOT NULL,
|
||||
"run_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(50) NOT NULL,
|
||||
"uri" TEXT NOT NULL,
|
||||
"sha256" CHAR(64) NOT NULL,
|
||||
"size_bytes" BIGINT,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_artifacts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_attestations" (
|
||||
"id" UUID NOT NULL,
|
||||
"run_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(50) NOT NULL,
|
||||
"subject_hash" CHAR(64) NOT NULL,
|
||||
"predicate" JSONB NOT NULL,
|
||||
"signer" VARCHAR(150) NOT NULL,
|
||||
"signature" TEXT,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_attestations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_dependencies" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"depends_on_task_id" UUID NOT NULL,
|
||||
"kind" VARCHAR(30) NOT NULL DEFAULT 'BLOCKS',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_dependencies_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_approval_decisions" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"gate" INTEGER NOT NULL,
|
||||
"decision" VARCHAR(20) NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"notes" TEXT,
|
||||
"expires_at" TIMESTAMPTZ NOT NULL,
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"run_id" UUID,
|
||||
"artifact_hash" CHAR(64),
|
||||
"commit_sha" VARCHAR(64),
|
||||
"environment" VARCHAR(50),
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_approval_decisions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_events" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID,
|
||||
"event_type" VARCHAR(60) NOT NULL,
|
||||
"from_state" VARCHAR(40),
|
||||
"to_state" VARCHAR(40),
|
||||
"sequence" INTEGER NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"idempotency_key" VARCHAR(150),
|
||||
"payload" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_events_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_budget_ledger" (
|
||||
"id" UUID NOT NULL,
|
||||
"task_id" UUID NOT NULL,
|
||||
"amount_cents" INTEGER NOT NULL,
|
||||
"kind" VARCHAR(40) NOT NULL,
|
||||
"idempotency_key" VARCHAR(150) NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_budget_ledger_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "orchestration_kill_switches" (
|
||||
"scope" VARCHAR(80) NOT NULL,
|
||||
"level" VARCHAR(30) NOT NULL,
|
||||
"active" BOOLEAN NOT NULL DEFAULT true,
|
||||
"reason" TEXT NOT NULL,
|
||||
"actor_id" VARCHAR(100) NOT NULL,
|
||||
"version" INTEGER NOT NULL DEFAULT 1,
|
||||
"updated_at" TIMESTAMPTZ NOT NULL,
|
||||
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "orchestration_kill_switches_pkey" PRIMARY KEY ("scope")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_tasks_key_key" ON "orchestration_tasks"("key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_tasks_state_created_at_idx" ON "orchestration_tasks"("state", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_tasks_department_state_idx" ON "orchestration_tasks"("department", "state");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_runs_idempotency_key_key" ON "orchestration_runs"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_runs_task_id_status_idx" ON "orchestration_runs"("task_id", "status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_runs_task_id_attempt_key" ON "orchestration_runs"("task_id", "attempt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_artifacts_run_id_sha256_key" ON "orchestration_artifacts"("run_id", "sha256");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_attestations_run_id_kind_subject_hash_signer_key" ON "orchestration_attestations"("run_id", "kind", "subject_hash", "signer");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_dependencies_task_id_depends_on_task_id_key" ON "orchestration_dependencies"("task_id", "depends_on_task_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_approval_decisions_idempotency_key_key" ON "orchestration_approval_decisions"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_approval_decisions_task_id_gate_created_at_idx" ON "orchestration_approval_decisions"("task_id", "gate", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_events_idempotency_key_key" ON "orchestration_events"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_events_event_type_created_at_idx" ON "orchestration_events"("event_type", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_events_task_id_sequence_key" ON "orchestration_events"("task_id", "sequence");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "orchestration_budget_ledger_idempotency_key_key" ON "orchestration_budget_ledger"("idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "orchestration_budget_ledger_task_id_created_at_idx" ON "orchestration_budget_ledger"("task_id", "created_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_runs" ADD CONSTRAINT "orchestration_runs_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_artifacts" ADD CONSTRAINT "orchestration_artifacts_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_attestations" ADD CONSTRAINT "orchestration_attestations_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_dependencies" ADD CONSTRAINT "orchestration_dependencies_depends_on_task_id_fkey" FOREIGN KEY ("depends_on_task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_approval_decisions" ADD CONSTRAINT "orchestration_approval_decisions_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "orchestration_runs"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_events" ADD CONSTRAINT "orchestration_events_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "orchestration_budget_ledger" ADD CONSTRAINT "orchestration_budget_ledger_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "orchestration_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Immutable evidence and accounting; corrections are new entries.
|
||||
CREATE FUNCTION orchestration_append_only() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'Orchestration append-only record cannot be changed'; END;
|
||||
$$;
|
||||
CREATE TRIGGER orchestration_budget_immutable BEFORE UPDATE OR DELETE ON orchestration_budget_ledger FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_events_immutable BEFORE UPDATE OR DELETE ON orchestration_events FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_approvals_immutable BEFORE UPDATE OR DELETE ON orchestration_approval_decisions FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_artifacts_immutable BEFORE UPDATE OR DELETE ON orchestration_artifacts FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
CREATE TRIGGER orchestration_attestations_immutable BEFORE UPDATE OR DELETE ON orchestration_attestations FOR EACH ROW EXECUTE FUNCTION orchestration_append_only();
|
||||
ALTER TABLE orchestration_tasks ADD CONSTRAINT orchestration_budget_nonnegative CHECK (budget_limit_cents >= 0);
|
||||
@@ -0,0 +1,10 @@
|
||||
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);
|
||||
@@ -179,6 +179,8 @@ model Blog {
|
||||
content String @db.Text
|
||||
excerpt String? @db.Text
|
||||
authorId String? @map("author_id") @db.Uuid
|
||||
authorTeam String? @map("author_team") @db.VarChar(200)
|
||||
authorRole String? @map("author_role") @db.VarChar(200)
|
||||
categoryId String? @map("category_id") @db.Uuid
|
||||
imageUrl String? @map("image_url") @db.Text
|
||||
imageAlt String? @map("image_alt") @db.VarChar(255)
|
||||
@@ -198,6 +200,7 @@ model Blog {
|
||||
isPublished Boolean @default(true) @map("is_published")
|
||||
publishedAt DateTime? @map("published_at") @db.Timestamptz()
|
||||
scheduledAt DateTime? @map("scheduled_at") @db.Timestamptz()
|
||||
contentUpdatedAt DateTime? @map("content_updated_at") @db.Timestamptz()
|
||||
readingTime Int @default(3) @map("reading_time")
|
||||
featured Boolean @default(false)
|
||||
allowComments Boolean @default(true) @map("allow_comments")
|
||||
@@ -1088,3 +1091,161 @@ model DepartmentTask {
|
||||
@@index([createdAt])
|
||||
@@map("department_tasks")
|
||||
}
|
||||
|
||||
// Orchestration v4 additive models. Legacy governance tables remain untouched.
|
||||
model OrchestrationTask {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
key String @unique @db.VarChar(120)
|
||||
title String @db.VarChar(255)
|
||||
department String @db.VarChar(50)
|
||||
state String @default("DRAFT") @db.VarChar(40)
|
||||
operationMode String @map("operation_mode") @db.VarChar(30)
|
||||
modelTier String? @map("model_tier") @db.VarChar(2)
|
||||
budgetLimitCents Int @map("budget_limit_cents")
|
||||
version Int @default(1)
|
||||
metadata Json @default("{}") @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
runs OrchestrationRun[]
|
||||
dependencies OrchestrationDependency[] @relation("task_dependencies")
|
||||
dependedOnBy OrchestrationDependency[] @relation("task_dependents")
|
||||
decisions OrchestrationApprovalDecision[]
|
||||
events OrchestrationEvent[]
|
||||
budgetLedger OrchestrationBudgetLedger[]
|
||||
@@index([state, createdAt])
|
||||
@@index([department, state])
|
||||
@@map("orchestration_tasks")
|
||||
}
|
||||
model OrchestrationRun {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
attempt Int @default(1)
|
||||
status String @default("PENDING") @db.VarChar(30)
|
||||
commitSha String @map("commit_sha") @db.VarChar(64)
|
||||
environment String @db.VarChar(50)
|
||||
retryClass String? @map("retry_class") @db.VarChar(30)
|
||||
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(150)
|
||||
startedAt DateTime? @map("started_at") @db.Timestamptz()
|
||||
finishedAt DateTime? @map("finished_at") @db.Timestamptz()
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask @relation(fields:[taskId],references:[id],onDelete:Restrict)
|
||||
artifacts OrchestrationArtifact[]
|
||||
attestations OrchestrationAttestation[]
|
||||
approvals OrchestrationApprovalDecision[]
|
||||
@@unique([taskId, attempt])
|
||||
@@index([taskId, status])
|
||||
@@map("orchestration_runs")
|
||||
}
|
||||
model OrchestrationArtifact {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
runId String @map("run_id") @db.Uuid
|
||||
kind String @db.VarChar(50)
|
||||
uri String @db.Text
|
||||
sha256 String @db.Char(64)
|
||||
sizeBytes BigInt? @map("size_bytes")
|
||||
metadata Json @default("{}") @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
run OrchestrationRun @relation(fields:[runId],references:[id],onDelete:Restrict)
|
||||
@@unique([runId, sha256])
|
||||
@@map("orchestration_artifacts")
|
||||
}
|
||||
model OrchestrationAttestation {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
runId String @map("run_id") @db.Uuid
|
||||
kind String @db.VarChar(50)
|
||||
subjectHash String @map("subject_hash") @db.Char(64)
|
||||
predicate Json @db.JsonB
|
||||
signer String @db.VarChar(150)
|
||||
signature String? @db.Text
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
run OrchestrationRun @relation(fields:[runId],references:[id],onDelete:Restrict)
|
||||
@@unique([runId, kind, subjectHash, signer])
|
||||
@@map("orchestration_attestations")
|
||||
}
|
||||
model OrchestrationDependency {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
dependsOnTaskId String @map("depends_on_task_id") @db.Uuid
|
||||
kind String @default("BLOCKS") @db.VarChar(30)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask @relation("task_dependencies",fields:[taskId],references:[id],onDelete:Restrict)
|
||||
dependsOnTask OrchestrationTask @relation("task_dependents",fields:[dependsOnTaskId],references:[id],onDelete:Restrict)
|
||||
@@unique([taskId, dependsOnTaskId])
|
||||
@@map("orchestration_dependencies")
|
||||
}
|
||||
model OrchestrationApprovalDecision {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
gate Int
|
||||
decision String @db.VarChar(20)
|
||||
actorId String @map("actor_id") @db.VarChar(100)
|
||||
notes String? @db.Text
|
||||
expiresAt DateTime @map("expires_at") @db.Timestamptz()
|
||||
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(150)
|
||||
runId String? @map("run_id") @db.Uuid
|
||||
artifactHash String? @map("artifact_hash") @db.Char(64)
|
||||
commitSha String? @map("commit_sha") @db.VarChar(64)
|
||||
environment String? @db.VarChar(50)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask @relation(fields:[taskId],references:[id],onDelete:Restrict)
|
||||
run OrchestrationRun? @relation(fields:[runId],references:[id],onDelete:Restrict)
|
||||
@@index([taskId, gate, createdAt])
|
||||
@@map("orchestration_approval_decisions")
|
||||
}
|
||||
model OrchestrationEvent {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String? @map("task_id") @db.Uuid
|
||||
eventType String @map("event_type") @db.VarChar(60)
|
||||
fromState String? @map("from_state") @db.VarChar(40)
|
||||
toState String? @map("to_state") @db.VarChar(40)
|
||||
sequence Int
|
||||
actorId String @map("actor_id") @db.VarChar(100)
|
||||
idempotencyKey String? @unique @map("idempotency_key") @db.VarChar(150)
|
||||
payload Json @default("{}") @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask? @relation(fields:[taskId],references:[id],onDelete:Restrict)
|
||||
@@unique([taskId, sequence])
|
||||
@@index([eventType, createdAt])
|
||||
@@map("orchestration_events")
|
||||
}
|
||||
model OrchestrationBudgetLedger {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
taskId String @map("task_id") @db.Uuid
|
||||
amountCents Int @map("amount_cents")
|
||||
kind String @db.VarChar(40)
|
||||
idempotencyKey String @unique @map("idempotency_key") @db.VarChar(150)
|
||||
actorId String @map("actor_id") @db.VarChar(100)
|
||||
metadata Json @default("{}") @db.JsonB
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
task OrchestrationTask @relation(fields:[taskId],references:[id],onDelete:Restrict)
|
||||
@@index([taskId, createdAt])
|
||||
@@map("orchestration_budget_ledger")
|
||||
}
|
||||
model OrchestrationKillSwitch {
|
||||
scope String @id @db.VarChar(80)
|
||||
level String @db.VarChar(30)
|
||||
active Boolean @default(true)
|
||||
reason String @db.Text
|
||||
actorId String @map("actor_id") @db.VarChar(100)
|
||||
version Int @default(1)
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
|
||||
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)
|
||||
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])
|
||||
@@map("prepare_workflow_outbox")
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { GoneException } from '@nestjs/common';
|
||||
import { ApprovalsController } from './approvals.controller';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
describe('ApprovalsController retired mutation boundary',()=>{
|
||||
const access=jest.fn();
|
||||
const prisma=new Proxy({},{get:(_target,key)=>{access(key);throw new Error('Database access forbidden');}});
|
||||
const controller=new ApprovalsController(prisma as PrismaService);
|
||||
beforeEach(()=>access.mockClear());
|
||||
it('create {department:SEO,category:SEO,title:Legacy,payload:{}} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.create({department:'SEO',category:'SEO',title:'Legacy',payload:{}})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.create({department:'SEO',category:'SEO',title:'Legacy',payload:{}})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
it('decide missing, {decision:APPROVED} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.decide('missing', {decision:'APPROVED'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.decide('missing', {decision:'APPROVED'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
it('decide missing, {decision:REJECTED} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.decide('missing', {decision:'REJECTED'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.decide('missing', {decision:'REJECTED'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -3,13 +3,12 @@ import {
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
GoneException,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
@@ -83,17 +82,7 @@ export class ApprovalsController {
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ثبت آیتم جدید جهت تایید مدیریت (از طرف سیستم یا دپارتمانها)" })
|
||||
async create(@Body() dto: CreateApprovalRequestDto) {
|
||||
const item = await (this.prisma as any).approvalRequest.create({
|
||||
data: {
|
||||
department: dto.department,
|
||||
category: dto.category,
|
||||
title: dto.title,
|
||||
payload: dto.payload,
|
||||
testContext: dto.testContext || {},
|
||||
status: "PENDING",
|
||||
},
|
||||
});
|
||||
return { success: true, data: item };
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
@Post(":id/test")
|
||||
@@ -106,7 +95,6 @@ export class ApprovalsController {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
|
||||
// شبیهسازی بسته به دستهبندی
|
||||
let testResult: any = { status: "SIMULATION_SUCCESS" };
|
||||
if (item.category === "PRICING") {
|
||||
const payload = item.payload as any;
|
||||
@@ -140,80 +128,7 @@ export class ApprovalsController {
|
||||
@Put(":id/decide")
|
||||
@ApiOperation({ summary: "تصمیمگیری مدیرعامل (تایید یا رد همراه با یادداشت)" })
|
||||
async decide(@Param("id") id: string, @Body() dto: DecideApprovalDto) {
|
||||
if (!["APPROVED", "REJECTED"].includes(dto.decision)) {
|
||||
throw new BadRequestException("Decision must be either APPROVED or REJECTED");
|
||||
}
|
||||
|
||||
const item = await (this.prisma as any).approvalRequest.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException(`Approval request ${id} not found`);
|
||||
}
|
||||
|
||||
if (dto.decision === "REJECTED") {
|
||||
// 5. رد توسط مدیرعامل: تسک و درخواست کلاً از سیستم پاکسازی کامل میشوند
|
||||
await (this.prisma as any).departmentTask.deleteMany({
|
||||
where: { approvalId: id },
|
||||
});
|
||||
await (this.prisma as any).approvalRequest.delete({
|
||||
where: { id },
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
message: "درخواست با موفقیت رد و از سیستم پاکسازی شد.",
|
||||
};
|
||||
}
|
||||
|
||||
// 1. تایید مدیرعامل: وضعیت درخواست APPROVED و وضعیت تسک در صف اقدام به TODO تغییر مییابد
|
||||
const updated = await (this.prisma as any).approvalRequest.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: "APPROVED",
|
||||
ceoNotes: dto.ceoNotes || null,
|
||||
executedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
// جستجو یا ایجاد تسک متناظر با استاتوس TODO
|
||||
const existingTask = await (this.prisma as any).departmentTask.findFirst({
|
||||
where: { approvalId: id },
|
||||
});
|
||||
|
||||
if (existingTask) {
|
||||
await (this.prisma as any).departmentTask.update({
|
||||
where: { id: existingTask.id },
|
||||
data: {
|
||||
status: "TODO",
|
||||
description: dto.ceoNotes ? (existingTask.description || "") + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes : existingTask.description,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
await (this.prisma as any).departmentTask.create({
|
||||
data: {
|
||||
code: "TSK-" + Date.now().toString().slice(-6),
|
||||
department: item.department,
|
||||
title: item.title,
|
||||
description: dto.ceoNotes ? (item.title + "\n\n[یادداشت مدیرعامل]: " + dto.ceoNotes) : item.title,
|
||||
status: "TODO",
|
||||
priority: "HIGH",
|
||||
assignee: "AI_AGENT",
|
||||
approvalId: item.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "درخواست تایید شد و مأموریت به صف اقدام (TODO) دپارتمان منتقل گردید.",
|
||||
data: updated,
|
||||
};
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@ApiOperation({ summary: "حذف آیتم از کارتابل" })
|
||||
async remove(@Param("id") id: string) {
|
||||
await (this.prisma as any).approvalRequest.delete({ where: { id } });
|
||||
return { success: true, message: "Deleted successfully" };
|
||||
}
|
||||
}
|
||||
@@ -229,6 +229,15 @@ describe("BlogsController (Admin)", () => {
|
||||
expect(result).toEqual({ success: true, data: createdBlog });
|
||||
});
|
||||
|
||||
it("propagates create validation failures", async () => {
|
||||
const req = { user: { id: "admin-user-id" } };
|
||||
const body = { title: "Bad date", contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
|
||||
mockBlogsService.createBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
|
||||
|
||||
await expect(controller.createBlog(body, req)).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(service.createBlog).toHaveBeenCalledWith(body, req.user.id);
|
||||
});
|
||||
|
||||
it("updateBlog should update blog details and return success: true", async () => {
|
||||
const blogId = "blog-10";
|
||||
const body = {
|
||||
@@ -244,6 +253,14 @@ describe("BlogsController (Admin)", () => {
|
||||
expect(result).toEqual({ success: true, data: updatedBlog });
|
||||
});
|
||||
|
||||
it("propagates invalid content timestamp rejection without accepting createdAt", async () => {
|
||||
const body = { contentUpdatedAt: "invalid", createdAt: "2000-01-01" };
|
||||
mockBlogsService.updateBlog.mockRejectedValueOnce(new Error("Invalid contentUpdatedAt"));
|
||||
|
||||
await expect(controller.updateBlog("blog-10", body)).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(service.updateBlog).toHaveBeenCalledWith("blog-10", body);
|
||||
});
|
||||
|
||||
it("deleteBlog should delete blog and return success: true", async () => {
|
||||
const blogId = "blog-10";
|
||||
mockBlogsService.deleteBlog.mockResolvedValue(undefined);
|
||||
|
||||
@@ -203,6 +203,50 @@ describe("Admin BlogsService", () => {
|
||||
expect(result).toEqual(createdBlog);
|
||||
});
|
||||
|
||||
it("allowlists create fields and blocks server-owned and unknown fields", async () => {
|
||||
mockPrisma.blog.create.mockResolvedValue({ id: "created", slug: "safe-post" });
|
||||
|
||||
await service.createBlog(
|
||||
{
|
||||
title: "Safe post",
|
||||
slug: "safe-post",
|
||||
content: "Safe content",
|
||||
id: "client-id",
|
||||
createdAt: "2000-01-01T00:00:00.000Z",
|
||||
updatedAt: "2000-01-01T00:00:00.000Z",
|
||||
viewCount: 999999,
|
||||
serverOwned: "must-not-pass",
|
||||
},
|
||||
"user-admin-1",
|
||||
);
|
||||
|
||||
const payload = mockPrisma.blog.create.mock.calls[0][0].data;
|
||||
expect(payload).toEqual(expect.objectContaining({
|
||||
title: "Safe post",
|
||||
slug: "safe-post",
|
||||
content: "Safe content",
|
||||
}));
|
||||
expect(payload).not.toHaveProperty("id");
|
||||
expect(payload).not.toHaveProperty("createdAt");
|
||||
expect(payload).not.toHaveProperty("updatedAt");
|
||||
expect(payload).not.toHaveProperty("viewCount");
|
||||
expect(payload).not.toHaveProperty("serverOwned");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["contentUpdatedAt", { contentUpdatedAt: "not-a-date" }, "Invalid contentUpdatedAt"],
|
||||
["publishedAt", { publishedAt: "not-a-date" }, "Invalid publishedAt"],
|
||||
["scheduledAt", { scheduledAt: "not-a-date" }, "Invalid scheduledAt"],
|
||||
])("rejects invalid explicit %s", async (_field, timestamps, message) => {
|
||||
await expect(
|
||||
service.createBlog(
|
||||
{ title: "Bad date", slug: "bad-date", content: "Content", ...timestamps },
|
||||
"user-admin-1",
|
||||
),
|
||||
).rejects.toThrow(message);
|
||||
expect(mockPrisma.blog.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should create a SCHEDULED blog if scheduledAt is in the future", async () => {
|
||||
const futureDate = new Date(Date.now() + 86400000).toISOString();
|
||||
const blogData = {
|
||||
@@ -274,6 +318,81 @@ describe("Admin BlogsService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("material freshness and scheduled publishing", () => {
|
||||
it("sets contentUpdatedAt intentionally and never rewrites createdAt", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", createdAt: new Date("2025-01-01") });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { title: "Material edit", markContentUpdated: true });
|
||||
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
|
||||
expect(payload.contentUpdatedAt).toEqual(expect.any(Date));
|
||||
expect(payload).not.toHaveProperty("markContentUpdated");
|
||||
expect(payload).not.toHaveProperty("createdAt");
|
||||
});
|
||||
it("automatically marks freshness when material article content changes", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Old content" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { content: "Meaningfully revised content" });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toEqual(expect.any(Date));
|
||||
});
|
||||
it("does not mark freshness for attribution-only changes", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post", content: "Same content" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { authorTeam: "Clinical team", authorRole: "Review" });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data).not.toHaveProperty("contentUpdatedAt");
|
||||
});
|
||||
it("allows explicitly clearing contentUpdatedAt", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "b1", slug: "post" });
|
||||
await service.updateBlog("b1", { contentUpdatedAt: null });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
|
||||
});
|
||||
it("publishes due posts without rewriting createdAt", async () => {
|
||||
const scheduledAt = new Date("2025-02-01T10:00:00Z");
|
||||
mockPrisma.blog.findMany.mockResolvedValue([{ id: "b1", slug: "post", title: "Post", scheduledAt }]);
|
||||
mockPrisma.blog.update.mockResolvedValue({});
|
||||
await service.publishDueScheduledBlogs();
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalledWith({ where: { id: "b1" }, data: { status: "PUBLISHED", isPublished: true, publishedAt: scheduledAt } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateBlog security and freshness validation", () => {
|
||||
beforeEach(() => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue({ id: "blog-1", slug: "safe" });
|
||||
mockPrisma.blog.update.mockResolvedValue({ id: "blog-1", slug: "safe" });
|
||||
});
|
||||
|
||||
it("allowlists mutable fields and ignores createdAt and unrecognized fields", async () => {
|
||||
await service.updateBlog("blog-1", {
|
||||
title: "Allowed title",
|
||||
createdAt: "2000-01-01T00:00:00.000Z",
|
||||
serverOwned: "must-not-pass",
|
||||
});
|
||||
|
||||
const payload = mockPrisma.blog.update.mock.calls[0][0].data;
|
||||
expect(payload.title).toBe("Allowed title");
|
||||
expect(payload).not.toHaveProperty("createdAt");
|
||||
expect(payload).not.toHaveProperty("serverOwned");
|
||||
});
|
||||
|
||||
it("rejects an invalid explicit contentUpdatedAt", async () => {
|
||||
await expect(
|
||||
service.updateBlog("blog-1", { contentUpdatedAt: "not-a-date" }),
|
||||
).rejects.toThrow("Invalid contentUpdatedAt");
|
||||
expect(mockPrisma.blog.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves explicit null clearing and markContentUpdated precedence", async () => {
|
||||
await service.updateBlog("blog-1", { contentUpdatedAt: null });
|
||||
expect(mockPrisma.blog.update.mock.calls[0][0].data.contentUpdatedAt).toBeNull();
|
||||
|
||||
await service.updateBlog("blog-1", {
|
||||
contentUpdatedAt: "not-a-date",
|
||||
markContentUpdated: true,
|
||||
});
|
||||
expect(mockPrisma.blog.update.mock.calls[1][0].data.contentUpdatedAt).toEqual(expect.any(Date));
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteBlog", () => {
|
||||
it("should throw NotFoundException if blog not found", async () => {
|
||||
mockPrisma.blog.findUnique.mockResolvedValue(null);
|
||||
@@ -468,7 +587,6 @@ describe("Admin BlogsService", () => {
|
||||
status: "PUBLISHED",
|
||||
isPublished: true,
|
||||
publishedAt: scheduledDate,
|
||||
createdAt: scheduledDate,
|
||||
},
|
||||
});
|
||||
expect(mockRevalidationService.revalidateBlog).toHaveBeenCalledWith(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
OnModuleInit,
|
||||
@@ -141,16 +142,31 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
async createBlog(data: any, currentUserId: string) {
|
||||
const {
|
||||
tags,
|
||||
tagNames,
|
||||
categoryId,
|
||||
authorId,
|
||||
publishedAt,
|
||||
scheduledAt,
|
||||
readingTime,
|
||||
...rest
|
||||
markContentUpdated,
|
||||
contentUpdatedAt,
|
||||
} = data;
|
||||
|
||||
const parseOptionalDate = (value: unknown, field: string): Date | null => {
|
||||
if (value === undefined || value === null || value === "") return null;
|
||||
const parsed = new Date(value as string | number | Date);
|
||||
if (!Number.isFinite(parsed.getTime())) {
|
||||
throw new BadRequestException(`Invalid ${field}`);
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
|
||||
const parsedPublishedAt = parseOptionalDate(publishedAt, "publishedAt");
|
||||
const parsedScheduledAt = parseOptionalDate(scheduledAt, "scheduledAt");
|
||||
const parsedContentUpdatedAt = markContentUpdated
|
||||
? new Date()
|
||||
: parseOptionalDate(contentUpdatedAt, "contentUpdatedAt");
|
||||
|
||||
// Connect or create tags
|
||||
const tagConnectOrCreate = [];
|
||||
if (Array.isArray(tagNames) && tagNames.length > 0) {
|
||||
@@ -171,13 +187,12 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
const targetAuthorId = authorId || currentUserId;
|
||||
const now = new Date();
|
||||
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||
const isFutureSchedule = parsedScheduledAt && parsedScheduledAt > now;
|
||||
|
||||
let finalStatus = rest.status || "PUBLISHED";
|
||||
let finalStatus = data.status || "PUBLISHED";
|
||||
let finalIsPublished =
|
||||
rest.isPublished !== undefined ? rest.isPublished : true;
|
||||
let finalPublishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||
data.isPublished !== undefined ? data.isPublished : true;
|
||||
let finalPublishedAt = parsedPublishedAt;
|
||||
|
||||
if (isFutureSchedule) {
|
||||
finalStatus = "SCHEDULED";
|
||||
@@ -191,19 +206,45 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
finalPublishedAt = now;
|
||||
}
|
||||
|
||||
const createPayload: Prisma.BlogCreateInput = {
|
||||
...rest,
|
||||
const createPayload = {
|
||||
title: data.title,
|
||||
slug: data.slug,
|
||||
content: data.content,
|
||||
excerpt: data.excerpt,
|
||||
authorTeam: data.authorTeam,
|
||||
authorRole: data.authorRole,
|
||||
imageUrl: data.imageUrl,
|
||||
imageAlt: data.imageAlt,
|
||||
imageCaption: data.imageCaption,
|
||||
metaTitle: data.metaTitle,
|
||||
metaDescription: data.metaDescription,
|
||||
keywords: data.keywords,
|
||||
focusKeywords: data.focusKeywords,
|
||||
canonicalUrl: data.canonicalUrl,
|
||||
noIndex: data.noIndex,
|
||||
noFollow: data.noFollow,
|
||||
schemaType: data.schemaType,
|
||||
ogTitle: data.ogTitle,
|
||||
ogDescription: data.ogDescription,
|
||||
ogImage: data.ogImage,
|
||||
status: finalStatus,
|
||||
isPublished: finalIsPublished,
|
||||
readingTime: readingTime ? Number(readingTime) : 3,
|
||||
featured: data.featured,
|
||||
allowComments: data.allowComments,
|
||||
showOnHome: data.showOnHome,
|
||||
homeDisplayMode: data.homeDisplayMode,
|
||||
relatedProductIds: data.relatedProductIds,
|
||||
relatedBlogIds: data.relatedBlogIds,
|
||||
readingTime: readingTime !== undefined ? Number(readingTime) : 3,
|
||||
publishedAt: finalPublishedAt,
|
||||
scheduledAt: parsedScheduledAt,
|
||||
contentUpdatedAt: parsedContentUpdatedAt,
|
||||
author: { connect: { id: targetAuthorId } },
|
||||
...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
|
||||
...(tagConnectOrCreate.length > 0
|
||||
? { tags: { connectOrCreate: tagConnectOrCreate } }
|
||||
: {}),
|
||||
};
|
||||
} satisfies Prisma.BlogCreateInput;
|
||||
|
||||
const created = await this.prisma.blog.create({
|
||||
data: createPayload,
|
||||
@@ -223,19 +264,83 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
if (!blog) throw new NotFoundException("Blog not found");
|
||||
|
||||
const {
|
||||
tags,
|
||||
tagNames,
|
||||
categoryId,
|
||||
authorId,
|
||||
publishedAt,
|
||||
scheduledAt,
|
||||
readingTime,
|
||||
...rest
|
||||
markContentUpdated,
|
||||
contentUpdatedAt,
|
||||
} = data;
|
||||
|
||||
const mutableScalarFields = [
|
||||
"title",
|
||||
"slug",
|
||||
"content",
|
||||
"excerpt",
|
||||
"authorTeam",
|
||||
"authorRole",
|
||||
"imageUrl",
|
||||
"imageAlt",
|
||||
"imageCaption",
|
||||
"metaTitle",
|
||||
"metaDescription",
|
||||
"keywords",
|
||||
"focusKeywords",
|
||||
"canonicalUrl",
|
||||
"noIndex",
|
||||
"noFollow",
|
||||
"schemaType",
|
||||
"ogTitle",
|
||||
"ogDescription",
|
||||
"ogImage",
|
||||
"status",
|
||||
"isPublished",
|
||||
"featured",
|
||||
"allowComments",
|
||||
"showOnHome",
|
||||
"homeDisplayMode",
|
||||
"relatedProductIds",
|
||||
"relatedBlogIds",
|
||||
] as const;
|
||||
const updatePayload: Prisma.BlogUpdateInput = {};
|
||||
for (const field of mutableScalarFields) {
|
||||
if (data[field] !== undefined) {
|
||||
(updatePayload as Record<string, unknown>)[field] = data[field];
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const updatePayload: Prisma.BlogUpdateInput = {
|
||||
...rest,
|
||||
const materialContentFields = [
|
||||
"title",
|
||||
"content",
|
||||
"excerpt",
|
||||
"imageUrl",
|
||||
"imageAlt",
|
||||
"imageCaption",
|
||||
] as const;
|
||||
const hasMaterialContentChange = materialContentFields.some(
|
||||
(field) => data[field] !== undefined && data[field] !== blog[field],
|
||||
);
|
||||
if (markContentUpdated || (contentUpdatedAt === undefined && hasMaterialContentChange)) {
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = now;
|
||||
} else if (contentUpdatedAt !== undefined) {
|
||||
if (contentUpdatedAt === null || contentUpdatedAt === "") {
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = null;
|
||||
} else {
|
||||
const parsedContentUpdatedAt = new Date(contentUpdatedAt);
|
||||
if (!Number.isFinite(parsedContentUpdatedAt.getTime())) {
|
||||
throw new BadRequestException("Invalid contentUpdatedAt");
|
||||
}
|
||||
(updatePayload as Record<string, unknown>).contentUpdatedAt = parsedContentUpdatedAt;
|
||||
}
|
||||
}
|
||||
|
||||
Object.assign(updatePayload, {
|
||||
...(readingTime !== undefined
|
||||
? { readingTime: Number(readingTime) }
|
||||
: {}),
|
||||
...(readingTime !== undefined
|
||||
? { readingTime: Number(readingTime) }
|
||||
: {}),
|
||||
@@ -245,7 +350,7 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
? { category: { connect: { id: categoryId } } }
|
||||
: { category: { disconnect: true } }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
if (scheduledAt !== undefined) {
|
||||
const parsedScheduledAt = scheduledAt ? new Date(scheduledAt) : null;
|
||||
@@ -259,7 +364,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
updatePayload.status = "PUBLISHED";
|
||||
updatePayload.isPublished = true;
|
||||
updatePayload.publishedAt = parsedScheduledAt;
|
||||
updatePayload.createdAt = parsedScheduledAt;
|
||||
}
|
||||
} else if (publishedAt !== undefined) {
|
||||
updatePayload.publishedAt = publishedAt ? new Date(publishedAt) : null;
|
||||
@@ -472,7 +576,6 @@ export class BlogsService implements OnModuleInit, OnModuleDestroy {
|
||||
status: "PUBLISHED",
|
||||
isPublished: true,
|
||||
publishedAt: publishDate,
|
||||
createdAt: publishDate,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
import { assertTaskCanComplete } from "./department-task-completion.policy";
|
||||
|
||||
describe("department task completion policy", () => {
|
||||
it("rejects model-only output without a live deliverable", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: null,
|
||||
acceptanceCriteria: { criteria: ["live URL responds 200"] },
|
||||
executionLogs: [{ status: "COMPLETED_BY_AGENT" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion without acceptance criteria", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: null,
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion without QA evidence", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "COMPLETED_BY_AGENT" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("allows completion with URL, criteria and QA evidence", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("rejects pseudo-protocol canina:// deliverable URLs", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "canina://blog/sample-article",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects git://stage staging or repo URLs as verifiable deliverable", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "git://stage/canina-repo#commit123",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects missing or placeholder post-tsk article deliverables", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/post-tsk-49102",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it("rejects completion when QA evidence reports missing article or 404 error", () => {
|
||||
expect(() =>
|
||||
assertTaskCanComplete({
|
||||
deliverableUrl: "https://canina.ir/blog/verified-article",
|
||||
acceptanceCriteria: { criteria: ["HTTP 200"] },
|
||||
executionLogs: [{ status: "QA_PASSED", note: "HTTP 404 - مقاله یافت نشد" }],
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
|
||||
export interface CompletableTask {
|
||||
code?: string | null;
|
||||
title?: string | null;
|
||||
deliverableUrl?: string | null;
|
||||
acceptanceCriteria?: unknown;
|
||||
executionLogs?: unknown;
|
||||
}
|
||||
|
||||
function hasAcceptanceCriteria(criteria: unknown): boolean {
|
||||
if (!criteria) return false;
|
||||
if (typeof criteria === "string") return criteria.trim().length > 0;
|
||||
if (Array.isArray(criteria)) return criteria.length > 0;
|
||||
if (typeof criteria === "object") {
|
||||
const value = criteria as Record<string, unknown>;
|
||||
const items = value.criteria;
|
||||
return Array.isArray(items) ? items.length > 0 : Object.keys(value).length > 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function hasValidQaEvidence(logs: unknown): boolean {
|
||||
if (!Array.isArray(logs)) return false;
|
||||
const validPassStatuses = ["QA_PASSED", "VERIFIED", "PRODUCTION_VERIFIED"];
|
||||
|
||||
let foundValidPass = false;
|
||||
for (const log of logs) {
|
||||
if (!log || typeof log !== "object") continue;
|
||||
const entry = log as Record<string, unknown>;
|
||||
const status = String(entry.status || "").toUpperCase();
|
||||
const note = String(entry.note || "").toLowerCase();
|
||||
|
||||
// Rejection of invalid QA claims: 404, missing article, not found, post-tsk
|
||||
if (
|
||||
note.includes("404") ||
|
||||
note.includes("مقاله یافت نشد") ||
|
||||
note.includes("not found") ||
|
||||
note.includes("missing article") ||
|
||||
note.includes("post-tsk")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (validPassStatuses.includes(status)) {
|
||||
foundValidPass = true;
|
||||
}
|
||||
}
|
||||
return foundValidPass;
|
||||
}
|
||||
|
||||
export function assertTaskCanComplete(task: CompletableTask): void {
|
||||
const rawUrl = task.deliverableUrl?.trim();
|
||||
if (!rawUrl) {
|
||||
throw new BadRequestException("DONE requires a verifiable deliverable URL");
|
||||
}
|
||||
|
||||
const lowerUrl = rawUrl.toLowerCase();
|
||||
|
||||
// Reject internal pseudo-protocols
|
||||
if (lowerUrl.startsWith("canina://") || lowerUrl.includes("canina://")) {
|
||||
throw new BadRequestException("Deliverable URL cannot use pseudo-protocol canina://; an independently verifiable HTTP(S) URL is required");
|
||||
}
|
||||
|
||||
// Reject git repository pointers or staging branches as production deliverables
|
||||
if (lowerUrl.startsWith("git://") || lowerUrl.includes("git://stage")) {
|
||||
throw new BadRequestException("Deliverable URL cannot be a git staging reference; an independently verifiable HTTP(S) URL is required");
|
||||
}
|
||||
|
||||
// Must be an HTTP or HTTPS URL
|
||||
if (!lowerUrl.startsWith("http://") && !lowerUrl.startsWith("https://")) {
|
||||
throw new BadRequestException("DONE requires an independently verifiable HTTP or HTTPS deliverable URL");
|
||||
}
|
||||
|
||||
// Reject deleted or placeholder post-tsk articles
|
||||
if (/post[-_]?tsk/i.test(rawUrl)) {
|
||||
throw new BadRequestException("Deliverable URL references an unverified or deleted post-tsk placeholder article");
|
||||
}
|
||||
if (task.title && /post[-_]?tsk/i.test(task.title)) {
|
||||
throw new BadRequestException("Task references an unverified or deleted post-tsk article");
|
||||
}
|
||||
if (task.code && /post[-_]?tsk/i.test(task.code)) {
|
||||
throw new BadRequestException("Task references an unverified or deleted post-tsk code");
|
||||
}
|
||||
|
||||
if (!hasAcceptanceCriteria(task.acceptanceCriteria)) {
|
||||
throw new BadRequestException("DONE requires explicit acceptance criteria");
|
||||
}
|
||||
|
||||
if (!hasValidQaEvidence(task.executionLogs)) {
|
||||
throw new BadRequestException("DONE requires QA/production verification evidence");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { GoneException } from '@nestjs/common';
|
||||
import { DepartmentTasksController } from './department-tasks.controller';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
describe('DepartmentTasksController retired mutation boundary',()=>{
|
||||
const access=jest.fn();
|
||||
const prisma=new Proxy({},{get:(_target,key)=>{access(key);throw new Error('Database access forbidden');}});
|
||||
const controller=new DepartmentTasksController(prisma as PrismaService);
|
||||
beforeEach(()=>access.mockClear());
|
||||
it('create {department:SEO,title:Legacy} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.create({department:'SEO',title:'Legacy'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.create({department:'SEO',title:'Legacy'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
it('updateStatus missing, {status:DONE} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.updateStatus('missing', {status:'DONE'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.updateStatus('missing', {status:'DONE'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
it('updateStatus missing, {status:TODO} returns 410 without reading or writing persistence',async()=>{
|
||||
await expect(controller.updateStatus('missing', {status:'TODO'})).rejects.toBeInstanceOf(GoneException);
|
||||
await expect(controller.updateStatus('missing', {status:'TODO'})).rejects.toMatchObject({status:410});
|
||||
expect(access).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -3,12 +3,12 @@ import {
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
NotFoundException,
|
||||
GoneException,
|
||||
} from "@nestjs/common";
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from "@nestjs/swagger";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
@@ -112,37 +112,7 @@ export class DepartmentTasksController {
|
||||
@Post()
|
||||
@ApiOperation({ summary: "ایجاد تسک جدید سازمانی" })
|
||||
async create(@Body() body: any) {
|
||||
const code = body.code || "TSK-" + Date.now().toString().slice(-6);
|
||||
const task = await (this.prisma as any).departmentTask.create({
|
||||
data: {
|
||||
code,
|
||||
department: body.department,
|
||||
title: body.title,
|
||||
description: body.description || null,
|
||||
status: body.status || "TODO",
|
||||
priority: body.priority || "MEDIUM",
|
||||
assignee: body.assignee || "AI_AGENT",
|
||||
acceptanceCriteria: body.acceptanceCriteria || null,
|
||||
executionLogs: body.executionLogs || [],
|
||||
deliverableUrl: body.deliverableUrl || null,
|
||||
startedAt: body.status === "IN_PROGRESS" ? new Date() : null,
|
||||
},
|
||||
});
|
||||
|
||||
// ثبت در تاریخچه لاگها
|
||||
await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
entity: "task",
|
||||
entityId: task.id,
|
||||
action: "CREATE",
|
||||
department: task.department,
|
||||
actor: task.assignee || "SYSTEM",
|
||||
summary: "تسک جدید " + task.code + " (" + task.title + ") ایجاد شد.",
|
||||
newValues: task,
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true, data: task };
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
@Put(":id/status")
|
||||
@@ -151,58 +121,7 @@ export class DepartmentTasksController {
|
||||
@Param("id") id: string,
|
||||
@Body() body: { status: string; logNote?: string; deliverableUrl?: string }
|
||||
) {
|
||||
const existing = await (this.prisma as any).departmentTask.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
if (!existing) throw new NotFoundException(`Task ${id} not found`);
|
||||
|
||||
const logs = Array.isArray(existing.executionLogs) ? [...existing.executionLogs] : [];
|
||||
if (body.logNote) {
|
||||
logs.push({
|
||||
timestamp: new Date().toISOString(),
|
||||
status: body.status,
|
||||
note: body.logNote,
|
||||
});
|
||||
}
|
||||
|
||||
const updateData: any = {
|
||||
status: body.status,
|
||||
executionLogs: logs,
|
||||
};
|
||||
if (body.deliverableUrl) updateData.deliverableUrl = body.deliverableUrl;
|
||||
if (body.status === "IN_PROGRESS" && !existing.startedAt) updateData.startedAt = new Date();
|
||||
if (body.status === "DONE") updateData.completedAt = new Date();
|
||||
// اگر تست QA ناموفق بود و به TODO برگشت، لاگ اصلاح ضمیمه میشود
|
||||
if (body.status === "TODO" && body.logNote) {
|
||||
updateData.description = (existing.description || "") + "\n\n[اصلاحات و تضمین کیفیت QA]: " + body.logNote;
|
||||
}
|
||||
|
||||
const updated = await (this.prisma as any).departmentTask.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
// ثبت در تاریخچه
|
||||
await (this.prisma as any).auditLog.create({
|
||||
data: {
|
||||
entity: "task",
|
||||
entityId: updated.id,
|
||||
action: "UPDATE",
|
||||
department: updated.department,
|
||||
actor: "SYSTEM",
|
||||
summary: "وضعیت تسک " + updated.code + " به " + body.status + " تغییر یافت.",
|
||||
oldValues: { status: existing.status },
|
||||
newValues: { status: updated.status, note: body.logNote },
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true, data: updated };
|
||||
throw new GoneException("Legacy orchestration mutations are retired. Orchestration v4 remains read-only; no replacement mutation is enabled.");
|
||||
}
|
||||
|
||||
@Delete(":id")
|
||||
@ApiOperation({ summary: "حذف تسک" })
|
||||
async remove(@Param("id") id: string) {
|
||||
await (this.prisma as any).departmentTask.delete({ where: { id } });
|
||||
return { success: true, message: "Deleted successfully" };
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,16 @@ export class DecideApprovalDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
ceoNotes?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "نتیجه اقدام مدیریتی یا استراتژیک" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
outcome?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: "مستندات و مدرک اقدام مدیریتی" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
evidence?: string;
|
||||
}
|
||||
|
||||
export class QueryApprovalDto {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import request from 'supertest';
|
||||
import { ApprovalsController } from './approvals.controller';
|
||||
import { DepartmentTasksController } from './department-tasks.controller';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
|
||||
describe('retired legacy orchestration HTTP boundary', () => {
|
||||
let app: INestApplication;
|
||||
const dbAccess = jest.fn();
|
||||
const prisma = new Proxy({}, {get: (_target, key) => {
|
||||
// Nest inspects provider thenables and lifecycle hooks during setup.
|
||||
if (["then", "onModuleInit", "onApplicationBootstrap", "onModuleDestroy", "beforeApplicationShutdown", "onApplicationShutdown"].includes(String(key))) return undefined;
|
||||
dbAccess(key);
|
||||
throw new Error('Persistence must not be accessed');
|
||||
}});
|
||||
const routes = [
|
||||
['post', '/admin/approvals'],
|
||||
['put', '/admin/approvals/missing/decide'],
|
||||
['post', '/admin/department-tasks'],
|
||||
['put', '/admin/department-tasks/missing/status'],
|
||||
] as const;
|
||||
beforeAll(async () => {
|
||||
const module = await Test.createTestingModule({
|
||||
controllers: [ApprovalsController, DepartmentTasksController],
|
||||
providers: [{provide: PrismaService, useValue: prisma}, RolesGuard],
|
||||
}).overrideGuard(JwtAuthGuard).useValue({canActivate(context: any) {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
if (!req.headers.authorization) return false;
|
||||
req.user = {id: 'test-admin', role: req.headers.authorization};
|
||||
return true;
|
||||
}}).compile();
|
||||
app = module.createNestApplication();
|
||||
await app.init();
|
||||
dbAccess.mockClear();
|
||||
});
|
||||
beforeEach(() => dbAccess.mockClear());
|
||||
afterAll(async () => { if (app) await app.close(); });
|
||||
it.each(routes)('%s %s returns explicit 410 for authorized callers before database access', async (method, path) => {
|
||||
const response = await request(app.getHttpServer())[method](path)
|
||||
.set('Authorization', 'Admin').send({decision:'APPROVED',status:'DONE'}).expect(410);
|
||||
expect(response.body.message).toContain('retired');
|
||||
expect(dbAccess).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(routes)('%s %s retains anonymous and customer authorization guards', async (method, path) => {
|
||||
await request(app.getHttpServer())[method](path).send({}).expect(403);
|
||||
await request(app.getHttpServer())[method](path).set('Authorization','CUSTOMER').send({}).expect(403);
|
||||
expect(dbAccess).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import { RouterUsageModule } from './router-usage/router-usage.module';
|
||||
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";
|
||||
@@ -37,11 +39,16 @@ import { DoctorsModule } from "./doctors/doctors.module";
|
||||
import { FaqModule } from "./faq/faq.module";
|
||||
import { MenuModule } from "./menu/menu.module";
|
||||
import { RevalidationModule } from "./common/revalidation/revalidation.module";
|
||||
import { OrchestrationModule } from "./orchestration/orchestration.module";
|
||||
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
RouterUsageModule,
|
||||
// Deny-all registration: no request identity or runtime credentials are accepted yet.
|
||||
HermesManagementModule.register({origin:'http://canina-hermes:9119',token:async()=>''}),
|
||||
OrchestrationModule,
|
||||
SupportChatModule,
|
||||
RevalidationModule,
|
||||
SmsModule,
|
||||
|
||||
@@ -50,7 +50,8 @@ describe("BlogsService", () => {
|
||||
expect(result.data).toEqual(blogs);
|
||||
expect(result.meta.total).toBe(1);
|
||||
const query = mockPrisma.blog.findMany.mock.calls[0][0];
|
||||
expect(query.include.author).toBeUndefined();
|
||||
expect(query.include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
expect(query.orderBy).toEqual([{ publishedAt: "desc" }, { id: "asc" }]);
|
||||
});
|
||||
|
||||
it("should filter by categorySlug and search term", async () => {
|
||||
@@ -69,7 +70,19 @@ describe("BlogsService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("selects the minimal public author identity for list results", async () => {
|
||||
mockPrisma.blog.findMany.mockResolvedValue([]); mockPrisma.blog.count.mockResolvedValue(0);
|
||||
await service.findAll({});
|
||||
expect(mockPrisma.blog.findMany.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
describe("findHomepage", () => {
|
||||
it("selects the minimal public author identity for homepage results", async () => {
|
||||
mockPrisma.blog.findMany.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
|
||||
await service.findHomepage();
|
||||
for (const call of mockPrisma.blog.findMany.mock.calls.slice(0, 2)) expect(call[0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
it("should return selected blogs if showOnHome posts exist", async () => {
|
||||
const selected = [{ id: "b1", title: "Hero Blog", showOnHome: true }];
|
||||
mockPrisma.blog.findMany.mockResolvedValueOnce(selected);
|
||||
@@ -92,6 +105,12 @@ describe("BlogsService", () => {
|
||||
});
|
||||
|
||||
describe("findOneBySlug", () => {
|
||||
it("selects the minimal public author identity for detail results", async () => {
|
||||
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
||||
await expect(service.findOneBySlug("missing")).rejects.toThrow(NotFoundException);
|
||||
expect(mockPrisma.blog.findFirst.mock.calls[0][0].include.author).toEqual({ select: { id: true, firstName: true, lastName: true } });
|
||||
});
|
||||
|
||||
it("should throw NotFoundException if slug is empty or blog not found", async () => {
|
||||
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
||||
await expect(service.findOneBySlug("unknown-slug")).rejects.toThrow(
|
||||
|
||||
@@ -64,10 +64,16 @@ export class BlogsService {
|
||||
where: whereClause,
|
||||
skip,
|
||||
take: Number(limit),
|
||||
orderBy: {
|
||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||
},
|
||||
{ id: "asc" },
|
||||
],
|
||||
include: {
|
||||
author: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: {
|
||||
select: { id: true, name: true, slug: true },
|
||||
},
|
||||
@@ -105,8 +111,11 @@ export class BlogsService {
|
||||
const selectedBlogs = await this.prisma.blog.findMany({
|
||||
where: { ...baseWhere, showOnHome: true },
|
||||
take: 4,
|
||||
orderBy: { publishedAt: "desc" },
|
||||
orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
|
||||
include: {
|
||||
author: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: { select: { id: true, name: true, slug: true } },
|
||||
tags: { select: { id: true, name: true, slug: true } },
|
||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||
@@ -121,8 +130,11 @@ export class BlogsService {
|
||||
const newestBlogs = await this.prisma.blog.findMany({
|
||||
where: baseWhere,
|
||||
take: 4,
|
||||
orderBy: { publishedAt: "desc" },
|
||||
orderBy: [{ publishedAt: "desc" }, { id: "asc" }],
|
||||
include: {
|
||||
author: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
category: { select: { id: true, name: true, slug: true } },
|
||||
tags: { select: { id: true, name: true, slug: true } },
|
||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||
@@ -158,6 +170,7 @@ export class BlogsService {
|
||||
],
|
||||
},
|
||||
include: {
|
||||
author: { select: { id: true, firstName: true, lastName: true } },
|
||||
category: {
|
||||
select: { id: true, name: true, slug: true },
|
||||
},
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { CallHandler, ExecutionContext } from "@nestjs/common";
|
||||
import { of, lastValueFrom } from "rxjs";
|
||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
describe("AdminRevalidationInterceptor", () => {
|
||||
const revalidation = { revalidate: jest.fn().mockResolvedValue(true) } as unknown as RevalidationService;
|
||||
const interceptor = new AdminRevalidationInterceptor(revalidation);
|
||||
const next = { handle: () => of({ ok: true }) } as CallHandler;
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
function context(method: string, url: string): ExecutionContext {
|
||||
return { switchToHttp: () => ({ getRequest: () => ({ method, originalUrl: url }) }) } as unknown as ExecutionContext;
|
||||
}
|
||||
|
||||
it("invalidates blog list and detail after an admin blog mutation", async () => {
|
||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/blogs/blog-1"), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(
|
||||
expect.arrayContaining(["blogs", "blog-categories", "blog-tags", "home-data"]),
|
||||
expect.arrayContaining(["/", "/blog"]),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/api/admin/products/p1", "products"],
|
||||
["/api/admin/categories/c1", "categories"],
|
||||
["/api/admin/wiki/glucosamine", "wiki"],
|
||||
["/api/admin/settings", "settings"],
|
||||
["/api/admin/cms/hero-banners/b1", "banners"],
|
||||
["/api/admin/cms/vet-testimonials/t1", "testimonials"],
|
||||
["/api/admin/reviews/r1", "products"],
|
||||
["/api/admin/media/m1", "products"],
|
||||
])("maps %s mutations to %s cache invalidation", async (url, expectedTag) => {
|
||||
await lastValueFrom(interceptor.intercept(context("DELETE", url), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
||||
});
|
||||
|
||||
it("does not invalidate cache for reads or internal-only admin CRUD", async () => {
|
||||
await lastValueFrom(interceptor.intercept(context("GET", "/api/admin/blogs"), next));
|
||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/users/u1"), next));
|
||||
expect(revalidation.revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/api/banners/banner-1", "banners"],
|
||||
["/api/menu/menu-1", "menu"],
|
||||
["/api/videos/video-1", "videos"],
|
||||
["/api/testimonials/testimonial-1", "testimonials"],
|
||||
["/api/faq/faq-1", "faq"],
|
||||
["/api/ingredients/ingredient-1", "ingredients"],
|
||||
["/api/doctors/doctor-1", "doctors"],
|
||||
["/api/settings/seo", "seo-config"],
|
||||
["/api/settings/ui-texts/HERO_TITLE", "ui-texts"],
|
||||
["/api/contact/info", "settings"],
|
||||
["/api/smart-advisor/rules/rule-1", "smart-advisor"],
|
||||
])("maps storefront mutation %s to %s cache invalidation", async (url, expectedTag) => {
|
||||
await lastValueFrom(interceptor.intercept(context("PATCH", url), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
|
||||
import { Observable, tap } from "rxjs";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
type Target = { tags: string[]; paths: string[] };
|
||||
|
||||
const TARGETS: Array<{ pattern: RegExp; target: Target }> = [
|
||||
{ pattern: /^\/api\/banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/menu(?:\/|$)/, target: { tags: ["menu", "settings"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/videos(?:\/|$)/, target: { tags: ["videos", "home-data"], paths: ["/", "/videos"] } },
|
||||
{ pattern: /^\/api\/testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/faq(?:\/|$)/, target: { tags: ["faq"], paths: ["/faq"] } },
|
||||
{ pattern: /^\/api\/ingredients(?:\/|$)/, target: { tags: ["ingredients", "products", "wiki"], paths: ["/shop", "/wiki"] } },
|
||||
{ pattern: /^\/api\/doctors(?:\/|$)/, target: { tags: ["doctors", "settings"], paths: ["/contact"] } },
|
||||
{ pattern: /^\/api\/settings\/seo(?:\/|$)/, target: { tags: ["seo-config", "settings"], paths: ["/", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/settings\/(?:ui-texts|system|financial)(?:\/|$)/, target: { tags: ["ui-texts", "settings", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/contact\/info(?:\/|$)/, target: { tags: ["settings"], paths: ["/contact", "/"] } },
|
||||
{ pattern: /^\/api\/smart-advisor\/rules(?:\/|$)/, target: { tags: ["smart-advisor", "products"], paths: ["/smart-advisor"] } },
|
||||
{ pattern: /^\/api\/admin\/blogs(?:\/|$)/, target: { tags: ["blogs", "blog-categories", "blog-tags", "home-data"], paths: ["/", "/blog", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/categories(?:\/|$)/, target: { tags: ["products", "categories", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/wiki(?:\/|$)/, target: { tags: ["wiki", "scientific-terms"], paths: ["/wiki", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/(?:settings|pricing)(?:\/|$)/, target: { tags: ["settings", "ui-texts", "seo-config", "products", "home-data"], paths: ["/", "/shop"] } },
|
||||
{ pattern: /^\/api\/admin\/cms\/hero-banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/admin\/cms\/vet-testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/admin\/reviews(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop"] } },
|
||||
{ pattern: /^\/api\/admin\/media(?:\/|$)/, target: { tags: ["products", "blogs", "wiki", "home-data"], paths: ["/", "/shop", "/blog", "/wiki"] } },
|
||||
{ pattern: /^\/api\/admin\/products(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class AdminRevalidationInterceptor implements NestInterceptor {
|
||||
constructor(private readonly revalidation: RevalidationService) {}
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
const request = context.switchToHttp().getRequest<{ method?: string; originalUrl?: string; url?: string }>();
|
||||
const method = (request.method || "GET").toUpperCase();
|
||||
const url = (request.originalUrl || request.url || "").split("?")[0];
|
||||
const target = method === "GET" || method === "HEAD" || method === "OPTIONS"
|
||||
? undefined
|
||||
: TARGETS.find((entry) => entry.pattern.test(url))?.target;
|
||||
|
||||
return next.handle().pipe(
|
||||
tap(() => {
|
||||
if (target) void this.revalidation.revalidate(target.tags, target.paths);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Global, Module } from "@nestjs/common";
|
||||
import { APP_INTERCEPTOR } from "@nestjs/core";
|
||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [RevalidationService],
|
||||
providers: [RevalidationService, { provide: APP_INTERCEPTOR, useClass: AdminRevalidationInterceptor }],
|
||||
exports: [RevalidationService],
|
||||
})
|
||||
export class RevalidationModule {}
|
||||
@@ -110,4 +110,22 @@ describe("RevalidationService", () => {
|
||||
expect(pathSpy).toHaveBeenCalledWith("/shop/ART-100");
|
||||
});
|
||||
});
|
||||
|
||||
describe("revalidate batch", () => {
|
||||
it("should send deduplicated tags and paths in one request", async () => {
|
||||
const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({ ok: true, status: 200 } as any);
|
||||
|
||||
const result = await service.revalidate(["blogs", "blogs"], ["/blog", "/blog"]);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
"http://frontend_mock:8080/api/revalidate",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({ tags: ["blogs"], paths: ["/blog"] }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -31,6 +31,32 @@ export class RevalidationService {
|
||||
return secret;
|
||||
}
|
||||
|
||||
async revalidate(tags: string[] = [], paths: string[] = []): Promise<boolean> {
|
||||
const cleanTags = [...new Set(tags.filter(Boolean))];
|
||||
const cleanPaths = [...new Set(paths.filter((path) => path.startsWith("/")))];
|
||||
if (!cleanTags.length && !cleanPaths.length) return true;
|
||||
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-revalidate-secret": this.secret,
|
||||
},
|
||||
body: JSON.stringify({ tags: cleanTags, paths: cleanPaths }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
this.logger.warn(`Failed to revalidate cache batch: ${res.status} ${res.statusText}`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
this.logger.debug(`Batch revalidation skipped or frontend offline: ${err?.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async revalidateTag(tag: string): Promise<boolean> {
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { HermesIntegrationService } from './hermes-integration.service';
|
||||
import { HermesAdapter } from './hermes.adapter';
|
||||
describe('backend-owned runtime authorization', () => {
|
||||
const ctx = { subject: 'admin', profiles: ['seo'] };
|
||||
const make = (allow = true, enabled = false) => {
|
||||
const fetcher = jest
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({ id: 'j', profile: 'seo', enabled: false }),
|
||||
),
|
||||
);
|
||||
const authorize = jest.fn().mockResolvedValue(allow);
|
||||
return {
|
||||
fetcher,
|
||||
authorize,
|
||||
s: new HermesIntegrationService(
|
||||
new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
},
|
||||
fetcher,
|
||||
),
|
||||
{ authorize },
|
||||
enabled,
|
||||
),
|
||||
};
|
||||
};
|
||||
it('denies missing principal, missing profile, denied policy before upstream IO', async () => {
|
||||
const { s, fetcher } = make(false);
|
||||
await expect(s.pauseCron(ctx, 'seo', 'j')).rejects.toMatchObject({
|
||||
code: 'FORBIDDEN',
|
||||
});
|
||||
await expect(
|
||||
s.pauseCron({ ...ctx, subject: '' }, 'seo', 'j'),
|
||||
).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
await expect(s.pauseCron(ctx, 'dev', 'j')).rejects.toMatchObject({
|
||||
code: 'FORBIDDEN',
|
||||
});
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
it('allows authorized pause but leaves resume disabled by default', async () => {
|
||||
const { s, fetcher, authorize } = make();
|
||||
await s.pauseCron(ctx, 'seo', 'j');
|
||||
expect(authorize).toHaveBeenCalledWith(ctx, 'cron.pause', 'seo');
|
||||
await expect(s.resumeCron(ctx, 'seo', 'j')).rejects.toMatchObject({
|
||||
code: 'FORBIDDEN',
|
||||
});
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('fails closed on all execution and never forwards arbitrary events or RPC', async () => {
|
||||
const { s, fetcher } = make();
|
||||
expect(s.capabilities()).toMatchObject({
|
||||
chat: false,
|
||||
control: false,
|
||||
eventDispatch: false,
|
||||
cronResume: false,
|
||||
});
|
||||
await expect(s.chat(ctx, 'seo', 'hello')).rejects.toMatchObject({
|
||||
code: 'UNSUPPORTED',
|
||||
});
|
||||
await expect(s.control(ctx, 'seo', 'interrupt')).rejects.toMatchObject({
|
||||
code: 'UNSUPPORTED',
|
||||
});
|
||||
await expect(
|
||||
s.dispatchEvent(ctx, 'seo', { type: 'order.created' }),
|
||||
).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
it('fails closed when authorization provider throws', async () => {
|
||||
const a = new HermesAdapter({
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
});
|
||||
const s = new HermesIntegrationService(a, {
|
||||
authorize: () => Promise.reject(new Error('private')),
|
||||
});
|
||||
await expect(s.health(ctx)).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
});
|
||||
});
|
||||
|
||||
it('checks every read capability and filters the global profile roster', async () => {
|
||||
const fetcher = jest.fn().mockImplementation((input: URL) => {
|
||||
const payloads: Record<string, unknown> = {
|
||||
'/api/health': {
|
||||
ok: true,
|
||||
version: 'x',
|
||||
commit: 'x',
|
||||
auth_required: true,
|
||||
},
|
||||
'/api/status': {
|
||||
version: 'x',
|
||||
gateway_running: false,
|
||||
gateway_state: null,
|
||||
overall: 'degraded',
|
||||
active_agents: 0,
|
||||
},
|
||||
'/api/profiles': {
|
||||
profiles: [
|
||||
{ name: 'seo', is_default: false, gateway_running: false },
|
||||
{ name: 'dev', is_default: false, gateway_running: false },
|
||||
],
|
||||
},
|
||||
'/api/model/info': {
|
||||
model: 'm',
|
||||
provider: 'p',
|
||||
effective_context_length: 1,
|
||||
},
|
||||
'/api/model/options': { providers: [] },
|
||||
'/api/analytics/usage': {
|
||||
period_days: 30,
|
||||
totals: {
|
||||
total_input: 0,
|
||||
total_output: 0,
|
||||
total_sessions: 0,
|
||||
total_estimated_cost: 0,
|
||||
},
|
||||
},
|
||||
'/api/sessions': { sessions: [], total: 0 },
|
||||
'/api/cron/jobs': [],
|
||||
};
|
||||
return Promise.resolve(
|
||||
new Response(JSON.stringify(payloads[input.pathname])),
|
||||
);
|
||||
});
|
||||
const authorize = jest.fn().mockResolvedValue(true);
|
||||
const s = new HermesIntegrationService(
|
||||
new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
},
|
||||
fetcher,
|
||||
),
|
||||
{ authorize },
|
||||
);
|
||||
const p = { subject: 'verified', profiles: ['seo'] };
|
||||
await s.health(p);
|
||||
await s.status(p, 'seo');
|
||||
expect(await s.profiles(p)).toHaveLength(1);
|
||||
await s.modelInfo(p, 'seo');
|
||||
await s.modelOptions(p, 'seo');
|
||||
await s.usage(p, 'seo');
|
||||
await s.sessions(p, 'seo');
|
||||
await s.crons(p, 'seo');
|
||||
expect(authorize).toHaveBeenCalledTimes(8);
|
||||
expect(authorize.mock.calls.every((c) => c[1] === 'runtime.read')).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import { HermesAdapter, HermesError, Json } from './hermes.adapter';
|
||||
/** Context MUST be constructed from verified backend identity, never request bodies. */
|
||||
export interface RuntimePrincipal {
|
||||
subject: string;
|
||||
profiles: readonly string[];
|
||||
}
|
||||
export type RuntimePermission =
|
||||
| 'runtime.read'
|
||||
| 'cron.pause'
|
||||
| 'cron.resume'
|
||||
| 'chat'
|
||||
| 'control'
|
||||
| 'event.dispatch';
|
||||
export interface RuntimeAuthorizer {
|
||||
authorize(
|
||||
principal: RuntimePrincipal,
|
||||
permission: RuntimePermission,
|
||||
profile?: string,
|
||||
): Promise<boolean>;
|
||||
}
|
||||
/** No controller or socket is registered: only the backend gatekeeper can call this seam. */
|
||||
export class HermesIntegrationService {
|
||||
constructor(
|
||||
private readonly adapter: HermesAdapter,
|
||||
private readonly policy: RuntimeAuthorizer,
|
||||
private readonly resumeEnabled = false,
|
||||
) {}
|
||||
capabilities() {
|
||||
return {
|
||||
inventory: true,
|
||||
cronPause: true,
|
||||
cronResume: this.resumeEnabled,
|
||||
chat: false,
|
||||
control: false,
|
||||
eventDispatch: false,
|
||||
} as const;
|
||||
}
|
||||
private async check(
|
||||
principal: RuntimePrincipal,
|
||||
permission: RuntimePermission,
|
||||
profile?: string,
|
||||
): Promise<void> {
|
||||
if (
|
||||
!principal?.subject ||
|
||||
!Array.isArray(principal.profiles) ||
|
||||
(profile && !principal.profiles.includes(profile))
|
||||
)
|
||||
throw new HermesError('FORBIDDEN');
|
||||
try {
|
||||
if (
|
||||
(await this.policy.authorize(principal, permission, profile)) !== true
|
||||
)
|
||||
throw new HermesError('FORBIDDEN');
|
||||
} catch {
|
||||
throw new HermesError('FORBIDDEN');
|
||||
}
|
||||
}
|
||||
async health(p: RuntimePrincipal) {
|
||||
await this.check(p, 'runtime.read');
|
||||
return this.adapter.health();
|
||||
}
|
||||
async status(p: RuntimePrincipal, profile: string) {
|
||||
await this.check(p, 'runtime.read', profile);
|
||||
return this.adapter.status(profile);
|
||||
}
|
||||
async profiles(p: RuntimePrincipal) {
|
||||
await this.check(p, 'runtime.read');
|
||||
return (await this.adapter.profiles()).filter(
|
||||
(r) => typeof r.name === 'string' && p.profiles.includes(r.name),
|
||||
);
|
||||
}
|
||||
async modelInfo(p: RuntimePrincipal, profile: string) {
|
||||
await this.check(p, 'runtime.read', profile);
|
||||
return this.adapter.modelInfo(profile);
|
||||
}
|
||||
async modelOptions(p: RuntimePrincipal, profile: string) {
|
||||
await this.check(p, 'runtime.read', profile);
|
||||
return this.adapter.modelOptions(profile);
|
||||
}
|
||||
async usage(p: RuntimePrincipal, profile: string, days = 30) {
|
||||
await this.check(p, 'runtime.read', profile);
|
||||
return this.adapter.usage(profile, days);
|
||||
}
|
||||
async sessions(p: RuntimePrincipal, profile: string, limit = 20, offset = 0) {
|
||||
await this.check(p, 'runtime.read', profile);
|
||||
return this.adapter.sessions(profile, limit, offset);
|
||||
}
|
||||
async crons(p: RuntimePrincipal, profile: string) {
|
||||
await this.check(p, 'runtime.read', profile);
|
||||
return this.adapter.crons(profile);
|
||||
}
|
||||
async pauseCron(p: RuntimePrincipal, profile: string, id: string) {
|
||||
await this.check(p, 'cron.pause', profile);
|
||||
return this.adapter.pauseCron(profile, id);
|
||||
}
|
||||
async resumeCron(p: RuntimePrincipal, profile: string, id: string) {
|
||||
await this.check(p, 'cron.resume', profile);
|
||||
if (!this.resumeEnabled) throw new HermesError('FORBIDDEN');
|
||||
return this.adapter.resumeCron(profile, id);
|
||||
}
|
||||
async chat(
|
||||
p: RuntimePrincipal,
|
||||
profile: string,
|
||||
_text: string,
|
||||
): Promise<never> {
|
||||
await this.check(p, 'chat', profile);
|
||||
throw new HermesError('UNSUPPORTED');
|
||||
}
|
||||
async control(
|
||||
p: RuntimePrincipal,
|
||||
profile: string,
|
||||
_command: 'interrupt',
|
||||
): Promise<never> {
|
||||
await this.check(p, 'control', profile);
|
||||
throw new HermesError('UNSUPPORTED');
|
||||
}
|
||||
/** Disabled independently of policy: no unreviewed event may become an agent prompt. */
|
||||
async dispatchEvent(
|
||||
p: RuntimePrincipal,
|
||||
profile: string,
|
||||
_event: Json,
|
||||
): Promise<never> {
|
||||
await this.check(p, 'event.dispatch', profile);
|
||||
throw new HermesError('FORBIDDEN');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { HermesManagementModule } from './hermes-management.module';
|
||||
import { HermesIntegrationService } from './hermes-integration.service';
|
||||
it('requires explicit registration and denies by default without publishing controllers', async () => {
|
||||
const module = await Test.createTestingModule({
|
||||
imports: [
|
||||
HermesManagementModule.register({
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
}),
|
||||
],
|
||||
}).compile();
|
||||
const service = module.get(HermesIntegrationService);
|
||||
await expect(
|
||||
service.health({ subject: 'admin', profiles: [] }),
|
||||
).rejects.toMatchObject({ code: 'FORBIDDEN' });
|
||||
await module.close();
|
||||
});
|
||||
|
||||
it('registers backend credential broker without acquiring credentials before policy authorization', async () => {
|
||||
const credentials=jest.fn().mockResolvedValue({username:'backend',password:'test-only'});
|
||||
const module=await Test.createTestingModule({imports:[HermesManagementModule.registerAuthenticated(credentials)]}).compile();
|
||||
await expect(module.get(HermesIntegrationService).health({subject:'admin',profiles:[]})).rejects.toMatchObject({code:'FORBIDDEN'});
|
||||
expect(credentials).not.toHaveBeenCalled();
|
||||
await module.close();
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { DynamicModule, Module } from '@nestjs/common';
|
||||
import { HermesSessionBroker } from './hermes-session-broker';
|
||||
import { HermesAdapter, HermesConfig } from './hermes.adapter';
|
||||
import {
|
||||
HermesIntegrationService,
|
||||
RuntimeAuthorizer,
|
||||
} from './hermes-integration.service';
|
||||
@Module({})
|
||||
export class HermesManagementModule {
|
||||
static registerAuthenticated(
|
||||
credentials: () => Promise<{username:string;password:string}>,
|
||||
policy: RuntimeAuthorizer = {authorize: async () => false},
|
||||
): DynamicModule {
|
||||
const broker = new HermesSessionBroker(credentials);
|
||||
return this.register({origin:'http://canina-hermes:9119',token:()=>broker.token()},policy);
|
||||
}
|
||||
|
||||
static register(
|
||||
config: HermesConfig,
|
||||
policy: RuntimeAuthorizer = { authorize: () => Promise.resolve(false) },
|
||||
): DynamicModule {
|
||||
return {
|
||||
module: HermesManagementModule,
|
||||
providers: [
|
||||
{ provide: HermesAdapter, useFactory: () => new HermesAdapter(config) },
|
||||
{
|
||||
provide: HermesIntegrationService,
|
||||
useFactory: (adapter: HermesAdapter) =>
|
||||
new HermesIntegrationService(adapter, policy, false),
|
||||
inject: [HermesAdapter],
|
||||
},
|
||||
],
|
||||
exports: [HermesIntegrationService],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { afterEach } from '@jest/globals';
|
||||
import { HermesSessionBroker } from './hermes-session-broker';
|
||||
const credentials = async () => ({username:'backend',password:'test-only'});
|
||||
const response = () => new Response('{"ok":true}', {headers:{'set-cookie':'hermes_session_at=verified-test-token; Max-Age=60; Path=/; HttpOnly'}});
|
||||
describe('server-only Hermes session broker',()=>{
|
||||
afterEach(()=>{jest.useRealTimers();});
|
||||
it('renews expired cached access without retaining the refresh cookie',async()=>{
|
||||
jest.useFakeTimers();
|
||||
const fetcher=jest.fn().mockImplementation(async()=>response());
|
||||
const broker=new HermesSessionBroker(credentials,fetcher);
|
||||
await broker.token();
|
||||
await jest.advanceTimersByTimeAsync(51000);
|
||||
await broker.token();
|
||||
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it('bounds credential waits and releases the pending login after timeout',async()=>{
|
||||
jest.useFakeTimers();
|
||||
const load=jest.fn().mockImplementationOnce(()=>new Promise(()=>{})).mockImplementation(credentials);
|
||||
const broker=new HermesSessionBroker(load,jest.fn().mockImplementation(async()=>response()));
|
||||
const result=expect(broker.token()).rejects.toMatchObject({message:'Hermes unavailable'});
|
||||
await jest.advanceTimersByTimeAsync(5001);await result;
|
||||
expect(await broker.token()).toBe('verified-test-token');
|
||||
});
|
||||
it('rejects oversized response bodies and short cookie lifetimes',async()=>{
|
||||
for(const res of [new Response('x'.repeat(4097)),new Response('{"ok":true}',{headers:{'set-cookie':'hermes_session_at=token; Max-Age=1; Path=/'}})]){
|
||||
await expect(new HermesSessionBroker(credentials,jest.fn().mockResolvedValue(res)).token()).rejects.toMatchObject({message:'Hermes auth_required'});
|
||||
}
|
||||
});
|
||||
|
||||
it('coalesces login, caches only access token and uses installed password-login contract',async()=>{
|
||||
const fetcher=jest.fn().mockImplementation(async()=>response());
|
||||
const broker=new HermesSessionBroker(credentials,fetcher);
|
||||
expect(await Promise.all([broker.token(),broker.token()])).toEqual(['verified-test-token','verified-test-token']);
|
||||
expect(await broker.token()).toBe('verified-test-token');
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
const [url,options]=fetcher.mock.calls[0];
|
||||
expect(url).toBe('http://canina-hermes:9119/auth/password-login');
|
||||
expect(JSON.parse(options.body)).toEqual({provider:'basic',username:'backend',password:'test-only'});
|
||||
expect(options.redirect).toBe('error');
|
||||
});
|
||||
it('fails closed without echoing credentials, response bodies or provider errors',async()=>{
|
||||
for(const result of [new Response('private secret',{status:401}),new Response('{"ok":true}'),new Response('{"ok":false}',{headers:{'set-cookie':'hermes_session_at=bad; Max-Age=60'}})]){
|
||||
const broker=new HermesSessionBroker(credentials,jest.fn().mockResolvedValue(result));
|
||||
await expect(broker.token()).rejects.toMatchObject({message:'Hermes auth_required'});
|
||||
}
|
||||
});
|
||||
it('does not cache failures and permits a later successful login',async()=>{
|
||||
const fetcher=jest.fn().mockRejectedValueOnce(new Error('sensitive upstream')).mockImplementationOnce(async()=>response());
|
||||
const broker=new HermesSessionBroker(credentials,fetcher);
|
||||
await expect(broker.token()).rejects.toMatchObject({message:'Hermes unavailable'});
|
||||
expect(await broker.token()).toBe('verified-test-token');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { HermesError } from './hermes.adapter';
|
||||
export class HermesSessionBroker {
|
||||
private cached: {token:string;until:number}|undefined;
|
||||
private pending: Promise<string>|undefined;
|
||||
constructor(private readonly credentials:()=>Promise<{username:string;password:string}>,private readonly fetcher:typeof fetch=fetch) {}
|
||||
token():Promise<string>{
|
||||
if(this.cached && this.cached.until>Date.now()) return Promise.resolve(this.cached.token);
|
||||
if(this.pending) return this.pending;
|
||||
this.pending=this.login().finally(()=>{this.pending=undefined;});
|
||||
return this.pending;
|
||||
}
|
||||
private async login():Promise<string>{
|
||||
const controller=new AbortController();
|
||||
const timer=setTimeout(()=>controller.abort(),5000);
|
||||
try{
|
||||
const creds=await Promise.race([this.credentials(),new Promise<never>((_,reject)=>controller.signal.addEventListener('abort',()=>reject(new HermesError('UNAVAILABLE')),{once:true}))]);
|
||||
if(!creds.username || !creds.password) throw new HermesError('AUTH_REQUIRED');
|
||||
const response=await this.fetcher('http://canina-hermes:9119/auth/password-login',{method:'POST',redirect:'error',signal:controller.signal,headers:{'Content-Type':'application/json'},body:JSON.stringify({provider:'basic',...creds})});
|
||||
if(!response.ok) throw new HermesError('AUTH_REQUIRED');
|
||||
const reader=response.body?.getReader();
|
||||
if(!reader) throw new HermesError('AUTH_REQUIRED');
|
||||
const chunks:Uint8Array[]=[];let size=0;
|
||||
try{for(;;){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>4096)throw new HermesError('AUTH_REQUIRED');chunks.push(value);}}finally{await reader.cancel().catch(()=>undefined);}
|
||||
const body=JSON.parse(Buffer.concat(chunks).toString('utf8')) as {ok?:unknown};
|
||||
const cookies=response.headers.getSetCookie();
|
||||
const cookie=cookies.find(c=>c.startsWith('hermes_session_at='));
|
||||
const token=cookie?.match(/^hermes_session_at=([A-Za-z0-9_.=-]+);/)?.[1];
|
||||
const 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};
|
||||
return token;
|
||||
}catch(error){if(error instanceof HermesError)throw error;throw new HermesError('UNAVAILABLE');}
|
||||
finally{clearTimeout(timer);}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import { HermesAdapter, HermesError } from './hermes.adapter';
|
||||
const health = {
|
||||
ok: true,
|
||||
version: '0.13',
|
||||
commit: 'abc',
|
||||
auth_required: true,
|
||||
};
|
||||
describe('installed Hermes health contract', () => {
|
||||
it('uses pinned internal origin, bearer only server side and strips extra fields', async () => {
|
||||
const fetcher = jest
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({ ...health, token: 'never', home: '/secret' }),
|
||||
),
|
||||
);
|
||||
const adapter = new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('private'),
|
||||
},
|
||||
fetcher,
|
||||
);
|
||||
expect(await adapter.health()).toEqual(health);
|
||||
expect(fetcher.mock.calls[0][0].toString()).toBe(
|
||||
'http://canina-hermes:9119/api/health',
|
||||
);
|
||||
expect(fetcher.mock.calls[0][1].headers.Authorization).toBe(
|
||||
'Bearer private',
|
||||
);
|
||||
expect(fetcher.mock.calls[0][1].redirect).toBe('error');
|
||||
});
|
||||
it('refuses a runtime reporting that authentication is disabled', async () => {
|
||||
const adapter = new HermesAdapter({origin:'http://canina-hermes:9119',token:async()=> 'private'},
|
||||
jest.fn().mockResolvedValue(new Response(JSON.stringify({...health,auth_required:false}))));
|
||||
await expect(adapter.health()).rejects.toMatchObject({code:'AUTH_REQUIRED'});
|
||||
});
|
||||
|
||||
it('fails closed for bad origin, auth errors, malformed contract and oversized bodies', async () => {
|
||||
expect(
|
||||
() =>
|
||||
new HermesAdapter({
|
||||
origin: 'https://evil.test',
|
||||
token: () => Promise.resolve(''),
|
||||
}),
|
||||
).toThrow(HermesError);
|
||||
for (const response of [
|
||||
new Response('private', { status: 401 }),
|
||||
new Response('{}'),
|
||||
new Response('x'.repeat(262145)),
|
||||
]) {
|
||||
const a = new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
},
|
||||
jest.fn().mockResolvedValue(response),
|
||||
);
|
||||
await expect(a.health()).rejects.toBeInstanceOf(HermesError);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('bounded profile-scoped REST inventory', () => {
|
||||
const create = (payload: unknown) => {
|
||||
const fetcher = jest
|
||||
.fn()
|
||||
.mockResolvedValue(new Response(JSON.stringify(payload)));
|
||||
return {
|
||||
a: new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
},
|
||||
fetcher,
|
||||
),
|
||||
fetcher,
|
||||
};
|
||||
};
|
||||
it('projects status, profiles, models and usage without raw paths, prompts or credentials', async () => {
|
||||
expect(
|
||||
await create({
|
||||
version: 'x',
|
||||
gateway_running: false,
|
||||
gateway_state: null,
|
||||
overall: 'degraded',
|
||||
active_agents: 0,
|
||||
}).a.status('seo'),
|
||||
).toEqual({
|
||||
version: 'x',
|
||||
gateway_running: false,
|
||||
gateway_state: null,
|
||||
overall: 'degraded',
|
||||
active_agents: 0,
|
||||
});
|
||||
expect(
|
||||
await create({
|
||||
profiles: [
|
||||
{
|
||||
name: 'seo',
|
||||
is_default: false,
|
||||
gateway_running: false,
|
||||
path: '/private',
|
||||
description: 'token=secret',
|
||||
},
|
||||
],
|
||||
}).a.profiles(),
|
||||
).toEqual([{ name: 'seo', is_default: false, gateway_running: false }]);
|
||||
expect(
|
||||
await create({
|
||||
model: 'm',
|
||||
provider: 'p',
|
||||
effective_context_length: 0,
|
||||
api_key: 'secret',
|
||||
}).a.modelInfo('seo'),
|
||||
).toEqual({ model: 'm', provider: 'p', effective_context_length: 0 });
|
||||
expect(
|
||||
await create({
|
||||
providers: [
|
||||
{ slug: 'p', name: 'Provider', models: ['m'], api_key: 'secret' },
|
||||
],
|
||||
current: { api_key: 'secret' },
|
||||
}).a.modelOptions('seo'),
|
||||
).toEqual([{ slug: 'p', name: 'Provider', models: ['m'] }]);
|
||||
expect(
|
||||
await create({
|
||||
period_days: 7,
|
||||
totals: {
|
||||
total_input: 0,
|
||||
total_output: 2,
|
||||
total_sessions: 1,
|
||||
total_estimated_cost: 0,
|
||||
},
|
||||
tools: { secret: 1 },
|
||||
}).a.usage('seo', 7),
|
||||
).toEqual({
|
||||
period_days: 7,
|
||||
totals: {
|
||||
total_input: 0,
|
||||
total_output: 2,
|
||||
total_sessions: 1,
|
||||
total_estimated_cost: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
it('uses scoped list contract and rejects unbounded queries or profile escape', async () => {
|
||||
const { a, fetcher } = create({
|
||||
sessions: [
|
||||
{
|
||||
id: 's',
|
||||
profile: 'seo',
|
||||
is_active: false,
|
||||
source: 'cron',
|
||||
title: 'secret',
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
storage: {},
|
||||
});
|
||||
expect(await a.sessions('seo', 20, 0)).toEqual({
|
||||
sessions: [{ id: 's', profile: 'seo', is_active: false, source: 'cron' }],
|
||||
total: 1,
|
||||
});
|
||||
expect(fetcher.mock.calls[0][0].pathname).toBe('/api/sessions');
|
||||
expect(fetcher.mock.calls[0][0].searchParams.get('full')).toBe('false');
|
||||
await expect(a.sessions('../escape', 20, 0)).rejects.toThrow();
|
||||
await expect(a.sessions('seo', 101, 0)).rejects.toThrow();
|
||||
await expect(a.usage('seo', 366)).rejects.toThrow();
|
||||
await expect(
|
||||
create({
|
||||
sessions: [],
|
||||
total: 0,
|
||||
storage: { seo: 'corrupt' },
|
||||
}).a.sessions('seo'),
|
||||
).rejects.toThrow();
|
||||
await expect(
|
||||
create({
|
||||
sessions: [
|
||||
{ id: 's', profile: 'dev', source: 'cli', is_active: false },
|
||||
],
|
||||
total: 1,
|
||||
}).a.sessions('seo'),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
it('lists scoped cron array; pause/resume use exact POST routes without triggers', async () => {
|
||||
expect(
|
||||
await create([
|
||||
{ id: 'j', profile: 'seo', enabled: false, prompt: 'secret' },
|
||||
]).a.crons('seo'),
|
||||
).toEqual([{ id: 'j', profile: 'seo', enabled: false }]);
|
||||
const { a, fetcher } = create({ id: 'j', profile: 'seo', enabled: false });
|
||||
expect(await a.pauseCron('seo', 'j')).toEqual({
|
||||
id: 'j',
|
||||
profile: 'seo',
|
||||
enabled: false,
|
||||
});
|
||||
expect(fetcher.mock.calls[0][0].pathname).toBe('/api/cron/jobs/j/pause');
|
||||
expect(fetcher.mock.calls[0][1].method).toBe('POST');
|
||||
const resume = create({ id: 'j', profile: 'seo', enabled: true });
|
||||
await resume.a.resumeCron('seo', 'j');
|
||||
expect(resume.fetcher.mock.calls[0][0].pathname).toBe(
|
||||
'/api/cron/jobs/j/resume',
|
||||
);
|
||||
await expect(a.pauseCron('seo', '../trigger')).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('resource budgets and safe errors', () => {
|
||||
it('does not leak upstream errors or tokens and limits credential waits', async () => {
|
||||
jest.useFakeTimers();
|
||||
const a = new HermesAdapter({
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => new Promise(() => {}),
|
||||
});
|
||||
const result = expect(a.health()).rejects.toMatchObject({
|
||||
code: 'UNAVAILABLE',
|
||||
message: 'Hermes unavailable',
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(5001);
|
||||
await result;
|
||||
jest.useRealTimers();
|
||||
});
|
||||
it('caps concurrency before upstream IO', async () => {
|
||||
const resolvers: ((r: Response) => void)[] = [];
|
||||
const fetcher = jest.fn(
|
||||
() =>
|
||||
new Promise<Response>((r) => {
|
||||
resolvers.push(r);
|
||||
}),
|
||||
);
|
||||
const a = new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('secret'),
|
||||
},
|
||||
fetcher,
|
||||
);
|
||||
const calls = Array.from({ length: 4 }, () => a.health());
|
||||
const denied = expect(a.health()).rejects.toMatchObject({ code: 'LIMIT' });
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
resolvers.forEach((r) => r(new Response(JSON.stringify(health))));
|
||||
await denied;
|
||||
await Promise.all(calls);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
export type Json =
|
||||
| null
|
||||
| boolean
|
||||
| number
|
||||
| string
|
||||
| Json[]
|
||||
| { [key: string]: Json };
|
||||
export type Row = Record<string, Json>;
|
||||
export type HermesErrorCode =
|
||||
| 'CONFIGURATION'
|
||||
| 'AUTH_REQUIRED'
|
||||
| 'UNAVAILABLE'
|
||||
| 'CONTRACT'
|
||||
| 'LIMIT'
|
||||
| 'FORBIDDEN'
|
||||
| 'UNSUPPORTED';
|
||||
export class HermesError extends Error {
|
||||
constructor(readonly code: HermesErrorCode) {
|
||||
super(`Hermes ${code.toLowerCase()}`);
|
||||
}
|
||||
}
|
||||
export interface HermesConfig {
|
||||
origin: string;
|
||||
token: () => Promise<string>;
|
||||
}
|
||||
export interface Health {
|
||||
ok: boolean;
|
||||
version: string;
|
||||
commit: string;
|
||||
auth_required: boolean;
|
||||
}
|
||||
function object(value: unknown): Record<string, unknown> {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value))
|
||||
throw new HermesError('CONTRACT');
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
function fields(
|
||||
value: unknown,
|
||||
schema: Record<string, 'string' | 'boolean' | 'number'>,
|
||||
): Row {
|
||||
const source = object(value);
|
||||
const result: Row = {};
|
||||
for (const [key, type] of Object.entries(schema)) {
|
||||
if (
|
||||
typeof source[key] !== type ||
|
||||
(type === 'number' && !Number.isFinite(source[key]))
|
||||
)
|
||||
throw new HermesError('CONTRACT');
|
||||
result[key] = source[key] as Json;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export class HermesAdapter {
|
||||
private readonly origin: string;
|
||||
private inflight = 0;
|
||||
constructor(
|
||||
private readonly config: HermesConfig,
|
||||
private readonly fetcher: typeof fetch = fetch,
|
||||
) {
|
||||
if (config.origin !== 'http://canina-hermes:9119')
|
||||
throw new HermesError('CONFIGURATION');
|
||||
this.origin = config.origin;
|
||||
}
|
||||
private async request(
|
||||
path: string,
|
||||
profile?: string,
|
||||
method = 'GET',
|
||||
params: Record<string, string> = {},
|
||||
): Promise<unknown> {
|
||||
if (
|
||||
profile !== undefined &&
|
||||
!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(profile)
|
||||
)
|
||||
throw new HermesError('FORBIDDEN');
|
||||
const url = new URL(path, this.origin);
|
||||
if (profile) url.searchParams.set('profile', profile);
|
||||
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||
if (this.inflight >= 4) throw new HermesError('LIMIT');
|
||||
this.inflight++;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), 5000);
|
||||
try {
|
||||
const token = await Promise.race([
|
||||
this.config.token(),
|
||||
new Promise<never>((_, reject) =>
|
||||
controller.signal.addEventListener(
|
||||
'abort',
|
||||
() => reject(new HermesError('UNAVAILABLE')),
|
||||
{ once: true },
|
||||
),
|
||||
),
|
||||
]);
|
||||
if (!token || /[\r\n]/.test(token))
|
||||
throw new HermesError('AUTH_REQUIRED');
|
||||
const response = await this.fetcher(url, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
signal: controller.signal,
|
||||
redirect: 'error',
|
||||
});
|
||||
if ([401, 403].includes(response.status))
|
||||
throw new HermesError('AUTH_REQUIRED');
|
||||
if (response.status === 404) throw new HermesError('UNSUPPORTED');
|
||||
if (!response.ok) throw new HermesError('UNAVAILABLE');
|
||||
if (Number(response.headers.get('content-length')) > 262144)
|
||||
throw new HermesError('LIMIT');
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) throw new HermesError('CONTRACT');
|
||||
let bytes = 0;
|
||||
const chunks: Uint8Array[] = [];
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
bytes += value.byteLength;
|
||||
if (bytes > 262144) throw new HermesError('LIMIT');
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
}
|
||||
return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown;
|
||||
} catch (error) {
|
||||
if (error instanceof HermesError) throw error;
|
||||
throw new HermesError('UNAVAILABLE');
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
this.inflight--;
|
||||
}
|
||||
}
|
||||
async health(): Promise<Health> {
|
||||
const health = fields(await this.request('/api/health'), {
|
||||
ok: 'boolean',
|
||||
version: 'string',
|
||||
commit: 'string',
|
||||
auth_required: 'boolean',
|
||||
}) as unknown as Health;
|
||||
if (!health.auth_required) throw new HermesError('AUTH_REQUIRED');
|
||||
return health;
|
||||
}
|
||||
async status(profile: string): Promise<Row> {
|
||||
const raw = object(await this.request('/api/status', profile));
|
||||
const row = fields(raw, {
|
||||
version: 'string',
|
||||
gateway_running: 'boolean',
|
||||
overall: 'string',
|
||||
active_agents: 'number',
|
||||
});
|
||||
if (raw.gateway_state !== null && typeof raw.gateway_state !== 'string')
|
||||
throw new HermesError('CONTRACT');
|
||||
return { ...row, gateway_state: raw.gateway_state as Json };
|
||||
}
|
||||
async profiles(): Promise<Row[]> {
|
||||
return list(object(await this.request('/api/profiles')).profiles).map((r) =>
|
||||
fields(r, {
|
||||
name: 'string',
|
||||
is_default: 'boolean',
|
||||
gateway_running: 'boolean',
|
||||
}),
|
||||
);
|
||||
}
|
||||
async modelInfo(profile: string): Promise<Row> {
|
||||
return fields(await this.request('/api/model/info', profile), {
|
||||
model: 'string',
|
||||
provider: 'string',
|
||||
effective_context_length: 'number',
|
||||
});
|
||||
}
|
||||
async modelOptions(profile: string): Promise<Row[]> {
|
||||
return list(
|
||||
object(await this.request('/api/model/options', profile)).providers,
|
||||
).map((r) => {
|
||||
const row = fields(r, { slug: 'string', name: 'string' });
|
||||
const models = list(object(r).models);
|
||||
if (models.some((m) => typeof m !== 'string'))
|
||||
throw new HermesError('CONTRACT');
|
||||
return { ...row, models: models as string[] };
|
||||
});
|
||||
}
|
||||
async usage(profile: string, days = 30): Promise<Row> {
|
||||
bound(days, 1, 365);
|
||||
const raw = object(
|
||||
await this.request('/api/analytics/usage', profile, 'GET', {
|
||||
days: String(days),
|
||||
}),
|
||||
);
|
||||
return {
|
||||
...fields(raw, { period_days: 'number' }),
|
||||
totals: fields(raw.totals, {
|
||||
total_input: 'number',
|
||||
total_output: 'number',
|
||||
total_sessions: 'number',
|
||||
total_estimated_cost: 'number',
|
||||
}),
|
||||
};
|
||||
}
|
||||
async sessions(profile: string, limit = 20, offset = 0): Promise<Row> {
|
||||
bound(limit, 1, 100);
|
||||
bound(offset, 0, 10000);
|
||||
const raw = object(
|
||||
await this.request('/api/sessions', profile, 'GET', {
|
||||
limit: String(limit),
|
||||
offset: String(offset),
|
||||
full: 'false',
|
||||
order: 'recent',
|
||||
}),
|
||||
);
|
||||
if (raw.storage && Object.keys(object(raw.storage)).length)
|
||||
throw new HermesError('UNAVAILABLE');
|
||||
const rows = list(raw.sessions).map((r) =>
|
||||
scoped(r, profile, {
|
||||
id: 'string',
|
||||
profile: 'string',
|
||||
source: 'string',
|
||||
is_active: 'boolean',
|
||||
}),
|
||||
);
|
||||
return { ...fields(raw, { total: 'number' }), sessions: rows };
|
||||
}
|
||||
async crons(profile: string): Promise<Row[]> {
|
||||
return list(await this.request('/api/cron/jobs', profile)).map((r) =>
|
||||
scoped(r, profile, {
|
||||
id: 'string',
|
||||
profile: 'string',
|
||||
enabled: 'boolean',
|
||||
}),
|
||||
);
|
||||
}
|
||||
private async cron(
|
||||
profile: string,
|
||||
id: string,
|
||||
action: 'pause' | 'resume',
|
||||
): Promise<Row> {
|
||||
if (!/^[a-zA-Z0-9_-]{1,128}$/.test(id)) throw new HermesError('FORBIDDEN');
|
||||
return scoped(
|
||||
await this.request(`/api/cron/jobs/${id}/${action}`, profile, 'POST'),
|
||||
profile,
|
||||
{ id: 'string', profile: 'string', enabled: 'boolean' },
|
||||
);
|
||||
}
|
||||
pauseCron(profile: string, id: string): Promise<Row> {
|
||||
return this.cron(profile, id, 'pause');
|
||||
}
|
||||
resumeCron(profile: string, id: string): Promise<Row> {
|
||||
return this.cron(profile, id, 'resume');
|
||||
}
|
||||
}
|
||||
|
||||
function list(value: unknown): unknown[] {
|
||||
if (!Array.isArray(value) || value.length > 1000)
|
||||
throw new HermesError('CONTRACT');
|
||||
return value;
|
||||
}
|
||||
function bound(value: number, min: number, max: number): void {
|
||||
if (!Number.isInteger(value) || value < min || value > max)
|
||||
throw new HermesError('LIMIT');
|
||||
}
|
||||
function scoped(
|
||||
value: unknown,
|
||||
profile: string,
|
||||
schema: Record<string, 'string' | 'boolean' | 'number'>,
|
||||
): Row {
|
||||
const row = fields(value, schema);
|
||||
if (row.profile !== profile) throw new HermesError('FORBIDDEN');
|
||||
return row;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { createServer } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { HermesAdapter } from './hermes.adapter';
|
||||
it('exercises bounded HTTP transport against an isolated server', async () => {
|
||||
const seen: string[] = [];
|
||||
const server = createServer((req, res) => {
|
||||
seen.push(`${req.method} ${req.url}`);
|
||||
if (req.headers.authorization !== 'Bearer local-test') {
|
||||
res.writeHead(401).end();
|
||||
return;
|
||||
}
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
ok: true,
|
||||
version: 'test',
|
||||
commit: 'test',
|
||||
auth_required: true,
|
||||
api_key: 'redacted',
|
||||
}),
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
try {
|
||||
const port = (server.address() as AddressInfo).port;
|
||||
const transport: typeof fetch = (input, init) =>
|
||||
fetch(
|
||||
`http://127.0.0.1:${port}${new URL(input instanceof URL ? input.href : typeof input === 'string' ? input : input.url).pathname}`,
|
||||
init,
|
||||
);
|
||||
const adapter = new HermesAdapter(
|
||||
{
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => Promise.resolve('local-test'),
|
||||
},
|
||||
transport,
|
||||
);
|
||||
expect(await adapter.health()).toEqual({
|
||||
ok: true,
|
||||
version: 'test',
|
||||
commit: 'test',
|
||||
auth_required: true,
|
||||
});
|
||||
expect(seen).toEqual(['GET /api/health']);
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) =>
|
||||
server.close((e) => (e ? reject(e) : resolve())),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"outDir": "../../../.hermes-contract-build",
|
||||
"incremental": false,
|
||||
"strict": true
|
||||
},
|
||||
"include": ["./*.ts"],
|
||||
"exclude": []
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,90 @@
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
IsEnum,
|
||||
IsHash,
|
||||
IsIn,
|
||||
IsInt,
|
||||
IsISO8601,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Max,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { OperationMode, WorkflowState } from '../orchestration.domain';
|
||||
export class CreateOrchestrationTaskDto {
|
||||
@IsString() @IsNotEmpty() key!: string;
|
||||
@IsString() @IsNotEmpty() title!: string;
|
||||
@IsString() @IsNotEmpty() department!: string;
|
||||
@IsEnum(OperationMode) operationMode!: OperationMode;
|
||||
@Type(() => Number) @IsInt() @Min(0) budgetLimitCents!: number;
|
||||
@IsOptional() metadata?: Record<string, unknown>;
|
||||
}
|
||||
export class TransitionTaskDto {
|
||||
@IsEnum(WorkflowState) toState!: WorkflowState;
|
||||
@Type(() => Number) @IsInt() @Min(1) expectedVersion!: number;
|
||||
@IsString() @IsNotEmpty() idempotencyKey!: string;
|
||||
@IsOptional() @IsString() reason?: string;
|
||||
}
|
||||
export class GateDecisionDto {
|
||||
@IsIn(['APPROVED', 'REJECTED']) decision!: 'APPROVED' | 'REJECTED';
|
||||
@Type(() => Number) @IsInt() @Min(1) expectedVersion!: number;
|
||||
@IsString() @IsNotEmpty() idempotencyKey!: 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 RecordBudgetDto {
|
||||
@Type(() => Number) @IsInt() @Min(1) amountCents!: number;
|
||||
@IsString() @IsNotEmpty() idempotencyKey!: string;
|
||||
@IsString() @IsNotEmpty() kind!: string;
|
||||
@IsOptional() metadata?: Record<string, unknown>;
|
||||
}
|
||||
export class SetKillSwitchDto {
|
||||
@IsIn([
|
||||
'FREEZE_NEW_WORK',
|
||||
'STOP_AGENTS',
|
||||
'DISABLE_MUTATIONS',
|
||||
'EMERGENCY_HALT',
|
||||
])
|
||||
level!: string;
|
||||
@IsString() @IsNotEmpty() reason!: string;
|
||||
}
|
||||
|
||||
export class ReconcileBudgetDto {
|
||||
@IsString() @IsNotEmpty() reservationId!: string;
|
||||
@Type(() => Number) @IsInt() @Min(0) actualCents!: number;
|
||||
@IsString() @IsNotEmpty() idempotencyKey!: string;
|
||||
}
|
||||
export class OrchestrationCommandDto {
|
||||
@Type(() => Number) @IsInt() @Min(1) expectedVersion!: number;
|
||||
@IsString() @IsNotEmpty() idempotencyKey!: string;
|
||||
@IsOptional() @IsString() commitSha?: string;
|
||||
@IsOptional()
|
||||
@IsIn(['development', 'staging', 'production'])
|
||||
environment?: string;
|
||||
@IsOptional() @IsString() runId?: string;
|
||||
@IsOptional() @IsString() approvalId?: string;
|
||||
@IsOptional() @IsString() dependsOnTaskId?: string;
|
||||
@IsOptional() @IsIn(['SUCCEEDED', 'FAILED']) status?: string;
|
||||
@IsOptional()
|
||||
@IsIn([
|
||||
'TRANSIENT',
|
||||
'RATE_LIMITED',
|
||||
'DEPENDENCY',
|
||||
'VALIDATION',
|
||||
'POLICY',
|
||||
'PERMANENT',
|
||||
])
|
||||
retryClass?: string;
|
||||
@IsOptional() @IsHash('sha256') sha256?: string;
|
||||
@IsOptional() @IsHash('sha256') artifactHash?: string;
|
||||
@IsOptional() @IsHash('sha256') subjectHash?: string;
|
||||
@IsOptional() @IsString() kind?: string;
|
||||
@IsOptional() @IsString() uri?: string;
|
||||
@IsOptional() predicate?: Record<string, unknown>;
|
||||
@IsOptional() @IsString() signature?: string;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { ForbiddenException } from '@nestjs/common';
|
||||
import { KillSwitchService } from './kill-switch.service';
|
||||
|
||||
describe('KillSwitchService', () => {
|
||||
const prisma = { orchestrationKillSwitch: { findUnique: jest.fn() } };
|
||||
const service = new KillSwitchService(prisma as never);
|
||||
|
||||
beforeEach(() => jest.resetAllMocks());
|
||||
|
||||
it.each([
|
||||
['FREEZE_NEW_WORK', 'CREATE_TASK'],
|
||||
['STOP_AGENTS', 'RUN_AGENT'],
|
||||
['DISABLE_MUTATIONS', 'MUTATE_PRODUCTION'],
|
||||
['EMERGENCY_HALT', 'OBSERVE'],
|
||||
])('blocks %s at its policy boundary', async (level, action) => {
|
||||
prisma.orchestrationKillSwitch.findUnique.mockResolvedValue({
|
||||
scope: 'GLOBAL',
|
||||
level,
|
||||
active: true,
|
||||
});
|
||||
await expect(service.assertAllowed(action as never)).rejects.toThrow(
|
||||
ForbiddenException,
|
||||
);
|
||||
});
|
||||
|
||||
it('freezes new claims while allowing an already running agent to finish', async () => {
|
||||
prisma.orchestrationKillSwitch.findUnique.mockResolvedValue({scope:'GLOBAL',level:'FREEZE_NEW_WORK',active:true});
|
||||
await expect(service.assertAllowed('CLAIM_TASK' as never)).rejects.toThrow(ForbiddenException);
|
||||
await expect(service.assertAllowed('RUN_AGENT')).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('fails closed when an active persisted kill level is unknown', async () => {
|
||||
prisma.orchestrationKillSwitch.findUnique.mockResolvedValue({scope:'GLOBAL',level:'CORRUPT_LEVEL',active:true});
|
||||
await expect(service.assertAllowed('RUN_AGENT')).rejects.toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it('allows observation while production mutations are disabled', async () => {
|
||||
prisma.orchestrationKillSwitch.findUnique.mockResolvedValue({
|
||||
scope: 'GLOBAL',
|
||||
level: 'DISABLE_MUTATIONS',
|
||||
active: true,
|
||||
});
|
||||
await expect(service.assertAllowed('OBSERVE')).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { ForbiddenException, Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { KillSwitchLevel } from './orchestration.domain';
|
||||
export type GuardedAction =
|
||||
| 'CREATE_TASK'
|
||||
| 'CLAIM_TASK'
|
||||
| 'RUN_AGENT'
|
||||
| 'MUTATE_PRODUCTION'
|
||||
| 'OBSERVE';
|
||||
@Injectable()
|
||||
export class KillSwitchService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
async assertAllowed(action: GuardedAction): Promise<void> {
|
||||
const state = await (this.prisma as any).orchestrationKillSwitch.findUnique(
|
||||
{ where: { scope: 'GLOBAL' } },
|
||||
);
|
||||
if (!state?.active) return;
|
||||
const blocked: Record<KillSwitchLevel, GuardedAction[]> = {
|
||||
FREEZE_NEW_WORK: ['CREATE_TASK', 'CLAIM_TASK'],
|
||||
STOP_AGENTS: ['CREATE_TASK', 'CLAIM_TASK', 'RUN_AGENT'],
|
||||
DISABLE_MUTATIONS: ['CREATE_TASK', 'CLAIM_TASK', 'RUN_AGENT', 'MUTATE_PRODUCTION'],
|
||||
EMERGENCY_HALT: [
|
||||
'CREATE_TASK',
|
||||
'CLAIM_TASK',
|
||||
'RUN_AGENT',
|
||||
'MUTATE_PRODUCTION',
|
||||
'OBSERVE',
|
||||
],
|
||||
};
|
||||
if (!Object.values(KillSwitchLevel).includes(state.level) ||
|
||||
blocked[state.level as KillSwitchLevel].includes(action))
|
||||
throw new ForbiddenException(
|
||||
`Orchestration kill switch ${state.level} blocks ${action}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
describe('orchestration migration safety', () => {
|
||||
it('is additive and never mutates legacy governance tables', () => {
|
||||
const sql = readFileSync(
|
||||
join(
|
||||
process.cwd(),
|
||||
'prisma/migrations/20261022000000_add_orchestration_v4_core/migration.sql',
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
expect(sql).not.toMatch(/^\s*(DROP|TRUNCATE|DELETE|UPDATE)\b/im);
|
||||
expect(sql).not.toMatch(
|
||||
/ALTER TABLE "(approval_requests|department_tasks|audit_logs)"/i,
|
||||
);
|
||||
expect(sql.match(/CREATE TABLE "orchestration_/g)).toHaveLength(9);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { ModelTierPolicyService } from './model-tier-policy.service';
|
||||
|
||||
describe('ModelTierPolicyService', () => {
|
||||
const policy = new ModelTierPolicyService();
|
||||
|
||||
it.each([
|
||||
[
|
||||
{
|
||||
complexity: 0,
|
||||
risk: 0,
|
||||
operationMode: 'OBSERVE',
|
||||
remainingBudgetCents: 1,
|
||||
},
|
||||
'L0',
|
||||
],
|
||||
[
|
||||
{
|
||||
complexity: 2,
|
||||
risk: 1,
|
||||
operationMode: 'PREPARE',
|
||||
remainingBudgetCents: 100,
|
||||
},
|
||||
'L1',
|
||||
],
|
||||
[
|
||||
{
|
||||
complexity: 5,
|
||||
risk: 4,
|
||||
operationMode: 'PREPARE',
|
||||
remainingBudgetCents: 500,
|
||||
},
|
||||
'L2',
|
||||
],
|
||||
[
|
||||
{
|
||||
complexity: 7,
|
||||
risk: 7,
|
||||
operationMode: 'PREPARE',
|
||||
remainingBudgetCents: 1500,
|
||||
},
|
||||
'L3',
|
||||
],
|
||||
[
|
||||
{
|
||||
complexity: 9,
|
||||
risk: 9,
|
||||
operationMode: 'MUTATE_PRODUCTION',
|
||||
remainingBudgetCents: 5000,
|
||||
},
|
||||
'L4',
|
||||
],
|
||||
])('selects a deterministic tier for policy inputs', (input, expected) => {
|
||||
expect(policy.select(input as never)).toBe(expected);
|
||||
expect(policy.select(input as never)).toBe(expected);
|
||||
});
|
||||
|
||||
it('fails closed when the selected tier exceeds the remaining hard budget', () => {
|
||||
expect(() =>
|
||||
policy.select({
|
||||
complexity: 9,
|
||||
risk: 9,
|
||||
operationMode: 'MUTATE_PRODUCTION',
|
||||
remainingBudgetCents: 100,
|
||||
}),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { OperationMode } from './orchestration.domain';
|
||||
export type ModelTier = 'L0' | 'L1' | 'L2' | 'L3' | 'L4';
|
||||
@Injectable()
|
||||
export class ModelTierPolicyService {
|
||||
select(input: {
|
||||
complexity: number;
|
||||
risk: number;
|
||||
operationMode: OperationMode | string;
|
||||
remainingBudgetCents: number;
|
||||
}): ModelTier {
|
||||
const score =
|
||||
Math.max(input.complexity, input.risk) +
|
||||
(String(input.operationMode) === String(OperationMode.MUTATE_PRODUCTION)
|
||||
? 1
|
||||
: 0);
|
||||
const tier: ModelTier =
|
||||
score <= 1
|
||||
? 'L0'
|
||||
: score <= 3
|
||||
? 'L1'
|
||||
: score <= 5
|
||||
? 'L2'
|
||||
: score <= 8
|
||||
? 'L3'
|
||||
: 'L4';
|
||||
const floor: Record<ModelTier, number> = {
|
||||
L0: 1,
|
||||
L1: 25,
|
||||
L2: 100,
|
||||
L3: 500,
|
||||
L4: 2000,
|
||||
};
|
||||
if (input.remainingBudgetCents < floor[tier])
|
||||
throw new BadRequestException(
|
||||
`Hard budget cannot fund selected model tier ${tier}`,
|
||||
);
|
||||
return tier;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
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 { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
|
||||
describe('integration read boundary', () => {
|
||||
let app: INestApplication;
|
||||
const task = {
|
||||
id: 't1',
|
||||
key: 'k',
|
||||
title: 'Review',
|
||||
department: 'SEO',
|
||||
state: 'GATE2_APPROVED',
|
||||
version: 1,
|
||||
operationMode: 'PREPARE',
|
||||
budgetLimitCents: 0,
|
||||
metadata: { token: 'secret' },
|
||||
runs: [
|
||||
{
|
||||
id: 'r',
|
||||
status: 'VERIFIED',
|
||||
commitSha: 'abc',
|
||||
environment: 'stage',
|
||||
artifacts: [
|
||||
{
|
||||
id: 'a',
|
||||
sha256: 'f'.repeat(64),
|
||||
sizeBytes: 1n,
|
||||
uri: 'secret-uri',
|
||||
metadata: { token: 'secret' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
events: [
|
||||
{
|
||||
id: 'e',
|
||||
eventType: 'CREATED',
|
||||
sequence: 1,
|
||||
payload: { token: 'secret' },
|
||||
},
|
||||
],
|
||||
};
|
||||
const service = {
|
||||
findAll: jest.fn(() => Promise.resolve([task])),
|
||||
findOne: jest.fn(() => Promise.resolve(task)),
|
||||
createTask: jest.fn(),
|
||||
transition: jest.fn(),
|
||||
decideGate: jest.fn(),
|
||||
recordBudget: jest.fn(),
|
||||
setKillSwitch: jest.fn(),
|
||||
command: jest.fn(),
|
||||
reconcileBudget: jest.fn(),
|
||||
};
|
||||
beforeAll(async () => {
|
||||
const m = await Test.createTestingModule({
|
||||
controllers: [OrchestrationController],
|
||||
providers: [
|
||||
{ provide: OrchestrationService, useValue: service },
|
||||
RolesGuard,
|
||||
],
|
||||
})
|
||||
.overrideGuard(JwtAuthGuard)
|
||||
.useValue({
|
||||
canActivate(c: any) {
|
||||
const req = c.switchToHttp().getRequest();
|
||||
if (!req.headers.authorization) return false;
|
||||
req.user = { id: 'verified-user', role: req.headers.authorization };
|
||||
return true;
|
||||
},
|
||||
})
|
||||
.compile();
|
||||
app = m.createNestApplication();
|
||||
await app.init();
|
||||
});
|
||||
afterAll(async () => app.close());
|
||||
it('denies every mutation before legacy core is invoked', async () => {
|
||||
for (const [method, path] of [
|
||||
['post', 'tasks'],
|
||||
['put', 'tasks/t1/transition'],
|
||||
['post', 'tasks/t1/gates/2/decide'],
|
||||
['post', 'tasks/t1/budget'],
|
||||
['post', 'tasks/t1/commands/RUN_CREATE'],
|
||||
['post', 'tasks/t1/budget/reconcile'],
|
||||
['put', 'kill-switch'],
|
||||
['post', 'chat/messages'],
|
||||
] as const) {
|
||||
await request(app.getHttpServer())
|
||||
[method]('/admin/orchestration/' + path)
|
||||
.set('Authorization', 'Admin')
|
||||
.send({})
|
||||
.expect(path === 'tasks' || path.endsWith('/transition') ? 400 : 403);
|
||||
}
|
||||
for (const name of [
|
||||
'createTask',
|
||||
'transition',
|
||||
'decideGate',
|
||||
'recordBudget',
|
||||
'setKillSwitch',
|
||||
'command',
|
||||
'reconcileBudget',
|
||||
] as const)
|
||||
expect(service[name]).not.toHaveBeenCalled();
|
||||
});
|
||||
it('projects list and detail with no actions, arbitrary secrets or BigInt transport failures', async () => {
|
||||
for (const path of ['tasks', 'tasks/t1']) {
|
||||
const r = await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/' + path)
|
||||
.set('Authorization', 'Admin')
|
||||
.expect(200);
|
||||
const t = Array.isArray(r.body) ? r.body[0] : r.body;
|
||||
expect(t.availableActions).toEqual([]);
|
||||
expect(t.budgetLimitCents).toBe(0);
|
||||
expect(JSON.stringify(t)).not.toMatch(/secret|sizeBytes|payload|token/);
|
||||
}
|
||||
});
|
||||
it('returns actual inventory overview and explicit unavailable runtime resources', async () => {
|
||||
const r = await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/overview')
|
||||
.set('Authorization', 'Admin')
|
||||
.expect(200);
|
||||
expect(r.body.items).toEqual([
|
||||
expect.objectContaining({ id: 'tasks', count: 1 }),
|
||||
]);
|
||||
expect(r.body.capabilities).toMatchObject({
|
||||
mutations: false,
|
||||
chat: false,
|
||||
runtime: false,
|
||||
});
|
||||
for (const path of ['agents', 'schedules', 'model-policy'])
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/' + path)
|
||||
.set('Authorization', 'Admin')
|
||||
.expect(503);
|
||||
const releases = await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/releases')
|
||||
.set('Authorization', 'Admin')
|
||||
.expect(200);
|
||||
expect(releases.body.items[0]).toMatchObject({
|
||||
id: 'r',
|
||||
commitSha: 'abc',
|
||||
environment: 'stage',
|
||||
});
|
||||
});
|
||||
it('protects read surfaces from anonymous and customer access', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/overview')
|
||||
.expect(403);
|
||||
await request(app.getHttpServer())
|
||||
.get('/admin/orchestration/tasks')
|
||||
.set('Authorization', 'CUSTOMER')
|
||||
.expect(403);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,230 @@
|
||||
import {
|
||||
Controller,
|
||||
Body,
|
||||
Req,
|
||||
Optional,
|
||||
ValidationPipe,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
UseGuards,
|
||||
ForbiddenException,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
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,
|
||||
} 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[]) {
|
||||
return Object.fromEntries(
|
||||
keys.filter((k) => row[k] !== undefined).map((k) => [k, row[k]]),
|
||||
);
|
||||
}
|
||||
function project(row: any) {
|
||||
return {
|
||||
...pick(row, [
|
||||
'id',
|
||||
'key',
|
||||
'title',
|
||||
'department',
|
||||
'state',
|
||||
'version',
|
||||
'operationMode',
|
||||
'budgetLimitCents',
|
||||
]),
|
||||
availableActions: [],
|
||||
runs: (row.runs ?? []).map((run: any) => ({
|
||||
...pick(run, ['id', 'commitSha', 'environment', 'status']),
|
||||
artifacts: (run.artifacts ?? []).map((a: any) =>
|
||||
pick(a, ['id', 'kind', 'sha256']),
|
||||
),
|
||||
})),
|
||||
decisions: (row.decisions ?? []).map((d: any) =>
|
||||
pick(d, [
|
||||
'id',
|
||||
'gate',
|
||||
'decision',
|
||||
'expiresAt',
|
||||
'runId',
|
||||
'artifactHash',
|
||||
'commitSha',
|
||||
'environment',
|
||||
'createdAt',
|
||||
]),
|
||||
),
|
||||
events: (row.events ?? []).map((e: any) =>
|
||||
pick(e, [
|
||||
'id',
|
||||
'eventType',
|
||||
'fromState',
|
||||
'toState',
|
||||
'sequence',
|
||||
'createdAt',
|
||||
]),
|
||||
),
|
||||
budgetLedger: (row.budgetLedger ?? []).map((b: any) =>
|
||||
pick(b, ['id', 'amountCents', 'kind', 'createdAt']),
|
||||
),
|
||||
};
|
||||
}
|
||||
@ApiTags('Admin - Orchestration v4')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@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;
|
||||
if (
|
||||
typeof id !== 'string' ||
|
||||
!id ||
|
||||
!['Admin', 'SUPER_ADMIN'].includes(req?.user?.role)
|
||||
)
|
||||
throw new ForbiddenException('Authenticated workflow identity required');
|
||||
return { id, role: req.user.role };
|
||||
}
|
||||
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,
|
||||
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) {
|
||||
return this.safe(await this.service.findOne(id), req);
|
||||
}
|
||||
@Get('overview') async overview() {
|
||||
const tasks = await this.service.findAll();
|
||||
return {
|
||||
items: [
|
||||
{ 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',
|
||||
};
|
||||
}
|
||||
@Get('releases') async releases() {
|
||||
const tasks = await this.service.findAll();
|
||||
const details = await Promise.all(
|
||||
tasks.map((t: any) => this.service.findOne(t.id)),
|
||||
);
|
||||
return {
|
||||
items: details.flatMap((t: any) =>
|
||||
(t.runs ?? []).map((run: any) =>
|
||||
pick(run, ['id', 'status', 'commitSha', 'environment']),
|
||||
),
|
||||
),
|
||||
measuredAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
@Get('agents') agents() {
|
||||
throw new ServiceUnavailableException(
|
||||
'Hermes runtime unavailable: trusted identity and runtime authentication not configured',
|
||||
);
|
||||
}
|
||||
@Get('schedules') schedules() {
|
||||
throw new ServiceUnavailableException(
|
||||
'Hermes schedules unavailable; runtime remains disabled',
|
||||
);
|
||||
}
|
||||
@Get('model-policy') models() {
|
||||
throw new ServiceUnavailableException(
|
||||
'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);
|
||||
}
|
||||
@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,
|
||||
);
|
||||
}
|
||||
@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/budget') budget() {
|
||||
return this.deny();
|
||||
}
|
||||
@Put('kill-switch') kill() {
|
||||
return this.deny();
|
||||
}
|
||||
@Post('chat/messages') chat() {
|
||||
return this.deny();
|
||||
}
|
||||
@Post('tasks/:id/commands/:command') command() {
|
||||
return this.deny();
|
||||
}
|
||||
@Post('tasks/:id/budget/reconcile') reconcile() {
|
||||
return this.deny();
|
||||
}
|
||||
private deny(): never {
|
||||
throw new ForbiddenException(
|
||||
'Orchestration mutations and chat disabled pending hardened core and trusted runtime integration',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
assertTransition,
|
||||
nextStateForGateDecision,
|
||||
OperationMode,
|
||||
WorkflowState,
|
||||
} from './orchestration.domain';
|
||||
|
||||
describe('orchestration domain', () => {
|
||||
it('allows only declared workflow transitions', () => {
|
||||
expect(() =>
|
||||
assertTransition(WorkflowState.DRAFT, WorkflowState.GATE1_PENDING),
|
||||
).not.toThrow();
|
||||
expect(() =>
|
||||
assertTransition(WorkflowState.DRAFT, WorkflowState.RUNNING),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('keeps gate 1 as execution authorization rather than release authorization', () => {
|
||||
expect(nextStateForGateDecision(1, 'APPROVED')).toBe(
|
||||
WorkflowState.GATE1_APPROVED,
|
||||
);
|
||||
expect(nextStateForGateDecision(2, 'APPROVED')).toBe(
|
||||
WorkflowState.GATE2_APPROVED,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an unsupported gate decision', () => {
|
||||
expect(() => nextStateForGateDecision(1, 'PENDING' as never)).toThrow(
|
||||
BadRequestException,
|
||||
);
|
||||
});
|
||||
|
||||
it.each([WorkflowState.GATE1_PENDING, WorkflowState.GATE2_PENDING])('does not revive an expired proposal into %s', (state) => {
|
||||
expect(() => assertTransition(WorkflowState.EXPIRED,state)).toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('classifies production mutation separately from observe and prepare', () => {
|
||||
expect(OperationMode.OBSERVE).toBe('OBSERVE');
|
||||
expect(OperationMode.PREPARE).toBe('PREPARE');
|
||||
expect(OperationMode.MUTATE_PRODUCTION).toBe('MUTATE_PRODUCTION');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
export enum WorkflowState {
|
||||
DRAFT = 'DRAFT',
|
||||
GATE1_PENDING = 'GATE1_PENDING',
|
||||
GATE1_APPROVED = 'GATE1_APPROVED',
|
||||
READY = 'READY',
|
||||
CLAIMED = 'CLAIMED',
|
||||
RUNNING = 'RUNNING',
|
||||
VERIFYING = 'VERIFYING',
|
||||
GATE2_PENDING = 'GATE2_PENDING',
|
||||
GATE2_APPROVED = 'GATE2_APPROVED',
|
||||
RELEASING = 'RELEASING',
|
||||
PRODUCTION_VERIFYING = 'PRODUCTION_VERIFYING',
|
||||
LIVE_VERIFIED = 'LIVE_VERIFIED',
|
||||
MEASURING = 'MEASURING',
|
||||
CLOSED = 'CLOSED',
|
||||
REJECTED = 'REJECTED',
|
||||
BLOCKED = 'BLOCKED',
|
||||
CANCELLED = 'CANCELLED',
|
||||
FAILED = 'FAILED',
|
||||
EXPIRED = 'EXPIRED',
|
||||
}
|
||||
export enum OperationMode {
|
||||
OBSERVE = 'OBSERVE',
|
||||
PREPARE = 'PREPARE',
|
||||
MUTATE_PRODUCTION = 'MUTATE_PRODUCTION',
|
||||
}
|
||||
export enum RetryClass {
|
||||
TRANSIENT = 'TRANSIENT',
|
||||
RATE_LIMITED = 'RATE_LIMITED',
|
||||
DEPENDENCY = 'DEPENDENCY',
|
||||
VALIDATION = 'VALIDATION',
|
||||
POLICY = 'POLICY',
|
||||
PERMANENT = 'PERMANENT',
|
||||
}
|
||||
export enum KillSwitchLevel {
|
||||
FREEZE_NEW_WORK = 'FREEZE_NEW_WORK',
|
||||
STOP_AGENTS = 'STOP_AGENTS',
|
||||
DISABLE_MUTATIONS = 'DISABLE_MUTATIONS',
|
||||
EMERGENCY_HALT = 'EMERGENCY_HALT',
|
||||
}
|
||||
|
||||
const transitions: Record<WorkflowState, WorkflowState[]> = {
|
||||
DRAFT: [WorkflowState.GATE1_PENDING, WorkflowState.CANCELLED],
|
||||
GATE1_PENDING: [
|
||||
WorkflowState.GATE1_APPROVED,
|
||||
WorkflowState.REJECTED,
|
||||
WorkflowState.EXPIRED,
|
||||
],
|
||||
GATE1_APPROVED: [WorkflowState.READY, WorkflowState.CANCELLED],
|
||||
READY: [
|
||||
WorkflowState.CLAIMED,
|
||||
WorkflowState.BLOCKED,
|
||||
WorkflowState.CANCELLED,
|
||||
],
|
||||
CLAIMED: [
|
||||
WorkflowState.RUNNING,
|
||||
WorkflowState.READY,
|
||||
WorkflowState.CANCELLED,
|
||||
],
|
||||
RUNNING: [
|
||||
WorkflowState.VERIFYING,
|
||||
WorkflowState.FAILED,
|
||||
WorkflowState.BLOCKED,
|
||||
],
|
||||
VERIFYING: [
|
||||
WorkflowState.GATE2_PENDING,
|
||||
WorkflowState.FAILED,
|
||||
WorkflowState.RUNNING,
|
||||
],
|
||||
GATE2_PENDING: [
|
||||
WorkflowState.GATE2_APPROVED,
|
||||
WorkflowState.REJECTED,
|
||||
WorkflowState.EXPIRED,
|
||||
],
|
||||
GATE2_APPROVED: [WorkflowState.RELEASING, WorkflowState.CANCELLED],
|
||||
RELEASING: [WorkflowState.PRODUCTION_VERIFYING, WorkflowState.FAILED],
|
||||
PRODUCTION_VERIFYING: [WorkflowState.LIVE_VERIFIED, WorkflowState.FAILED],
|
||||
LIVE_VERIFIED: [WorkflowState.MEASURING, WorkflowState.CLOSED],
|
||||
MEASURING: [WorkflowState.CLOSED, WorkflowState.FAILED],
|
||||
CLOSED: [],
|
||||
REJECTED: [],
|
||||
BLOCKED: [WorkflowState.READY, WorkflowState.CANCELLED],
|
||||
CANCELLED: [],
|
||||
FAILED: [WorkflowState.READY, WorkflowState.CANCELLED],
|
||||
EXPIRED: [WorkflowState.CANCELLED],
|
||||
};
|
||||
export function assertTransition(from: WorkflowState, to: WorkflowState): void {
|
||||
if (!transitions[from]?.includes(to))
|
||||
throw new BadRequestException(
|
||||
`Invalid orchestration transition ${from} -> ${to}`,
|
||||
);
|
||||
}
|
||||
export function nextStateForGateDecision(
|
||||
gate: 1 | 2,
|
||||
decision: 'APPROVED' | 'REJECTED',
|
||||
): WorkflowState {
|
||||
if (!(['APPROVED', 'REJECTED'] as string[]).includes(decision))
|
||||
throw new BadRequestException('Decision must be APPROVED or REJECTED');
|
||||
return decision === 'REJECTED'
|
||||
? WorkflowState.REJECTED
|
||||
: gate === 1
|
||||
? WorkflowState.GATE1_APPROVED
|
||||
: WorkflowState.GATE2_APPROVED;
|
||||
}
|
||||
@@ -0,0 +1,577 @@
|
||||
import { OrchestrationController } from './orchestration.controller';
|
||||
import { DepartmentTasksController } from '../admin/department-tasks.controller';
|
||||
import { ApprovalsController } from '../admin/approvals.controller';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { OrchestrationService } from './orchestration.service';
|
||||
import { KillSwitchService } from './kill-switch.service';
|
||||
import { WorkflowState, OperationMode } from './orchestration.domain';
|
||||
const enabled = process.env.ORCHESTRATION_INTEGRATION === '1';
|
||||
(enabled ? describe : describe.skip)(
|
||||
'v4 disposable PostgreSQL invariants',
|
||||
() => {
|
||||
const db = new PrismaClient();
|
||||
const service = new OrchestrationService(
|
||||
db as never,
|
||||
new KillSwitchService(db as never),
|
||||
);
|
||||
let n = 0;
|
||||
async function task(state = 'DRAFT', budget = 100) {
|
||||
return db.orchestrationTask.create({
|
||||
data: {
|
||||
key: `test-${Date.now()}-${n++}`,
|
||||
title: 'test',
|
||||
department: 'TEST',
|
||||
operationMode: 'PREPARE',
|
||||
state,
|
||||
budgetLimitCents: budget,
|
||||
},
|
||||
});
|
||||
}
|
||||
afterAll(async () => db.$disconnect());
|
||||
it('release rejects PREPARE operation class even with gate approval', async()=>{
|
||||
const t=await task('GATE2_APPROVED');
|
||||
await expect(service.command(t.id,'RELEASE_AUTHORIZE',{expectedVersion:1,idempotencyKey:`mode-${t.id}`},'ci')).rejects.toThrow(/operation mode/i);
|
||||
});
|
||||
|
||||
it('append-only ledger rejects direct rewrites in PostgreSQL', async () => {
|
||||
const t = await task();
|
||||
const r = await service.recordBudget(
|
||||
t.id,
|
||||
{
|
||||
amountCents: 50,
|
||||
kind: 'RESERVE',
|
||||
idempotencyKey: `immutable-${t.id}`,
|
||||
},
|
||||
'a',
|
||||
);
|
||||
await expect(
|
||||
db.orchestrationBudgetLedger.update({
|
||||
where: { id: r.id },
|
||||
data: { amountCents: 0 },
|
||||
}),
|
||||
).rejects.toThrow(/append.only/i);
|
||||
await expect(
|
||||
db.orchestrationBudgetLedger.delete({ where: { id: r.id } }),
|
||||
).rejects.toThrow(/append.only/i);
|
||||
});
|
||||
it('generic transitions cannot fake run lifecycle or production verification', async () => {
|
||||
for (const [from, to] of [
|
||||
['CLAIMED', 'RUNNING'],
|
||||
['RUNNING', 'VERIFYING'],
|
||||
['FAILED', 'READY'],
|
||||
['PRODUCTION_VERIFYING', 'LIVE_VERIFIED'],
|
||||
]) {
|
||||
const t = await task(from);
|
||||
await expect(
|
||||
service.transition(
|
||||
t.id,
|
||||
{
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `fake-${t.id}`,
|
||||
toState: to as WorkflowState,
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/dedicated/i);
|
||||
}
|
||||
});
|
||||
it('exposes command and reconcile HTTP handlers', () => {
|
||||
const c = new OrchestrationController(service);
|
||||
expect(typeof c.command).toBe('function');
|
||||
expect(typeof c.reconcile).toBe('function');
|
||||
});
|
||||
it('highest kill level blocks reads and reconciliation', async () => {
|
||||
const t = await task();
|
||||
const r = await service.recordBudget(
|
||||
t.id,
|
||||
{
|
||||
kind: 'RESERVE',
|
||||
amountCents: 10,
|
||||
idempotencyKey: `stop-res-${t.id}`,
|
||||
},
|
||||
'a',
|
||||
);
|
||||
await service.setKillSwitch(
|
||||
['EMERGENCY', 'HALT'].join('_'),
|
||||
'test',
|
||||
'ceo',
|
||||
);
|
||||
try {
|
||||
await expect(service.findOne(t.id)).rejects.toThrow(/kill switch/i);
|
||||
await expect(
|
||||
service.reconcileBudget(
|
||||
t.id,
|
||||
{
|
||||
reservationId: r.id,
|
||||
actualCents: 0,
|
||||
idempotencyKey: `stop-recon-${t.id}`,
|
||||
},
|
||||
'a',
|
||||
),
|
||||
).rejects.toThrow(/kill switch/i);
|
||||
} finally {
|
||||
await db.orchestrationKillSwitch.deleteMany();
|
||||
}
|
||||
});
|
||||
it('legacy arbitrary status and approval endpoints fail closed', async () => {
|
||||
await expect(
|
||||
new DepartmentTasksController(db as never).create({
|
||||
title: 'bypass',
|
||||
status: 'DONE',
|
||||
}),
|
||||
).rejects.toThrow(/v4/i);
|
||||
await expect(
|
||||
new DepartmentTasksController(db as never).updateStatus('none', {
|
||||
status: 'DONE',
|
||||
}),
|
||||
).rejects.toThrow(/v4/i);
|
||||
await expect(
|
||||
new ApprovalsController(db as never).decide('none', {
|
||||
decision: 'APPROVED',
|
||||
} as any),
|
||||
).rejects.toThrow(/v4/i);
|
||||
});
|
||||
it('release consumes only matching fresh production Gate2 via dedicated command', async () => {
|
||||
const t = await task('GATE2_PENDING');
|
||||
const hash = 'f'.repeat(64),
|
||||
commitSha = 'a'.repeat(40);
|
||||
const r = await db.orchestrationRun.create({
|
||||
data: {
|
||||
taskId: t.id,
|
||||
status: 'SUCCEEDED',
|
||||
commitSha,
|
||||
environment: 'production',
|
||||
idempotencyKey: `rel-run-${t.id}`,
|
||||
},
|
||||
});
|
||||
await db.orchestrationArtifact.create({
|
||||
data: {
|
||||
runId: r.id,
|
||||
kind: 'BUILD',
|
||||
uri: 'https://ci.example/build',
|
||||
sha256: hash,
|
||||
},
|
||||
});
|
||||
await db.orchestrationAttestation.create({
|
||||
data: {
|
||||
runId: r.id,
|
||||
kind: 'TEST',
|
||||
subjectHash: hash,
|
||||
signer: 'ci',
|
||||
predicate: { passed: true },
|
||||
},
|
||||
});
|
||||
const decision = await service.decideGate(
|
||||
t.id,
|
||||
2,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `rel-approve-${t.id}`,
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
runId: r.id,
|
||||
artifactHash: hash,
|
||||
commitSha,
|
||||
environment: 'production',
|
||||
},
|
||||
'ceo',
|
||||
);
|
||||
const dto = {
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: `rel-${t.id}`,
|
||||
approvalId: decision.id,
|
||||
runId: r.id,
|
||||
artifactHash: hash,
|
||||
commitSha,
|
||||
environment: 'production',
|
||||
};
|
||||
await expect(
|
||||
(service as any).command(
|
||||
t.id,
|
||||
'RELEASE_AUTHORIZE',
|
||||
{ ...dto, artifactHash: '0'.repeat(64) },
|
||||
'ci',
|
||||
),
|
||||
).rejects.toThrow(/binding/i);
|
||||
const result = await (service as any).command(
|
||||
t.id,
|
||||
'RELEASE_AUTHORIZE',
|
||||
dto,
|
||||
'ci',
|
||||
);
|
||||
expect(result.authorized).toBe(true);
|
||||
expect(
|
||||
(await db.orchestrationTask.findUniqueOrThrow({ where: { id: t.id } }))
|
||||
.state,
|
||||
).toBe('RELEASING');
|
||||
await expect(
|
||||
(service as any).command(
|
||||
t.id,
|
||||
'RELEASE_AUTHORIZE',
|
||||
{ ...dto, expectedVersion: 3, idempotencyKey: `rel-again-${t.id}` },
|
||||
'ci',
|
||||
),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
it('gate decision replay rejects changed immutable expiry and actor', async () => {
|
||||
const t = await task('GATE1_PENDING');
|
||||
const dto = {
|
||||
decision: 'APPROVED' as const,
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `bind-${t.id}`,
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
};
|
||||
await service.decideGate(t.id, 1, dto, 'ceo');
|
||||
await expect(
|
||||
service.decideGate(
|
||||
t.id,
|
||||
1,
|
||||
{ ...dto, expiresAt: new Date(Date.now() + 120000).toISOString() },
|
||||
'ceo',
|
||||
),
|
||||
).rejects.toThrow(/Idempotency/i);
|
||||
await expect(service.decideGate(t.id, 1, dto, 'other')).rejects.toThrow(
|
||||
/Idempotency/i,
|
||||
);
|
||||
});
|
||||
it('dependencies block admission and reject cycles', async () => {
|
||||
const a = await task();
|
||||
const b = await task();
|
||||
await (service as any).command(
|
||||
a.id,
|
||||
'DEPENDENCY_ADD',
|
||||
{
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `dep-a-${a.id}`,
|
||||
dependsOnTaskId: b.id,
|
||||
},
|
||||
'actor',
|
||||
);
|
||||
await expect(
|
||||
(service as any).command(
|
||||
b.id,
|
||||
'DEPENDENCY_ADD',
|
||||
{
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `dep-b-${b.id}`,
|
||||
dependsOnTaskId: a.id,
|
||||
},
|
||||
'actor',
|
||||
),
|
||||
).rejects.toThrow(/cycle/i);
|
||||
await db.orchestrationTask.update({
|
||||
where: { id: a.id },
|
||||
data: { state: 'GATE1_PENDING' },
|
||||
});
|
||||
await service.decideGate(
|
||||
a.id,
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: `dep-approval-${a.id}`,
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
},
|
||||
'ceo',
|
||||
);
|
||||
await expect(
|
||||
service.transition(
|
||||
a.id,
|
||||
{
|
||||
toState: WorkflowState.READY,
|
||||
expectedVersion: 3,
|
||||
idempotencyKey: `dep-ready-${a.id}`,
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/dependency/i);
|
||||
});
|
||||
it('registers artifact and attestation for owned run, blocks unregistered subjects', async () => {
|
||||
const t = await task('CLAIMED');
|
||||
const base = {
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `life-${t.id}`,
|
||||
commitSha: 'c'.repeat(40),
|
||||
environment: 'staging',
|
||||
};
|
||||
const r = await (service as any).command(
|
||||
t.id,
|
||||
'RUN_CREATE',
|
||||
base,
|
||||
'agent',
|
||||
);
|
||||
const hash = 'd'.repeat(64);
|
||||
const a = await (service as any).command(
|
||||
t.id,
|
||||
'ARTIFACT_ADD',
|
||||
{
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: `art-${t.id}`,
|
||||
runId: r.id,
|
||||
sha256: hash,
|
||||
kind: 'BUILD',
|
||||
uri: 'https://ci.example/artifact',
|
||||
},
|
||||
'agent',
|
||||
);
|
||||
expect(a.sha256).toBe(hash);
|
||||
await expect(
|
||||
(service as any).command(
|
||||
t.id,
|
||||
'ATTESTATION_ADD',
|
||||
{
|
||||
expectedVersion: 3,
|
||||
idempotencyKey: `bad-att-${t.id}`,
|
||||
runId: r.id,
|
||||
subjectHash: 'e'.repeat(64),
|
||||
kind: 'TEST',
|
||||
predicate: { passed: true },
|
||||
},
|
||||
'ci',
|
||||
),
|
||||
).rejects.toThrow(/artifact/i);
|
||||
const att = await (service as any).command(
|
||||
t.id,
|
||||
'ATTESTATION_ADD',
|
||||
{
|
||||
expectedVersion: 3,
|
||||
idempotencyKey: `att-${t.id}`,
|
||||
runId: r.id,
|
||||
subjectHash: hash,
|
||||
kind: 'TEST',
|
||||
predicate: { passed: true },
|
||||
},
|
||||
'ci',
|
||||
);
|
||||
expect(att.signer).toBe('ci');
|
||||
});
|
||||
it('creates immutable versioned runs with bounded transient retries', async () => {
|
||||
const t = await task('CLAIMED');
|
||||
const dto = {
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `run-${t.id}`,
|
||||
commitSha: 'a'.repeat(40),
|
||||
environment: 'staging',
|
||||
};
|
||||
const r = await (service as any).command(
|
||||
t.id,
|
||||
'RUN_CREATE',
|
||||
dto,
|
||||
'agent',
|
||||
);
|
||||
expect(r.attempt).toBe(1);
|
||||
expect(
|
||||
await (service as any).command(t.id, 'RUN_CREATE', dto, 'agent'),
|
||||
).toEqual(r);
|
||||
await expect(
|
||||
(service as any).command(
|
||||
t.id,
|
||||
'RUN_CREATE',
|
||||
{ ...dto, commitSha: 'b'.repeat(40) },
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/Idempotency/i);
|
||||
await (service as any).command(
|
||||
t.id,
|
||||
'RUN_FINISH',
|
||||
{
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: `finish-${t.id}`,
|
||||
runId: r.id,
|
||||
status: 'FAILED',
|
||||
retryClass: 'POLICY',
|
||||
},
|
||||
'agent',
|
||||
);
|
||||
await expect(
|
||||
(service as any).command(
|
||||
t.id,
|
||||
'RUN_CREATE',
|
||||
{ ...dto, expectedVersion: 3, idempotencyKey: `retry-${t.id}` },
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/retry/i);
|
||||
});
|
||||
it('selects tier at admission using backend risk and budget', async () => {
|
||||
const t = await task('GATE1_PENDING', 1000);
|
||||
await service.decideGate(
|
||||
t.id,
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `approve-tier-${t.id}`,
|
||||
expiresAt: new Date(Date.now() + 60000).toISOString(),
|
||||
},
|
||||
'ceo',
|
||||
);
|
||||
await service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: WorkflowState.READY,
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: `admit-tier-${t.id}`,
|
||||
},
|
||||
'agent',
|
||||
);
|
||||
expect(
|
||||
(await db.orchestrationTask.findUniqueOrThrow({ where: { id: t.id } }))
|
||||
.modelTier,
|
||||
).toBe('L0');
|
||||
});
|
||||
it('STOP_AGENTS prevents claims and running transitions', async () => {
|
||||
await service.setKillSwitch('STOP_AGENTS', 'test', 'ceo');
|
||||
try {
|
||||
const t = await task('READY');
|
||||
await expect(
|
||||
service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: WorkflowState.CLAIMED,
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `kill-${t.id}`,
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/kill switch/i);
|
||||
} finally {
|
||||
await db.orchestrationKillSwitch.deleteMany();
|
||||
}
|
||||
});
|
||||
it('Gate1 admission consumes only unexpired approval', async () => {
|
||||
const t = await task('GATE1_PENDING');
|
||||
await service.decideGate(
|
||||
t.id,
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `approve-${t.id}`,
|
||||
expiresAt: new Date(Date.now() + 100).toISOString(),
|
||||
},
|
||||
'ceo',
|
||||
);
|
||||
await new Promise((r) => setTimeout(r, 150));
|
||||
await expect(
|
||||
service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: WorkflowState.READY,
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: `admit-${t.id}`,
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/expired/i);
|
||||
});
|
||||
it('versioned transition replay returns original result and rejects changed payload', async () => {
|
||||
const t = await task();
|
||||
const dto = {
|
||||
toState: WorkflowState.GATE1_PENDING,
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `tr-${t.id}`,
|
||||
};
|
||||
const first = await service.transition(t.id, dto, 'actor');
|
||||
expect(await service.transition(t.id, dto, 'actor')).toEqual(first);
|
||||
await expect(
|
||||
service.transition(t.id, { ...dto, reason: 'different' }, 'actor'),
|
||||
).rejects.toThrow(/Idempotency/i);
|
||||
});
|
||||
it('reconciles a reservation exactly once without erasing spent cost', async () => {
|
||||
const t = await task();
|
||||
const r = await service.recordBudget(
|
||||
t.id,
|
||||
{ amountCents: 80, kind: 'RESERVE', idempotencyKey: `res-${t.id}` },
|
||||
'agent',
|
||||
);
|
||||
const dto = {
|
||||
reservationId: r.id,
|
||||
actualCents: 35,
|
||||
idempotencyKey: `reconcile-${t.id}`,
|
||||
};
|
||||
await (service as any).reconcileBudget(t.id, dto, 'agent');
|
||||
await (service as any).reconcileBudget(t.id, dto, 'agent');
|
||||
await expect(
|
||||
(service as any).reconcileBudget(
|
||||
t.id,
|
||||
{ ...dto, idempotencyKey: `second-${t.id}` },
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/reconciled/i);
|
||||
expect(
|
||||
(
|
||||
await db.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: t.id },
|
||||
_sum: { amountCents: true },
|
||||
})
|
||||
)._sum.amountCents,
|
||||
).toBe(35);
|
||||
await expect(
|
||||
service.recordBudget(
|
||||
t.id,
|
||||
{
|
||||
amountCents: 66,
|
||||
kind: 'RESERVE',
|
||||
idempotencyKey: `too-much-${t.id}`,
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(/budget/i);
|
||||
});
|
||||
it('concurrent budget reservations never exceed hard cap and replay is harmless', async () => {
|
||||
const t = await task();
|
||||
const result = await Promise.allSettled(
|
||||
Array.from({ length: 8 }, (_, i) =>
|
||||
service.recordBudget(
|
||||
t.id,
|
||||
{
|
||||
amountCents: 30,
|
||||
kind: 'RESERVE',
|
||||
idempotencyKey: `reserve-${t.id}-${i}`,
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(result.filter((x) => x.status === 'fulfilled')).toHaveLength(3);
|
||||
const sum = await db.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: t.id },
|
||||
_sum: { amountCents: true },
|
||||
});
|
||||
expect(sum._sum.amountCents).toBe(90);
|
||||
const first = await db.orchestrationBudgetLedger.findFirstOrThrow({
|
||||
where: { taskId: t.id },
|
||||
});
|
||||
await service.recordBudget(
|
||||
t.id,
|
||||
{
|
||||
amountCents: 30,
|
||||
kind: 'RESERVE',
|
||||
idempotencyKey: first.idempotencyKey,
|
||||
},
|
||||
'agent',
|
||||
);
|
||||
expect(
|
||||
await db.orchestrationBudgetLedger.count({ where: { taskId: t.id } }),
|
||||
).toBe(3);
|
||||
});
|
||||
it('generic transition cannot approve gate 1', async () => {
|
||||
const t = await task('GATE1_PENDING');
|
||||
await expect(
|
||||
service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: WorkflowState.GATE1_APPROVED,
|
||||
expectedVersion: 1,
|
||||
idempotencyKey: `gate-bypass-${n}`,
|
||||
},
|
||||
'ceo',
|
||||
),
|
||||
).rejects.toThrow(/gate/i);
|
||||
expect(
|
||||
(await db.orchestrationTask.findUniqueOrThrow({ where: { id: t.id } }))
|
||||
.state,
|
||||
).toBe('GATE1_PENDING');
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,31 @@
|
||||
import {
|
||||
PrepareWorkflowService,
|
||||
PREPARE_WORKFLOW_CONFIG,
|
||||
} from './prepare-workflow.service';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { KillSwitchService } from './kill-switch.service';
|
||||
import { ModelTierPolicyService } from './model-tier-policy.service';
|
||||
import { OrchestrationController } from './orchestration.controller';
|
||||
import { OrchestrationService } from './orchestration.service';
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [OrchestrationController],
|
||||
providers: [
|
||||
OrchestrationService,
|
||||
KillSwitchService,
|
||||
ModelTierPolicyService,
|
||||
PrepareWorkflowService,
|
||||
{
|
||||
provide: PREPARE_WORKFLOW_CONFIG,
|
||||
useValue: { workerIds: [], stageCiIds: [] },
|
||||
},
|
||||
],
|
||||
exports: [
|
||||
OrchestrationService,
|
||||
KillSwitchService,
|
||||
ModelTierPolicyService,
|
||||
PrepareWorkflowService,
|
||||
],
|
||||
})
|
||||
export class OrchestrationModule {}
|
||||
@@ -0,0 +1,260 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { OrchestrationService } from './orchestration.service';
|
||||
|
||||
function mockPrisma() {
|
||||
const tx: any = {
|
||||
$queryRaw: jest.fn().mockResolvedValue([]),
|
||||
orchestrationTask: {
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
updateMany: jest.fn(),
|
||||
},
|
||||
orchestrationRun: { findUnique: jest.fn(), create: jest.fn() },
|
||||
orchestrationArtifact: { findFirst: jest.fn(), create: jest.fn() },
|
||||
orchestrationAttestation: { create: jest.fn() },
|
||||
orchestrationApprovalDecision: { findUnique: jest.fn(), create: jest.fn() },
|
||||
orchestrationEvent: { findUnique: jest.fn(), create: jest.fn() },
|
||||
orchestrationBudgetLedger: {
|
||||
findUnique: jest.fn(),
|
||||
aggregate: jest.fn(),
|
||||
create: jest.fn(),
|
||||
},
|
||||
orchestrationKillSwitch: { findUnique: jest.fn(), upsert: jest.fn() },
|
||||
};
|
||||
tx.$transaction = jest.fn((cb: any) => Promise.resolve(cb(tx)));
|
||||
return tx;
|
||||
}
|
||||
|
||||
describe('OrchestrationService', () => {
|
||||
let prisma: any;
|
||||
let service: OrchestrationService;
|
||||
beforeEach(() => {
|
||||
prisma = mockPrisma();
|
||||
service = new OrchestrationService(prisma, {
|
||||
assertAllowed: jest.fn(),
|
||||
} as never);
|
||||
});
|
||||
|
||||
it('rejects an unknown kill level before overwriting persisted protection', async () => {
|
||||
await expect(service.setKillSwitch('INVALID_LEVEL','test','admin')).rejects.toThrow(BadRequestException);
|
||||
expect(prisma.orchestrationKillSwitch.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('creates a task and append-only event transactionally', async () => {
|
||||
prisma.orchestrationTask.create.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
state: 'DRAFT',
|
||||
version: 1,
|
||||
});
|
||||
const result = await service.createTask(
|
||||
{
|
||||
key: 'seo-1',
|
||||
title: 'SEO',
|
||||
department: 'SEO',
|
||||
operationMode: 'PREPARE' as never,
|
||||
budgetLimitCents: 1000,
|
||||
},
|
||||
'actor-1',
|
||||
);
|
||||
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
|
||||
expect(prisma.orchestrationTask.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ state: 'DRAFT', version: 1 }),
|
||||
});
|
||||
expect(prisma.orchestrationEvent.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ eventType: 'TASK_CREATED', sequence: 1 }),
|
||||
});
|
||||
expect(result.id).toBe('task-1');
|
||||
});
|
||||
|
||||
it('uses compare-and-swap versioning for transitions', async () => {
|
||||
prisma.orchestrationTask.findUnique.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
state: 'DRAFT',
|
||||
version: 3,
|
||||
});
|
||||
prisma.orchestrationTask.updateMany.mockResolvedValue({ count: 0 });
|
||||
await expect(
|
||||
service.transition(
|
||||
'task-1',
|
||||
{
|
||||
toState: 'GATE1_PENDING' as never,
|
||||
expectedVersion: 3,
|
||||
idempotencyKey: 'i-1',
|
||||
},
|
||||
'actor',
|
||||
),
|
||||
).rejects.toThrow(ConflictException);
|
||||
});
|
||||
|
||||
it('makes gate decisions immutable and idempotent', async () => {
|
||||
const expiresAt = new Date(Date.now() + 10000).toISOString();
|
||||
prisma.orchestrationApprovalDecision.findUnique.mockResolvedValue({
|
||||
id: 'd1',
|
||||
decision: 'APPROVED',
|
||||
gate: 1,
|
||||
taskId: 'task-1',
|
||||
});
|
||||
prisma.orchestrationEvent.findUnique.mockResolvedValue({
|
||||
payload: {
|
||||
fingerprint: JSON.stringify({
|
||||
taskId: 'task-1',
|
||||
gate: 1,
|
||||
dto: {
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: 'gate-1',
|
||||
expiresAt,
|
||||
},
|
||||
actorId: 'ceo',
|
||||
}),
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
service.decideGate(
|
||||
'task-1',
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: 'gate-1',
|
||||
expiresAt,
|
||||
},
|
||||
'ceo',
|
||||
),
|
||||
).resolves.toMatchObject({ id: 'd1' });
|
||||
expect(prisma.orchestrationApprovalDecision.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects an expired approval', async () => {
|
||||
await expect(
|
||||
service.decideGate(
|
||||
'task-1',
|
||||
1,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 2,
|
||||
idempotencyKey: 'gate-expired',
|
||||
expiresAt: new Date(0).toISOString(),
|
||||
},
|
||||
'ceo',
|
||||
),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('binds gate 2 approval to run, artifact hash, commit and environment', async () => {
|
||||
prisma.orchestrationApprovalDecision.findUnique.mockResolvedValue(null);
|
||||
prisma.orchestrationTask.findUnique.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
state: 'GATE2_PENDING',
|
||||
version: 7,
|
||||
});
|
||||
prisma.orchestrationRun.findUnique.mockResolvedValue({
|
||||
id: 'run-1',
|
||||
taskId: 'task-1',
|
||||
commitSha: 'abc123',
|
||||
environment: 'staging',
|
||||
status: 'SUCCEEDED',
|
||||
});
|
||||
prisma.orchestrationArtifact.findFirst.mockResolvedValue({
|
||||
id: 'artifact-1',
|
||||
runId: 'run-1',
|
||||
sha256: 'f'.repeat(64),
|
||||
});
|
||||
prisma.orchestrationTask.updateMany.mockResolvedValue({ count: 1 });
|
||||
prisma.orchestrationApprovalDecision.create.mockResolvedValue({
|
||||
id: 'decision-2',
|
||||
gate: 2,
|
||||
});
|
||||
await service.decideGate(
|
||||
'task-1',
|
||||
2,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 7,
|
||||
idempotencyKey: 'gate-2',
|
||||
expiresAt: new Date(Date.now() + 10000).toISOString(),
|
||||
runId: 'run-1',
|
||||
artifactHash: 'f'.repeat(64),
|
||||
commitSha: 'abc123',
|
||||
environment: 'staging',
|
||||
},
|
||||
'ceo',
|
||||
);
|
||||
expect(prisma.orchestrationApprovalDecision.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
runId: 'run-1',
|
||||
artifactHash: 'f'.repeat(64),
|
||||
commitSha: 'abc123',
|
||||
environment: 'staging',
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it.each(['RUNNING', 'FAILED', 'CANCELLED'])('refuses Gate 2 approval for an unfinished or unsuccessful %s run', async (status) => {
|
||||
prisma.orchestrationTask.findUnique.mockResolvedValue({id:'task-1',state:'GATE2_PENDING',version:7});
|
||||
prisma.orchestrationRun.findUnique.mockResolvedValue({id:'run-1',taskId:'task-1',commitSha:'abc123',environment:'staging',status});
|
||||
prisma.orchestrationArtifact.findFirst.mockResolvedValue({id:'artifact-1'});
|
||||
prisma.orchestrationTask.updateMany.mockResolvedValue({count:1});
|
||||
await expect(service.decideGate('task-1',2,{
|
||||
decision:'APPROVED',expectedVersion:7,idempotencyKey:'failed-run',
|
||||
expiresAt:new Date(Date.now()+10000).toISOString(),runId:'run-1',
|
||||
artifactHash:'f'.repeat(64),commitSha:'abc123',environment:'staging',
|
||||
},'ceo')).rejects.toThrow(/successful run/i);
|
||||
expect(prisma.orchestrationApprovalDecision.create).not.toHaveBeenCalled();
|
||||
expect(prisma.orchestrationTask.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses gate 2 when binding does not match the immutable run', async () => {
|
||||
prisma.orchestrationApprovalDecision.findUnique.mockResolvedValue(null);
|
||||
prisma.orchestrationTask.findUnique.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
state: 'GATE2_PENDING',
|
||||
version: 7,
|
||||
});
|
||||
prisma.orchestrationRun.findUnique.mockResolvedValue({
|
||||
id: 'run-1',
|
||||
taskId: 'task-1',
|
||||
commitSha: 'real',
|
||||
environment: 'staging',
|
||||
});
|
||||
await expect(
|
||||
service.decideGate(
|
||||
'task-1',
|
||||
2,
|
||||
{
|
||||
decision: 'APPROVED',
|
||||
expectedVersion: 7,
|
||||
idempotencyKey: 'gate-bad',
|
||||
expiresAt: new Date(Date.now() + 10000).toISOString(),
|
||||
runId: 'run-1',
|
||||
artifactHash: 'f'.repeat(64),
|
||||
commitSha: 'wrong',
|
||||
environment: 'staging',
|
||||
},
|
||||
'ceo',
|
||||
),
|
||||
).rejects.toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it('enforces hard task budget atomically', async () => {
|
||||
prisma.orchestrationTask.findUnique.mockResolvedValue({
|
||||
id: 'task-1',
|
||||
budgetLimitCents: 1000,
|
||||
});
|
||||
prisma.orchestrationBudgetLedger.aggregate.mockResolvedValue({
|
||||
_sum: { amountCents: 900 },
|
||||
});
|
||||
await expect(
|
||||
service.recordBudget(
|
||||
'task-1',
|
||||
{ amountCents: 101, idempotencyKey: 'cost-1', kind: 'SPEND' },
|
||||
'agent',
|
||||
),
|
||||
).rejects.toThrow(ForbiddenException);
|
||||
expect(prisma.orchestrationBudgetLedger.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,665 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import {
|
||||
CreateOrchestrationTaskDto,
|
||||
GateDecisionDto,
|
||||
RecordBudgetDto,
|
||||
TransitionTaskDto,
|
||||
} from './dto/orchestration.dto';
|
||||
import {
|
||||
KillSwitchLevel,
|
||||
assertTransition,
|
||||
nextStateForGateDecision,
|
||||
OperationMode,
|
||||
WorkflowState,
|
||||
} from './orchestration.domain';
|
||||
import { ModelTierPolicyService } from './model-tier-policy.service';
|
||||
import { KillSwitchService } from './kill-switch.service';
|
||||
@Injectable()
|
||||
export class OrchestrationService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly killSwitch: KillSwitchService,
|
||||
) {}
|
||||
async createTask(dto: CreateOrchestrationTaskDto, actorId: string) {
|
||||
await this.killSwitch.assertAllowed('CREATE_TASK');
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
const task = await tx.orchestrationTask.create({
|
||||
data: {
|
||||
key: dto.key,
|
||||
title: dto.title,
|
||||
department: dto.department,
|
||||
operationMode: dto.operationMode,
|
||||
budgetLimitCents: dto.budgetLimitCents,
|
||||
metadata: dto.metadata ?? {},
|
||||
state: WorkflowState.DRAFT,
|
||||
version: 1,
|
||||
},
|
||||
});
|
||||
await tx.orchestrationEvent.create({
|
||||
data: {
|
||||
taskId: task.id,
|
||||
eventType: 'TASK_CREATED',
|
||||
fromState: null,
|
||||
toState: WorkflowState.DRAFT,
|
||||
sequence: 1,
|
||||
actorId,
|
||||
payload: { key: dto.key },
|
||||
},
|
||||
});
|
||||
return task;
|
||||
});
|
||||
}
|
||||
async transition(id: string, dto: TransitionTaskDto, actorId: string) {
|
||||
if (
|
||||
[
|
||||
WorkflowState.GATE1_APPROVED,
|
||||
WorkflowState.GATE2_APPROVED,
|
||||
WorkflowState.RELEASING,
|
||||
WorkflowState.RUNNING,
|
||||
WorkflowState.VERIFYING,
|
||||
WorkflowState.PRODUCTION_VERIFYING,
|
||||
WorkflowState.LIVE_VERIFIED,
|
||||
WorkflowState.MEASURING,
|
||||
WorkflowState.CLOSED,
|
||||
].includes(dto.toState)
|
||||
)
|
||||
throw new ForbiddenException(
|
||||
'Gate approvals and release require dedicated commands',
|
||||
);
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
await tx.$queryRaw`SELECT id FROM orchestration_tasks WHERE id = ${id}::uuid FOR UPDATE`;
|
||||
const fingerprint = JSON.stringify({ id, dto, actorId });
|
||||
const replay = await tx.orchestrationEvent.findUnique({
|
||||
where: { idempotencyKey: dto.idempotencyKey },
|
||||
});
|
||||
if (replay) {
|
||||
if (replay.payload.fingerprint !== fingerprint)
|
||||
throw new ConflictException('Idempotency payload mismatch');
|
||||
return replay.payload.result;
|
||||
}
|
||||
const existing = await tx.orchestrationTask.findUnique({ where: { id } });
|
||||
if (!existing)
|
||||
throw new NotFoundException(`Orchestration task ${id} not found`);
|
||||
if (existing.state === WorkflowState.FAILED)
|
||||
throw new ForbiddenException('Retries require dedicated run command');
|
||||
assertTransition(existing.state, dto.toState);
|
||||
await this.killSwitch.assertAllowed(
|
||||
[
|
||||
WorkflowState.READY,
|
||||
WorkflowState.CLAIMED,
|
||||
WorkflowState.RUNNING,
|
||||
WorkflowState.VERIFYING,
|
||||
WorkflowState.GATE2_PENDING,
|
||||
].includes(dto.toState)
|
||||
? 'RUN_AGENT'
|
||||
: 'OBSERVE',
|
||||
);
|
||||
if ([WorkflowState.READY, WorkflowState.CLAIMED].includes(dto.toState))
|
||||
await this.killSwitch.assertAllowed('CLAIM_TASK');
|
||||
let selectedTier = existing.modelTier;
|
||||
if (dto.toState === WorkflowState.READY) {
|
||||
const dependencies = await tx.orchestrationDependency.findMany({
|
||||
where: { taskId: id },
|
||||
include: { dependsOnTask: true },
|
||||
});
|
||||
if (dependencies.some((d: any) => d.dependsOnTask.state !== 'CLOSED'))
|
||||
throw new ForbiddenException('Unresolved dependency');
|
||||
const costs = await tx.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId: id },
|
||||
_sum: { amountCents: true },
|
||||
});
|
||||
selectedTier = new ModelTierPolicyService().select({
|
||||
complexity: Number(existing.metadata?.complexity ?? 0),
|
||||
risk: Number(existing.metadata?.risk ?? 0),
|
||||
operationMode: existing.operationMode,
|
||||
remainingBudgetCents:
|
||||
existing.budgetLimitCents - (costs._sum.amountCents ?? 0),
|
||||
});
|
||||
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('Gate 1 approval missing or expired');
|
||||
}
|
||||
if (
|
||||
existing.operationMode === OperationMode.MUTATE_PRODUCTION &&
|
||||
dto.toState === WorkflowState.RELEASING
|
||||
)
|
||||
await this.killSwitch.assertAllowed('MUTATE_PRODUCTION');
|
||||
const changed = await tx.orchestrationTask.updateMany({
|
||||
where: { id, version: dto.expectedVersion, state: existing.state },
|
||||
data: {
|
||||
state: dto.toState,
|
||||
modelTier: selectedTier,
|
||||
version: { increment: 1 },
|
||||
},
|
||||
});
|
||||
if (changed.count !== 1)
|
||||
throw new ConflictException(
|
||||
'Task version or state changed; reload before retrying',
|
||||
);
|
||||
await tx.orchestrationEvent.create({
|
||||
data: {
|
||||
taskId: id,
|
||||
eventType: 'STATE_TRANSITION',
|
||||
fromState: existing.state,
|
||||
toState: dto.toState,
|
||||
sequence: dto.expectedVersion + 1,
|
||||
actorId,
|
||||
idempotencyKey: dto.idempotencyKey,
|
||||
payload: {
|
||||
fingerprint,
|
||||
result: JSON.parse(
|
||||
JSON.stringify({
|
||||
...existing,
|
||||
state: dto.toState,
|
||||
modelTier: selectedTier,
|
||||
version: dto.expectedVersion + 1,
|
||||
}),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
return JSON.parse(
|
||||
JSON.stringify({
|
||||
...existing,
|
||||
state: dto.toState,
|
||||
modelTier: selectedTier,
|
||||
version: dto.expectedVersion + 1,
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
async decideGate(
|
||||
taskId: string,
|
||||
gate: 1 | 2,
|
||||
dto: GateDecisionDto,
|
||||
actorId: string,
|
||||
) {
|
||||
if (![1, 2].includes(gate)) throw new BadRequestException('Invalid gate');
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
await tx.$queryRaw`SELECT id FROM orchestration_tasks WHERE id = ${taskId}::uuid FOR UPDATE`;
|
||||
const fingerprint = JSON.stringify({ taskId, gate, dto, actorId });
|
||||
const prior = await tx.orchestrationApprovalDecision.findUnique({
|
||||
where: { idempotencyKey: dto.idempotencyKey },
|
||||
});
|
||||
if (prior) {
|
||||
const event = await tx.orchestrationEvent.findUnique({
|
||||
where: { idempotencyKey: `event:${dto.idempotencyKey}` },
|
||||
});
|
||||
if (event?.payload?.fingerprint !== fingerprint)
|
||||
throw new ConflictException('Idempotency payload mismatch');
|
||||
return prior;
|
||||
}
|
||||
if (
|
||||
!Number.isFinite(Date.parse(dto.expiresAt)) ||
|
||||
new Date(dto.expiresAt) <= new Date()
|
||||
)
|
||||
throw new BadRequestException('Approval decision has expired');
|
||||
await this.killSwitch.assertAllowed('OBSERVE');
|
||||
const task = await tx.orchestrationTask.findUnique({
|
||||
where: { id: taskId },
|
||||
});
|
||||
if (!task)
|
||||
throw new NotFoundException(`Orchestration task ${taskId} not found`);
|
||||
const expected =
|
||||
gate === 1 ? WorkflowState.GATE1_PENDING : WorkflowState.GATE2_PENDING;
|
||||
if (task.state !== expected)
|
||||
throw new ConflictException(`Gate ${gate} requires ${expected}`);
|
||||
if (gate === 2 && dto.decision === 'APPROVED') {
|
||||
if (
|
||||
!dto.runId ||
|
||||
!dto.artifactHash ||
|
||||
!dto.commitSha ||
|
||||
!dto.environment
|
||||
)
|
||||
throw new BadRequestException(
|
||||
'Gate 2 requires runId, artifactHash, commitSha and environment',
|
||||
);
|
||||
const run = await tx.orchestrationRun.findUnique({
|
||||
where: { id: dto.runId },
|
||||
});
|
||||
if (
|
||||
!run ||
|
||||
run.taskId !== taskId ||
|
||||
run.commitSha !== dto.commitSha ||
|
||||
run.environment !== dto.environment
|
||||
)
|
||||
throw new ForbiddenException(
|
||||
'Gate 2 binding does not match immutable run',
|
||||
);
|
||||
if (run.status !== 'SUCCEEDED')
|
||||
throw new ForbiddenException('Gate 2 requires a successful run');
|
||||
const artifact = await tx.orchestrationArtifact.findFirst({
|
||||
where: { runId: dto.runId, sha256: dto.artifactHash },
|
||||
});
|
||||
if (!artifact)
|
||||
throw new ForbiddenException(
|
||||
'Gate 2 artifact hash is not registered for run',
|
||||
);
|
||||
}
|
||||
const next = nextStateForGateDecision(gate, dto.decision);
|
||||
const changed = await tx.orchestrationTask.updateMany({
|
||||
where: { id: taskId, version: dto.expectedVersion, state: expected },
|
||||
data: { state: next, version: { increment: 1 } },
|
||||
});
|
||||
if (changed.count !== 1)
|
||||
throw new ConflictException(
|
||||
'Task version or state changed; approval not applied',
|
||||
);
|
||||
const decision = await tx.orchestrationApprovalDecision.create({
|
||||
data: {
|
||||
taskId,
|
||||
gate,
|
||||
decision: dto.decision,
|
||||
actorId,
|
||||
notes: dto.notes,
|
||||
expiresAt: new Date(dto.expiresAt),
|
||||
idempotencyKey: dto.idempotencyKey,
|
||||
runId: dto.runId,
|
||||
artifactHash: dto.artifactHash,
|
||||
commitSha: dto.commitSha,
|
||||
environment: dto.environment,
|
||||
},
|
||||
});
|
||||
await tx.orchestrationEvent.create({
|
||||
data: {
|
||||
taskId,
|
||||
eventType: `GATE${gate}_${dto.decision}`,
|
||||
fromState: expected,
|
||||
toState: next,
|
||||
sequence: dto.expectedVersion + 1,
|
||||
actorId,
|
||||
idempotencyKey: `event:${dto.idempotencyKey}`,
|
||||
payload: { decisionId: decision.id, fingerprint },
|
||||
},
|
||||
});
|
||||
return decision;
|
||||
});
|
||||
}
|
||||
async recordBudget(taskId: string, dto: RecordBudgetDto, actorId: string) {
|
||||
if (
|
||||
!Number.isSafeInteger(dto.amountCents) ||
|
||||
dto.amountCents < 1 ||
|
||||
!['RESERVE', 'SPEND'].includes(dto.kind)
|
||||
)
|
||||
throw new BadRequestException(
|
||||
'Use RESERVE or SPEND with positive integer cents',
|
||||
);
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
await tx.$queryRaw`SELECT id FROM orchestration_tasks WHERE id = ${taskId}::uuid FOR UPDATE`;
|
||||
const prior = await tx.orchestrationBudgetLedger.findUnique({
|
||||
where: { idempotencyKey: dto.idempotencyKey },
|
||||
});
|
||||
if (prior) {
|
||||
if (
|
||||
prior.taskId !== taskId ||
|
||||
prior.kind !== dto.kind ||
|
||||
prior.amountCents !== dto.amountCents ||
|
||||
prior.actorId !== actorId ||
|
||||
JSON.stringify(prior.metadata) !== JSON.stringify(dto.metadata ?? {})
|
||||
)
|
||||
throw new ConflictException('Idempotency payload mismatch');
|
||||
return prior;
|
||||
}
|
||||
await this.killSwitch.assertAllowed('RUN_AGENT');
|
||||
const task = await tx.orchestrationTask.findUnique({
|
||||
where: { id: taskId },
|
||||
});
|
||||
if (!task)
|
||||
throw new NotFoundException(`Orchestration task ${taskId} not found`);
|
||||
const sum = await tx.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId },
|
||||
_sum: { amountCents: true },
|
||||
});
|
||||
if ((sum._sum.amountCents ?? 0) + dto.amountCents > task.budgetLimitCents)
|
||||
throw new ForbiddenException('Hard task budget exceeded');
|
||||
return tx.orchestrationBudgetLedger.create({
|
||||
data: {
|
||||
taskId,
|
||||
amountCents: dto.amountCents,
|
||||
kind: dto.kind,
|
||||
idempotencyKey: dto.idempotencyKey,
|
||||
actorId,
|
||||
metadata: dto.metadata ?? {},
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
async command(taskId: string, command: string, dto: any, actorId: string) {
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
await tx.$queryRaw`SELECT id FROM orchestration_tasks WHERE id = ${taskId}::uuid FOR UPDATE`;
|
||||
const fingerprint = JSON.stringify({ taskId, command, dto, actorId });
|
||||
const replay = await tx.orchestrationEvent.findUnique({
|
||||
where: { idempotencyKey: dto.idempotencyKey },
|
||||
});
|
||||
if (replay) {
|
||||
if (replay.payload.fingerprint !== fingerprint)
|
||||
throw new ConflictException('Idempotency payload mismatch');
|
||||
return replay.payload.result;
|
||||
}
|
||||
const task = await tx.orchestrationTask.findUnique({
|
||||
where: { id: taskId },
|
||||
});
|
||||
if (!task) throw new NotFoundException('Task not found');
|
||||
if (task.version !== dto.expectedVersion)
|
||||
throw new ConflictException('Stale task version');
|
||||
await this.killSwitch.assertAllowed('RUN_AGENT');
|
||||
let result: any;
|
||||
let state = task.state;
|
||||
if (command === 'RUN_CREATE') {
|
||||
if (
|
||||
!/^[a-f0-9]{40,64}$/.test(dto.commitSha) ||
|
||||
!['development', 'staging', 'production'].includes(dto.environment)
|
||||
)
|
||||
throw new BadRequestException('Invalid immutable run binding');
|
||||
const last = await tx.orchestrationRun.findFirst({
|
||||
where: { taskId },
|
||||
orderBy: { attempt: 'desc' },
|
||||
});
|
||||
if (
|
||||
last &&
|
||||
(last.status !== 'FAILED' ||
|
||||
!['TRANSIENT', 'RATE_LIMITED', 'DEPENDENCY'].includes(
|
||||
last.retryClass,
|
||||
) ||
|
||||
last.attempt >= 3)
|
||||
)
|
||||
throw new ForbiddenException('Retry denied or exhausted');
|
||||
if (!last && task.state !== 'CLAIMED')
|
||||
throw new ConflictException('Run requires CLAIMED task');
|
||||
result = await tx.orchestrationRun.create({
|
||||
data: {
|
||||
taskId,
|
||||
attempt: (last?.attempt ?? 0) + 1,
|
||||
status: 'RUNNING',
|
||||
commitSha: dto.commitSha,
|
||||
environment: dto.environment,
|
||||
idempotencyKey: dto.idempotencyKey,
|
||||
startedAt: new Date(),
|
||||
},
|
||||
});
|
||||
state = 'RUNNING';
|
||||
} else if (command === 'RUN_FINISH') {
|
||||
const run = await tx.orchestrationRun.findUnique({
|
||||
where: { id: dto.runId },
|
||||
});
|
||||
if (
|
||||
!run ||
|
||||
run.taskId !== taskId ||
|
||||
run.status !== 'RUNNING' ||
|
||||
task.state !== 'RUNNING'
|
||||
)
|
||||
throw new ConflictException('Active run required');
|
||||
if (
|
||||
!['SUCCEEDED', 'FAILED'].includes(dto.status) ||
|
||||
(dto.status === 'FAILED' &&
|
||||
![
|
||||
'TRANSIENT',
|
||||
'RATE_LIMITED',
|
||||
'DEPENDENCY',
|
||||
'VALIDATION',
|
||||
'POLICY',
|
||||
'PERMANENT',
|
||||
].includes(dto.retryClass))
|
||||
)
|
||||
throw new BadRequestException('Invalid outcome taxonomy');
|
||||
result = await tx.orchestrationRun.update({
|
||||
where: { id: run.id },
|
||||
data: {
|
||||
status: dto.status,
|
||||
retryClass: dto.status === 'FAILED' ? dto.retryClass : null,
|
||||
finishedAt: new Date(),
|
||||
},
|
||||
});
|
||||
state = dto.status === 'FAILED' ? 'FAILED' : 'VERIFYING';
|
||||
} else if (command === 'ARTIFACT_ADD' || command === 'ATTESTATION_ADD') {
|
||||
const run = await tx.orchestrationRun.findUnique({
|
||||
where: { id: dto.runId },
|
||||
});
|
||||
if (
|
||||
!run ||
|
||||
run.taskId !== taskId ||
|
||||
!['RUNNING', 'VERIFYING'].includes(task.state)
|
||||
)
|
||||
throw new ConflictException('Owned active run required');
|
||||
const hash = command === 'ARTIFACT_ADD' ? dto.sha256 : dto.subjectHash;
|
||||
if (!/^[a-f0-9]{64}$/.test(hash) || !dto.kind)
|
||||
throw new BadRequestException('Invalid artifact hash or kind');
|
||||
if (command === 'ARTIFACT_ADD') {
|
||||
if (!/^https:\/\//.test(dto.uri))
|
||||
throw new BadRequestException('Artifact URI must be HTTPS');
|
||||
result = await tx.orchestrationArtifact.create({
|
||||
data: { runId: run.id, kind: dto.kind, sha256: hash, uri: dto.uri },
|
||||
});
|
||||
} else {
|
||||
if (
|
||||
!(await tx.orchestrationArtifact.findFirst({
|
||||
where: { runId: run.id, sha256: hash },
|
||||
}))
|
||||
)
|
||||
throw new ForbiddenException(
|
||||
'Attestation subject is not a registered artifact',
|
||||
);
|
||||
result = await tx.orchestrationAttestation.create({
|
||||
data: {
|
||||
runId: run.id,
|
||||
kind: dto.kind,
|
||||
subjectHash: hash,
|
||||
predicate: dto.predicate ?? {},
|
||||
signer: actorId,
|
||||
signature: dto.signature,
|
||||
},
|
||||
});
|
||||
}
|
||||
} else if (command === 'DEPENDENCY_ADD') {
|
||||
if (task.state !== 'DRAFT')
|
||||
throw new ConflictException(
|
||||
'Dependencies are frozen after submission',
|
||||
);
|
||||
await tx.$executeRaw`LOCK TABLE orchestration_dependencies IN EXCLUSIVE MODE`;
|
||||
const cycles =
|
||||
await tx.$queryRaw`WITH RECURSIVE chain(id) AS (SELECT ${dto.dependsOnTaskId}::uuid UNION SELECT d.depends_on_task_id FROM orchestration_dependencies d JOIN chain c ON d.task_id=c.id) SELECT id FROM chain WHERE id=${taskId}::uuid`;
|
||||
if (cycles.length) throw new ForbiddenException('Dependency cycle');
|
||||
result = await tx.orchestrationDependency.create({
|
||||
data: { taskId, dependsOnTaskId: dto.dependsOnTaskId },
|
||||
});
|
||||
} else if (command === 'RELEASE_AUTHORIZE') {
|
||||
await this.killSwitch.assertAllowed('MUTATE_PRODUCTION');
|
||||
if (task.state !== 'GATE2_APPROVED')
|
||||
throw new ConflictException(
|
||||
'Gate 2 approval required; already consumed or invalid state',
|
||||
);
|
||||
const approval = await tx.orchestrationApprovalDecision.findUnique({
|
||||
where: { id: dto.approvalId },
|
||||
});
|
||||
if (
|
||||
!approval ||
|
||||
approval.taskId !== taskId ||
|
||||
approval.gate !== 2 ||
|
||||
approval.decision !== 'APPROVED' ||
|
||||
approval.expiresAt <= new Date()
|
||||
)
|
||||
throw new ForbiddenException('Gate 2 missing or expired');
|
||||
for (const key of ['runId', 'artifactHash', 'commitSha', 'environment'])
|
||||
if (approval[key] !== dto[key])
|
||||
throw new ForbiddenException('Release binding mismatch');
|
||||
const run = await tx.orchestrationRun.findUnique({
|
||||
where: { id: dto.runId },
|
||||
});
|
||||
if (
|
||||
!run ||
|
||||
run.taskId !== taskId ||
|
||||
run.status !== 'SUCCEEDED' ||
|
||||
run.commitSha !== dto.commitSha ||
|
||||
run.environment !== dto.environment
|
||||
)
|
||||
throw new ForbiddenException('Run binding mismatch');
|
||||
if (
|
||||
!(await tx.orchestrationArtifact.findFirst({
|
||||
where: { runId: run.id, sha256: dto.artifactHash },
|
||||
})) ||
|
||||
!(await tx.orchestrationAttestation.findFirst({
|
||||
where: {
|
||||
runId: run.id,
|
||||
subjectHash: dto.artifactHash,
|
||||
kind: 'TEST',
|
||||
},
|
||||
}))
|
||||
)
|
||||
throw new ForbiddenException('Artifact evidence missing');
|
||||
result = {
|
||||
authorized: true,
|
||||
approvalId: approval.id,
|
||||
runId: run.id,
|
||||
artifactHash: dto.artifactHash,
|
||||
commitSha: dto.commitSha,
|
||||
environment: dto.environment,
|
||||
execution: 'CI_CD_ONLY',
|
||||
};
|
||||
state = 'RELEASING';
|
||||
} else throw new BadRequestException('Unknown command');
|
||||
await tx.orchestrationTask.update({
|
||||
where: { id: taskId },
|
||||
data: { state, version: { increment: 1 } },
|
||||
});
|
||||
const serialized = JSON.parse(JSON.stringify(result));
|
||||
await tx.orchestrationEvent.create({
|
||||
data: {
|
||||
taskId,
|
||||
eventType: command,
|
||||
fromState: task.state,
|
||||
toState: state,
|
||||
sequence: task.version + 1,
|
||||
actorId,
|
||||
idempotencyKey: dto.idempotencyKey,
|
||||
payload: { fingerprint, result: serialized },
|
||||
},
|
||||
});
|
||||
return serialized;
|
||||
});
|
||||
}
|
||||
async reconcileBudget(
|
||||
taskId: string,
|
||||
dto: { reservationId: string; actualCents: number; idempotencyKey: string },
|
||||
actorId: string,
|
||||
) {
|
||||
await this.killSwitch.assertAllowed('OBSERVE');
|
||||
if (!Number.isSafeInteger(dto.actualCents) || dto.actualCents < 0)
|
||||
throw new BadRequestException('Invalid actual cost');
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
await tx.$queryRaw`SELECT id FROM orchestration_tasks WHERE id = ${taskId}::uuid FOR UPDATE`;
|
||||
const prior = await tx.orchestrationBudgetLedger.findUnique({
|
||||
where: { idempotencyKey: dto.idempotencyKey },
|
||||
});
|
||||
if (prior) {
|
||||
if (
|
||||
prior.taskId !== taskId ||
|
||||
prior.actorId !== actorId ||
|
||||
prior.metadata.reservationId !== dto.reservationId ||
|
||||
prior.metadata.actualCents !== dto.actualCents
|
||||
)
|
||||
throw new ConflictException('Idempotency payload mismatch');
|
||||
return prior;
|
||||
}
|
||||
const reservation = await tx.orchestrationBudgetLedger.findUnique({
|
||||
where: { id: dto.reservationId },
|
||||
});
|
||||
if (
|
||||
!reservation ||
|
||||
reservation.taskId !== taskId ||
|
||||
reservation.kind !== 'RESERVE'
|
||||
)
|
||||
throw new BadRequestException('Reservation not found');
|
||||
if (
|
||||
await tx.orchestrationBudgetLedger.findFirst({
|
||||
where: {
|
||||
taskId,
|
||||
kind: 'RECONCILE',
|
||||
metadata: { path: ['reservationId'], equals: dto.reservationId },
|
||||
},
|
||||
})
|
||||
)
|
||||
throw new ConflictException('Reservation already reconciled');
|
||||
const task = await tx.orchestrationTask.findUnique({
|
||||
where: { id: taskId },
|
||||
});
|
||||
const total = await tx.orchestrationBudgetLedger.aggregate({
|
||||
where: { taskId },
|
||||
_sum: { amountCents: true },
|
||||
});
|
||||
const delta = dto.actualCents - reservation.amountCents;
|
||||
if (total._sum.amountCents + delta > task.budgetLimitCents)
|
||||
throw new ForbiddenException('Hard task budget exceeded');
|
||||
return tx.orchestrationBudgetLedger.create({
|
||||
data: {
|
||||
taskId,
|
||||
kind: 'RECONCILE',
|
||||
amountCents: delta,
|
||||
idempotencyKey: dto.idempotencyKey,
|
||||
actorId,
|
||||
metadata: {
|
||||
reservationId: dto.reservationId,
|
||||
actualCents: dto.actualCents,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
async findAll() {
|
||||
await this.killSwitch.assertAllowed('OBSERVE');
|
||||
return (this.prisma as any).orchestrationTask.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
}
|
||||
async findOne(id: string) {
|
||||
await this.killSwitch.assertAllowed('OBSERVE');
|
||||
const task = await (this.prisma as any).orchestrationTask.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
runs: { include: { artifacts: true, attestations: true } },
|
||||
dependencies: true,
|
||||
decisions: true,
|
||||
events: { orderBy: { sequence: 'asc' } },
|
||||
budgetLedger: true,
|
||||
},
|
||||
});
|
||||
if (!task)
|
||||
throw new NotFoundException(`Orchestration task ${id} not found`);
|
||||
return task;
|
||||
}
|
||||
async setKillSwitch(level: string, reason: string, actorId: string) {
|
||||
if (!Object.values(KillSwitchLevel).includes(level as KillSwitchLevel))
|
||||
throw new BadRequestException('Invalid kill switch level');
|
||||
return await (this.prisma as any).$transaction(async (tx: any) => {
|
||||
const value = await tx.orchestrationKillSwitch.upsert({
|
||||
where: { scope: 'GLOBAL' },
|
||||
create: { scope: 'GLOBAL', level, active: true, reason, actorId },
|
||||
update: {
|
||||
level,
|
||||
active: true,
|
||||
reason,
|
||||
actorId,
|
||||
version: { increment: 1 },
|
||||
},
|
||||
});
|
||||
await tx.orchestrationEvent.create({
|
||||
data: {
|
||||
eventType: 'KILL_SWITCH_CHANGED',
|
||||
sequence: value.version ?? 1,
|
||||
actorId,
|
||||
payload: { scope: 'GLOBAL', level, reason },
|
||||
},
|
||||
});
|
||||
return value;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
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 = {
|
||||
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('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())
|
||||
.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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,559 @@
|
||||
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 {
|
||||
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 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 (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) {
|
||||
this.identity(a, ['SUPER_ADMIN']);
|
||||
if (gate !== 1)
|
||||
throw new ForbiddenException(
|
||||
'Gate2 decisions and release remain disabled',
|
||||
);
|
||||
if (
|
||||
!['APPROVED', 'REJECTED'].includes(dto.decision) ||
|
||||
!Number.isFinite(Date.parse(dto.expiresAt)) ||
|
||||
Date.parse(dto.expiresAt) <= Date.now() ||
|
||||
Date.parse(dto.expiresAt) > Date.now() + 86400000
|
||||
)
|
||||
throw new BadRequestException(
|
||||
'Decision requires future expiry within 24 hours',
|
||||
);
|
||||
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');
|
||||
if (t.state !== 'GATE1_PENDING')
|
||||
throw new ConflictException('Gate1 pending required');
|
||||
await tx.orchestrationApprovalDecision.create({
|
||||
data: {
|
||||
taskId: id,
|
||||
gate: 1,
|
||||
decision: dto.decision,
|
||||
actorId: a.id,
|
||||
expiresAt: new Date(dto.expiresAt),
|
||||
idempotencyKey: `decision:${dto.idempotencyKey}`,
|
||||
},
|
||||
});
|
||||
return this.event(
|
||||
tx,
|
||||
t,
|
||||
dto.decision === 'APPROVED' ? 'GATE1_APPROVED' : 'REJECTED',
|
||||
a,
|
||||
dto.idempotencyKey,
|
||||
'PREPARE_GATE1',
|
||||
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 o.status='PENDING' 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 o.status='PENDING' 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,
|
||||
);
|
||||
});
|
||||
}
|
||||
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 actions: string[] = [];
|
||||
if (safe && owner && t.state === 'DRAFT') actions.push('SUBMIT_GATE1');
|
||||
if (safe && owner && t.state === 'GATE1_APPROVED')
|
||||
actions.push('QUEUE_PREPARE');
|
||||
if (
|
||||
safe &&
|
||||
a?.role === 'SUPER_ADMIN' &&
|
||||
t.metadata?.createdBy !== a.id &&
|
||||
t.state === 'GATE1_PENDING'
|
||||
)
|
||||
actions.push('APPROVE_GATE1', 'REJECT_GATE1');
|
||||
return {
|
||||
...t,
|
||||
metadata: safe
|
||||
? {
|
||||
scope: t.metadata.scope,
|
||||
...(t.metadata.workflowScope === 'STAGE_PREPARE'
|
||||
? { acceptanceCriteria: t.metadata.acceptanceCriteria }
|
||||
: {}),
|
||||
environment: 'staging',
|
||||
commitSha: t.metadata.commitSha,
|
||||
}
|
||||
: {},
|
||||
availableActions: actions,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,513 @@
|
||||
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 service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: WorkflowState.READY,
|
||||
expectedVersion: t.version,
|
||||
idempotencyKey: `ready-${t.id}`,
|
||||
},
|
||||
admin,
|
||||
);
|
||||
}
|
||||
afterAll(async () => {
|
||||
await db.$disconnect();
|
||||
});
|
||||
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,
|
||||
);
|
||||
await service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: 'READY',
|
||||
expectedVersion: current.version,
|
||||
idempotencyKey: `q-${t.id}`,
|
||||
},
|
||||
admin,
|
||||
);
|
||||
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,
|
||||
);
|
||||
const results = await Promise.allSettled(
|
||||
['one', 'two'].map((k) =>
|
||||
service.transition(
|
||||
t.id,
|
||||
{
|
||||
toState: 'READY',
|
||||
expectedVersion: t.version,
|
||||
idempotencyKey: `${k}-${t.id}`,
|
||||
},
|
||||
admin,
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
|
||||
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),
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { RouterUsageAdapter } from './router-usage.adapter';
|
||||
const stats = {totalRequests:0,totalPromptTokens:0,totalCompletionTokens:0,totalCachedTokens:0,byModel:{},byProvider:{},byAccount:{}};
|
||||
describe('bounded read-only adapter', () => {
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
it('uses only authenticated GET stats with a validated period and never follows redirects', async () => {
|
||||
const fetcher = jest.spyOn(global, 'fetch').mockResolvedValue(new Response(JSON.stringify(stats)));
|
||||
const adapter = new RouterUsageAdapter();
|
||||
process.env.ROUTER_USAGE_BASE_URL = 'https://nr.parsaaghayi.ir';
|
||||
process.env.ROUTER_USAGE_CLI_TOKEN = 'server-only-secret';
|
||||
const result = await adapter.summary('24h');
|
||||
expect(result.status).toBe('available');
|
||||
expect(result.attribution).toEqual({scope:'9router_total',hermes:null,additive:false});
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
expect(fetcher).toHaveBeenCalledWith('https://nr.parsaaghayi.ir/api/usage/stats?period=24h', expect.objectContaining({method:'GET',redirect:'error',headers:{'x-9r-cli-token':'server-only-secret',Accept:'application/json'}}));
|
||||
expect(JSON.stringify(result)).not.toContain('server-only-secret');
|
||||
});
|
||||
it('rejects invalid time filters before IO', async () => {
|
||||
const fetcher = jest.spyOn(global,'fetch');
|
||||
await expect(new RouterUsageAdapter().summary('../providers')).rejects.toThrow();
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
it('fails closed when credential is missing', async () => {
|
||||
delete process.env.ROUTER_USAGE_CLI_TOKEN;
|
||||
const fetcher = jest.spyOn(global,'fetch');
|
||||
const result = await new RouterUsageAdapter().summary('7d');
|
||||
expect(result).toMatchObject({status:'unavailable',data:null,reason:'not_configured'});
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([401,403,429,500])('returns unknown data without upstream error text for %s', async status => {
|
||||
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
|
||||
jest.spyOn(global,'fetch').mockResolvedValue(new Response('credential-secret',{status}));
|
||||
const result = await new RouterUsageAdapter().summary('7d');
|
||||
expect(result).toMatchObject({status:'unavailable',data:null,reason:'upstream_unavailable'});
|
||||
expect(JSON.stringify(result)).not.toContain('credential-secret');
|
||||
});
|
||||
it('rejects oversized bodies even without content length', async () => {
|
||||
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
|
||||
jest.spyOn(global,'fetch').mockResolvedValue(new Response('x'.repeat(1048577)));
|
||||
expect(await new RouterUsageAdapter().summary('7d')).toMatchObject({status:'unavailable',data:null});
|
||||
});
|
||||
it('does not return stale last-good totals after a failure', async () => {
|
||||
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
|
||||
jest.spyOn(global,'fetch').mockResolvedValueOnce(new Response(JSON.stringify(stats))).mockRejectedValueOnce(new Error('token-secret'));
|
||||
const adapter=new RouterUsageAdapter();
|
||||
expect((await adapter.summary('7d')).status).toBe('available');
|
||||
expect(await adapter.summary('7d')).toMatchObject({status:'unavailable',data:null});
|
||||
});
|
||||
});
|
||||
|
||||
describe('transport boundaries', () => {
|
||||
afterEach(()=>jest.restoreAllMocks());
|
||||
it('never sends credentials to a configured alternate origin', async()=>{
|
||||
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
|
||||
process.env.ROUTER_USAGE_BASE_URL='https://attacker.invalid';
|
||||
const fetcher=jest.spyOn(global,'fetch');
|
||||
expect(await new RouterUsageAdapter().summary()).toMatchObject({status:'unavailable',reason:'invalid_configuration'});
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
delete process.env.ROUTER_USAGE_BASE_URL;
|
||||
});
|
||||
it('bounds simultaneous upstream calls and exposes no stale totals', async()=>{
|
||||
process.env.ROUTER_USAGE_CLI_TOKEN='secret';
|
||||
let resolve!: (value: Response) => void;
|
||||
const pending=new Promise<Response>(r=>{resolve=r;});
|
||||
jest.spyOn(global,'fetch').mockReturnValue(pending);
|
||||
const adapter=new RouterUsageAdapter();
|
||||
const calls=Array.from({length:4},()=>adapter.summary());
|
||||
expect(await adapter.summary()).toMatchObject({status:'unavailable',reason:'busy',data:null});
|
||||
resolve(new Response('',{status:503}));
|
||||
await Promise.all(calls);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { normalizeStats } from './router-usage.contract';
|
||||
export const ROUTER_PERIODS = ['today','24h','7d','30d','60d','all'] as const;
|
||||
@Injectable()
|
||||
export class RouterUsageAdapter {
|
||||
private active = 0;
|
||||
async summary(period = '7d') {
|
||||
if (!ROUTER_PERIODS.includes(period as typeof ROUTER_PERIODS[number])) throw new BadRequestException('Invalid period');
|
||||
const base = {source:'9router' as const,period,attribution:{scope:'9router_total',hermes:null,additive:false},
|
||||
capabilities:{errors:false,reasoningTokens:false,cacheWriteTokens:false,quota:false,customTimeRange:false},
|
||||
freshness:{retrievedAt:null as string | null,sourceUpdatedAt:null,stale:null as boolean | null}};
|
||||
const unavailable = (reason: string) => ({...base,status:'unavailable' as const,reason,data:null});
|
||||
const token=process.env.ROUTER_USAGE_CLI_TOKEN;
|
||||
if (!token) return unavailable('not_configured');
|
||||
if (this.active >= 4) return unavailable('busy');
|
||||
this.active++;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(),5000);
|
||||
try {
|
||||
const url=new URL(process.env.ROUTER_USAGE_BASE_URL || 'https://nr.parsaaghayi.ir');
|
||||
if (url.origin !== 'https://nr.parsaaghayi.ir' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) return unavailable('invalid_configuration');
|
||||
const response=await fetch(`${url.origin}/api/usage/stats?period=${period}`,{
|
||||
method:'GET',redirect:'error',signal:controller.signal,
|
||||
headers:{'x-9r-cli-token':token,Accept:'application/json'},
|
||||
});
|
||||
if (!response.ok || !response.body) throw new Error('Upstream unavailable');
|
||||
const reader=response.body.getReader();
|
||||
const chunks:Uint8Array[]=[];
|
||||
let size=0;
|
||||
try {
|
||||
while (true) {
|
||||
const {done,value}=await reader.read();
|
||||
if (done) break;
|
||||
size+=value.byteLength;
|
||||
if (size>1048576) {await reader.cancel(); throw new Error('Response too large');}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally { reader.releaseLock(); }
|
||||
const data=normalizeStats(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
||||
return {...base,status:'available' as const,reason:null,data,
|
||||
freshness:{retrievedAt:new Date().toISOString(),sourceUpdatedAt:null,stale:null}};
|
||||
} catch { return unavailable('upstream_unavailable'); }
|
||||
finally { clearTimeout(timeout); this.active--; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
type RecordValue = Record<string, unknown>;
|
||||
export function record(value: unknown): RecordValue {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid upstream schema');
|
||||
return value as RecordValue;
|
||||
}
|
||||
function count(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
|
||||
}
|
||||
function identifier(value: unknown): string | null {
|
||||
return typeof value === 'string' && /^[a-zA-Z0-9_./:@()+ -]{1,180}$/.test(value) && !value.includes('@') && !/^(sk-|Bearer )/i.test(value) ? value : null;
|
||||
}
|
||||
function metrics(row: RecordValue, prefix = '') {
|
||||
const key = (name: string) => prefix ? prefix + name[0].toUpperCase() + name.slice(1) : name;
|
||||
return {
|
||||
requests: count(row[key('requests')]), inputTokens: count(row[key('promptTokens')]),
|
||||
outputTokens: count(row[key('completionTokens')]), cacheReadTokens: count(row[key('cachedTokens')]),
|
||||
cacheWriteTokens: null, reasoningTokens: null, errors: null,
|
||||
};
|
||||
}
|
||||
export function normalizeStats(value: unknown) {
|
||||
const stats = record(value);
|
||||
if (count(stats.totalRequests) === null) throw new Error('Invalid stats');
|
||||
const rows = (key: string) => {
|
||||
const entries = Object.entries(record(stats[key]));
|
||||
if (entries.length > 2000) throw new Error('Too many aggregates');
|
||||
return entries;
|
||||
};
|
||||
return {
|
||||
totals: metrics(stats, 'total'),
|
||||
providers: rows('byProvider').map(([id, row]) => ({provider: identifier(id), ...metrics(record(row))})),
|
||||
models: rows('byModel').map(([, row]) => { const r = record(row); return {model: identifier(r.rawModel), provider: identifier(r.provider), ...metrics(r)}; }),
|
||||
accounts: rows('byAccount').map(([, row]) => { const r = record(row); return {
|
||||
accountId: identifier(r.connectionId), model: identifier(r.rawModel), provider: identifier(r.provider), ...metrics(r),
|
||||
quota: {status: 'unknown' as const, remaining: null, resetAt: null, reason: 'upstream_quota_get_mutates_credentials'},
|
||||
}; }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Controller, Get, Header, Query, UseGuards, ValidationPipe } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { IsIn, IsOptional } from 'class-validator';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { ROUTER_PERIODS, RouterUsageAdapter } from './router-usage.adapter';
|
||||
export class RouterUsageQuery {
|
||||
@IsOptional()
|
||||
@IsIn(ROUTER_PERIODS)
|
||||
period?: string;
|
||||
}
|
||||
@Controller('admin/router-usage')
|
||||
@UseGuards(AuthGuard('jwt'), RolesGuard)
|
||||
@Roles('admin')
|
||||
export class RouterUsageController {
|
||||
constructor(private readonly adapter: RouterUsageAdapter) {}
|
||||
@Get()
|
||||
@Header('Cache-Control','private, no-store')
|
||||
summary(@Query(new ValidationPipe({transform:true,whitelist:true,forbidNonWhitelisted:true})) query: RouterUsageQuery) {
|
||||
return this.adapter.summary(query.period ?? '7d');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import request from 'supertest';
|
||||
import { RouterUsageModule } from './router-usage.module';
|
||||
import { RouterUsageAdapter } from './router-usage.adapter';
|
||||
|
||||
describe('protected router usage HTTP contract', () => {
|
||||
let app: INestApplication;
|
||||
const summary=jest.fn().mockResolvedValue({status:'available',data:{}});
|
||||
beforeAll(async () => {
|
||||
const module=await Test.createTestingModule({imports:[RouterUsageModule]})
|
||||
.overrideProvider(RouterUsageAdapter).useValue({summary})
|
||||
.overrideGuard(AuthGuard('jwt')).useValue({canActivate(context: any){
|
||||
const req=context.switchToHttp().getRequest();
|
||||
if (!req.headers.authorization) return false;
|
||||
req.user={role:req.headers.authorization}; return true;
|
||||
}}).compile();
|
||||
app=module.createNestApplication();
|
||||
app.useGlobalPipes(new ValidationPipe({transform:true,whitelist:true,forbidNonWhitelisted:true}));
|
||||
await app.init();
|
||||
});
|
||||
afterAll(async()=>app.close());
|
||||
it('blocks unauthenticated access', async()=>{ await request(app.getHttpServer()).get('/admin/router-usage').expect(403); });
|
||||
it('blocks non-admin users', async()=>{ await request(app.getHttpServer()).get('/admin/router-usage').set('Authorization','customer').expect(403); });
|
||||
it('permits admins and defaults to 7d', async()=>{
|
||||
await request(app.getHttpServer()).get('/admin/router-usage').set('Authorization','admin').expect(200);
|
||||
expect(summary).toHaveBeenCalledWith('7d');
|
||||
});
|
||||
it('rejects unsupported custom time range', async()=>{
|
||||
await request(app.getHttpServer()).get('/admin/router-usage?from=2026-01-01').set('Authorization','admin').expect(400);
|
||||
});
|
||||
it('rejects invalid period', async()=>{
|
||||
await request(app.getHttpServer()).get('/admin/router-usage?period=invalid').set('Authorization','admin').expect(400);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { RouterUsageController } from './router-usage.controller';
|
||||
import { RouterUsageAdapter } from './router-usage.adapter';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
@Module({controllers:[RouterUsageController],providers:[RouterUsageAdapter,RolesGuard],exports:[RouterUsageAdapter]})
|
||||
export class RouterUsageModule {}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { normalizeStats } from './router-usage.contract';
|
||||
|
||||
describe('9router stats allowlist', () => {
|
||||
it('maps real aggregate fields without leaking API-key map keys or account labels', () => {
|
||||
const result = normalizeStats({totalRequests:2,totalPromptTokens:10,totalCompletionTokens:4,totalCachedTokens:3,
|
||||
byProvider:{codex:{requests:2,promptTokens:10,completionTokens:4,cachedTokens:3}},
|
||||
byModel:{'m (codex)':{rawModel:'m',provider:'codex',requests:2}},
|
||||
byAccount:{'private@example.com':{rawModel:'m',provider:'codex',connectionId:'account-1',accountName:'private@example.com',requests:2}},
|
||||
byApiKey:{'SECRET-KEY|m':{apiKey:'SECRET-KEY'}},accessToken:'SECRET-TOKEN'});
|
||||
expect(result.totals).toEqual({requests:2,inputTokens:10,outputTokens:4,cacheReadTokens:3,cacheWriteTokens:null,reasoningTokens:null,errors:null});
|
||||
expect(result.models[0]).toMatchObject({model:'m',provider:'codex',requests:2});
|
||||
expect(result.accounts[0]).toMatchObject({accountId:'account-1',quota:{status:'unknown',remaining:null,resetAt:null,reason:'upstream_quota_get_mutates_credentials'}});
|
||||
expect(JSON.stringify(result)).not.toMatch(/SECRET|private@|accountName|byApiKey/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('unknown rather than fabricated metrics', () => {
|
||||
const empty = {totalRequests:0,byProvider:{},byModel:{},byAccount:{}};
|
||||
it('preserves known zero and unknown missing counters separately', () => {
|
||||
expect(normalizeStats(empty).totals).toEqual({requests:0,inputTokens:null,outputTokens:null,cacheReadTokens:null,cacheWriteTokens:null,reasoningTokens:null,errors:null});
|
||||
});
|
||||
it.each([null,{},[],{...empty,totalRequests:-1},{...empty,byModel:null}])('rejects invalid schemas', value => {
|
||||
expect(()=>normalizeStats(value)).toThrow();
|
||||
});
|
||||
it('rejects unsafe metric values instead of coercing them to zero', () => {
|
||||
expect(normalizeStats({...empty,totalPromptTokens:'10',totalCompletionTokens:-4,totalCachedTokens:Infinity}).totals).toMatchObject({inputTokens:null,outputTokens:null,cacheReadTokens:null});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
# Orchestration v4: Hermes runtime seam (review-only)
|
||||
|
||||
## Installed evidence / compatibility
|
||||
|
||||
Read-only inspection of `canina-hermes` source at `/opt/hermes` and Docker metadata:
|
||||
|
||||
- Running image ID: `sha256:373ddd5e6649f525b17993e1c885cdf1352127f8e98fd329140a73237125e52f`.
|
||||
- Registry digest (pinned template): `nousresearch/hermes-agent@sha256:9774f4f39a9bb8c2f68ce728ed5e99ddbad282163be56764afacf88ed952b784`.
|
||||
- Current command is `gateway run`, **not** `serve`. Loopback 9119 connection refused. This implementation does not claim a live dashboard integration or start one.
|
||||
- Existing `/opt/data` mount is external volume `canina-hermes_canina_hermes_data`; preserve it. Read-only cron JSON count: **17 jobs, 0 enabled**. Paused state is `enabled:false`, not a `paused` boolean. No cron/runtime/config mutation was made.
|
||||
- Existing untracked `/opt/services/ai/canina-hermes/compose.yml` remains untouched.
|
||||
|
||||
Sources inspected: `hermes_cli/web_routers/{status,profiles,models,sessions,analytics,cron,chat_ws}.py`, cron scoping helpers, `cron/jobs.py`, `hermes_cli/inventory.py`, `hermes_cli/dashboard_auth/{routes,middleware}.py`, `hermes_cli/web_server{,_chat}.py`, `tui_gateway/ws.py`.
|
||||
|
||||
## Supported allowlist
|
||||
|
||||
| Service method | Installed upstream contract | Public projection |
|
||||
|---|---|---|
|
||||
| health | GET /api/health | ok/version/commit/auth_required |
|
||||
| status | GET /api/status?profile= | version/gateway_running/gateway_state/overall/active_agents |
|
||||
| profiles | GET /api/profiles -> {profiles:[]} | name/is_default/gateway_running, filtered by backend scope |
|
||||
| modelInfo | GET /api/model/info?profile= | model/provider/effective_context_length |
|
||||
| modelOptions | GET /api/model/options?profile= | provider slug/name + model ID strings |
|
||||
| usage | GET /api/analytics/usage?profile=&days= | period_days and four numeric totals |
|
||||
| sessions | GET /api/sessions?profile=&limit=&offset=&full=false&order=recent | ID/profile/source/is_active, total |
|
||||
| crons | GET /api/cron/jobs?profile= -> array | ID/profile/enabled |
|
||||
| pauseCron | POST /api/cron/jobs/{id}/pause?profile= | ID/profile/enabled |
|
||||
| resumeCron | POST /api/cron/jobs/{id}/resume?profile= | implemented adapter; **disabled in registered service** |
|
||||
|
||||
No generic route/HTTP/RPC proxy. No model setter, config, secrets, PTY, trigger, deletion, raw transcript or raw logs. Status is not fabricated if unavailable. Numeric nulls/malformed/missing required fields produce CONTRACT (some empty analytics stores may therefore be unavailable). Unknown upstream fields are dropped, never forwarded; this is intentional forward-compatible redaction, not raw JSON passthrough. Scope mismatch is forbidden. Arrays cap at 1000, upstream bytes at 256 KiB, in-flight requests at 4, whole request/token budget at 5 seconds, no retries, redirects forbidden. The production fetch honors AbortSignal. Error messages never include upstream response/URL/token/exception. Do not log request headers or config objects.
|
||||
|
||||
Upstream GET /api/sessions can auto-archive internally; we inspected source only and did not call it against production. Some model inventory endpoints warm caches/probe providers. Classify these as managed reads, not guaranteed filesystem-pure operations.
|
||||
|
||||
## Authentication and WS discovery
|
||||
|
||||
- Non-loopback dashboard binds engage the provider-verified auth gate. REST supports provider-verified Bearer session tokens. Legacy loopback accepts session header/Bearer; **a Canina JWT or API_SERVER_KEY is not interchangeable**.
|
||||
- POST `/api/auth/ws-ticket` needs verified `request.state.session`; response `{ticket,ttl_seconds}` is single-use / 30 seconds. Do not mint tickets for a browser or copy credentials into browser URLs.
|
||||
- Installed WS: `/api/ws`, `/api/console`, `/api/events`, `/api/pub`, `/api/pty`; **no assumed `/api/chat/ws`**.
|
||||
- `/api/ws` uses newline-delimited JSON-RPC and `gateway.ready`; same dispatcher as TUI, broad privilege. Gated admission supports a ticket, including subprotocols `hermes-gateway-v1` and `hermes-gateway-ticket.<ticket>`; legacy process token is rejected in gated mode. Internal process credentials must never be extracted.
|
||||
- We deliberately do not bridge a powerful socket without a verified session/run ownership and event allowlist contract. `chat`/`control` return UNSUPPORTED after policy; event dispatch returns FORBIDDEN even with policy approval. No WS dependency, background connection, reconnect, or ticket endpoint is exposed.
|
||||
|
||||
## Wiring (owner integration step, no app.module.ts changes here)
|
||||
|
||||
Import `HermesManagementModule.register(config, authorizer)` in the owning backend module, then inject **HermesIntegrationService**, never the adapter into browser controllers. Registration exports the service only and defaults to deny-all policy. Example configuration:
|
||||
|
||||
```ts
|
||||
HermesManagementModule.register({
|
||||
origin: 'http://canina-hermes:9119',
|
||||
token: () => secretStore.read('hermes_dashboard_access_token'),
|
||||
}, backendRuntimeAuthorizer)
|
||||
```
|
||||
|
||||
Supply a provider-verified, short-lived Hermes token through backend secret storage (template references `/run/secrets/hermes_dashboard_access_token` only). Provision/refresh is an operator responsibility; this change neither extracts existing runtime secrets nor invents a login flow. No token in database/UI/env templates.
|
||||
|
||||
Controllers must verify Canina admin JWT, resolve subject/profile scopes from trusted backend data (not request DTO), enforce permission and rate limit/audit, translate HermesError codes to safe API errors (AUTH_REQUIRED/UNAVAILABLE -> 503, FORBIDDEN ->403, LIMIT ->429, CONTRACT/UNSUPPORTED ->502/501). Never forward upstream errors. `RuntimePrincipal` is an internal context, not a user input DTO. Authorizer must independently verify subject/action/profile. Missing/throwing authorizer denies. Registered module hard-disables resume; enabling requires an explicit reviewed code change. Resume can immediately make overdue recurring jobs due: never test it on production.
|
||||
|
||||
## Disabled event dispatch design
|
||||
|
||||
No listener, cron, poller, outbox consumer or webhook is registered. A future dispatcher must use backend-verified event identity, durable outbox and idempotency, server-resolved department/profile/run ownership, permission per action, payload minimization/redaction, budget and approval policy. Then use a tested narrow execution transport; never map arbitrary event text to TUI RPC or `/api/pub`. Unknown event/schema/principal/approval/ownership -> reject with no IO. Do not enable before isolated acceptance proves interruption, stream bounds and safe tool-output projection.
|
||||
|
||||
## Manifests and verification
|
||||
|
||||
`infra/hermes-runtime/compose.template.yml` is **not a deployable replacement yet**: manual-only profile, no automatic restart/public ports/socket/credentials, preserves external data volume, dedicated external backend network. It intentionally retains `gateway run`; dashboard/auth/network topology and gateway egress need an approved migration design. Do not run alongside current service sharing the same writable state. Never `down -v`.
|
||||
|
||||
`.gitea/workflows/hermes-runtime-contract.yml` is manual contract review only, no deploy job, SSH, runtime secret or event dispatch. Existing deploy workflow untouched. Compose parsed with `docker compose ... config --quiet`; no containers deployed.
|
||||
|
||||
Tests: `cd backend && npm test -- --runInBand hermes-management` (14 assertions across 4 suites); strict isolated typecheck/build `npx tsc -p src/hermes-management/tsconfig.contract.json [--noEmit]`; full backend `npm run build` after isolated `npx prisma generate`. All passed. Local HTTP transport is exercised on ephemeral loopback, not production. TDD failures were observed for missing adapter, inventory methods, integration service, module and concurrency limit before implementations. No live authenticated dashboard or WS execution was exercised. Host has no Node; disposable node:22-bookworm runners used. Initial shared dependency resolution and offline Prisma binary download failed; fresh worktree dependencies and isolated network-enabled Prisma generation resolved them, without DB connection/migration.
|
||||
|
||||
Final verification: full backend Jest regression **93 suites / 771 tests passed**; scoped ESLint and strict typecheck passed, full `tsc -b` build passed. Existing SSL/payment negative tests print expected error logs despite passing. No deploy or production action performed.
|
||||
@@ -0,0 +1,22 @@
|
||||
# Orchestration v4 read-only integration verification
|
||||
|
||||
Base e5c83e87fe2d52d06eb36532fa9e354570678c43 plus cherry-picks admin a34c2a9, runtime bd58cc4, router b0f4636. Separate remote worktree; no dirty core edits, pushes, deploys, DB access or runtime changes.
|
||||
|
||||
## RED → GREEN proof
|
||||
- New backend HTTP boundary suite initially failed 4/4: mutation returned 201, BigInt serialization returned 500, overview missing (404). After integration: 4/4 pass, covering all mutation routes, anonymous/customer rejection, secret projection, actual overview and unavailable resources.
|
||||
- New UI fail-closed capability test initially failed because Create bounded work was visible without authorization. After capability gating: 7/7 command-center tests pass. Existing explicit action/binding/retry tests retained.
|
||||
|
||||
## Disposable remote validation
|
||||
Node 22 bookworm, network none, userns host (host Docker remapping prevents normal bind mounts), worktree source mounts, read-only sibling dependency cache. Vite cache directories are ephemeral tmpfs; no existing dependency trees changed.
|
||||
- Backend focused aggregate: **13 suites, 65 tests pass** (orchestration, Hermes, router usage).
|
||||
- Backend `tsc --noEmit`: exit 0. `npm run build`: exit 0.
|
||||
- Backend changed controller/HTTP spec ESLint: exit 0, 8 unsafe-argument warnings (7 test harness, 1 existing any-typed Prisma result). Baseline subsystem lint had 256 errors/8 warnings largely inherited formatting; no full lint pass claimed.
|
||||
- Admin focused aggregate: **5 files, 19 tests pass** (command center, orchestration/router adapters, creation, navigation).
|
||||
- Admin `npm run build`: exit 0, existing unresolved font warning remains.
|
||||
- Admin `tsc --noEmit -p tsconfig.app.json`: exit 2 with **33 inherited diagnostics** outside this change: legacy Approvals/Audit/HQ/Dashboard/ManagerActions/Tasks unused imports, Orders requiresRx missing, Symptoms ConfirmModal props/unused setter. No changed-file diagnostics. Full admin typecheck is NOT green.
|
||||
|
||||
## Security/release blockers
|
||||
The committed legacy core permits gate-state bypass through generic transitions and lacks hardened replay/authorization/budget/kill-switch boundaries. It is retained unchanged for parent integration; every exposed v4 mutation is unconditionally denied by controller. Do not restore controller calls or enable execution until hardened core is merged and reverified.
|
||||
Runtime dashboard not listening per parent investigation; no fabricated health or live availability claim. No trusted runtime identity/profile policy or runtime auth configured. Chat, cron mutations, execution/event dispatch, release execution stay disabled. Read-only inventory still requires orchestration schema migration through approved CI/CD, never manual DB changes. Backend read queries are currently full inventory and release evidence uses per-task reads; pagination/scaling remains future work.
|
||||
|
||||
Parent must inspect this commit and reconcile hardened core before any mutation milestone. No Stage promotion performed by this worker; admin typecheck failures remain explicit verification blockers for parent decision.
|
||||
@@ -0,0 +1,50 @@
|
||||
# Stage v4 rollout safety
|
||||
|
||||
## Scope and deployment boundary
|
||||
|
||||
Only a push to `develop` followed by the existing Gitea workflow may roll out this change. Do not run `deploy.sh` manually. Its CI marker is an accident guard, not an authentication boundary: runner permissions remain the security boundary. `main`, unknown branches and the former `stage-backend-only` bypass fail before Docker operations. Production is intentionally blocked pending separate review; no silent baseline/resolve is permitted.
|
||||
|
||||
## Tracked sequence
|
||||
|
||||
1. Acquire the Stage rollout lock (same lock as the retired backend-only path).
|
||||
2. Fetch the branch and build images using the existing workflow. Build failure leaves old applications running.
|
||||
3. Stop Stage frontend and backend (maintenance/outage; no promise of a custom 503 page).
|
||||
4. Run the newly built backend image as an isolated one-off Prisma CLI job (`compose run --rm --no-deps --entrypoint ... migrate deploy`). No app command, published service ports or automatic baseline. Existing DB must already be running.
|
||||
5. Only on migration success start backend. Require all nine v4 tables, the successful tracked migration receipt and an actual HTTP catalog response with the catalog envelope. HTTP acceptance has bounded retries and timeouts; no response body is logged.
|
||||
6. On backend acceptance failure stop both applications and fail. Only after acceptance start frontend. CI success marker follows these gates. The shared support bot is not rebuilt/replaced by this Stage rollout.
|
||||
|
||||
Migration failure leaves maintenance in place; do not auto-restart old apps against a partly migrated schema. Diagnose from CI logs, restore from an authorized backup or ship a reviewed forward fix through CI/CD. Never `db push`, seed, silently `migrate resolve`, or manually apply live DDL.
|
||||
|
||||
## Verification (2026-10-22)
|
||||
|
||||
Strict RED/GREEN cycles captured missing rollout function, migration failure ordering, missing backend acceptance and missing CI/Production guard before implementation. `python3 scripts/tests/test_stage_rollout.py`: 3 passed. Shell tests simulate Docker failures to prove sequencing only; they do NOT certify a healthy release. `node --test scripts/tests/test_rollout_health.cjs`: 4 passed using a local HTTP server (503, HTML, incorrect envelope rejected; valid empty catalog shape accepted). These fixtures are not live health evidence.
|
||||
|
||||
`python3 scripts/tests/rehearse_rollout.py` performs only schema-only `pg_dump` and migration-history-only data dump from Stage. It restores into a fresh PostgreSQL 16 container with no network, no host ports, no persistent volume, and no customer rows. Prisma runs in that disposable container's network namespace using an existing generated v4 client/dependencies read-only from the core test worktree. Dumps have a private temporary directory and are removed on exit.
|
||||
|
||||
Observed output:
|
||||
|
||||
```
|
||||
Applying migration `20261022000000_add_orchestration_v4_core`
|
||||
All migrations have been successfully applied.
|
||||
No pending migrations to apply.
|
||||
PASS: actual Prisma legacy catalog/support and v4 relation queries
|
||||
Restored 61 legacy tables; all business tables empty
|
||||
PASS: unchanged legacy column definitions; 61 legacy queries; 9 v4 tables; migrate deploy repeatable
|
||||
Disposable database/container removed; no live DDL performed
|
||||
```
|
||||
|
||||
The first rehearsal hit a read-only nested mount creation error, cleaned up, and was corrected to mount only `prisma/` plus dependencies; subsequent rehearsals passed.
|
||||
|
||||
## Remaining acceptance constraints
|
||||
|
||||
- No push, actual deployment, live DDL, customer export, or Production change was performed. No live v4 health success is claimed.
|
||||
- Schema-only rehearsal proves schema/query compatibility, not row-volume performance, locks under traffic, or business-data backfill behavior. All 61 legacy business tables were verified empty.
|
||||
- Full image build/start and public frontend/admin/API acceptance still require the authorized CI rollout. The gate currently covers backend schema/catalog; frontend start success is not browser acceptance.
|
||||
- Workflow now downloads the deployment entrypoint by triggering `github.sha` and passes `DEPLOY_SHA`. The entrypoint rejects missing/malformed SHA values, verifies that the commit belongs to the fetched deployment branch, and checks out that exact commit. Six disposable rollout tests cover sequencing, CI/Production guards, pin wiring and SHA validation. Actual runner execution and strong artifact/release attestation still require live CI acceptance; SHA pinning alone does not authenticate artifact evidence.
|
||||
- Existing compose credentials are out of scope; no new credentials are added. Continue restricting runner access and runtime env files. Orchestration mutation/chat/runtime remain disabled in the integration base; this rollout does not enable them.
|
||||
|
||||
## Completion-branch rehearsal
|
||||
|
||||
The repository-relative rehearsal applied both `20261022000000_add_orchestration_v4_core` and `20261022190000_harden_orchestration_ledger` to a disposable database restored from Stage schema/history only. All 61 legacy business tables were empty, their column definitions were unchanged, nine v4 tables and actual Prisma queries passed, and a second deploy found no pending migrations. No live DDL or release execution occurred.
|
||||
|
||||
The workflow shell now stops on download failure. SHA-pinning and six rollout tests plus four HTTP fixtures are verified locally in disposable containers; they are not proof of an actual CI rollout or frontend acceptance.
|
||||
@@ -0,0 +1,41 @@
|
||||
# 9router admin consumption adapter
|
||||
|
||||
## Wiring (integration owner)
|
||||
Import `RouterUsageModule` from `backend/src/router-usage/router-usage.module` into the root application's imports. This branch deliberately does not edit app.module.ts. Existing AuthModule/JWT strategy must be registered by the application. Route requires a JWT bearer user with admin/superadmin role; API-key authentication is deliberately not enabled for this sensitive endpoint.
|
||||
|
||||
Set backend-only `ROUTER_USAGE_CLI_TOKEN` using the existing router CLI auth token from the operator secret store. Optional `ROUTER_USAGE_BASE_URL` must be exactly `https://nr.parsaaghayi.ir` (an origin slash is accepted). Do not ship this token to the frontend. No environment/configuration was changed during implementation. No push/deploy performed; integration follows CI/CD and production needs separate Gate2.
|
||||
|
||||
## Exact API
|
||||
`GET /admin/router-usage?period=7d` (plus the existing application global prefix, if any).
|
||||
Allowed periods: `today`, `24h`, `7d`, `30d`, `60d`, `all`; default `7d`. Unknown query properties/custom from/to ranges and invalid periods return 400. Missing/invalid JWT is rejected by Passport; authenticated non-admin gets 403. Response is private/no-store.
|
||||
|
||||
Response fields:
|
||||
- `source: "9router"`, `period`
|
||||
- `status: "available" | "unavailable"`
|
||||
- `reason: null | "not_configured" | "invalid_configuration" | "busy" | "upstream_unavailable"`
|
||||
- `attribution: {scope:"9router_total", hermes:null, additive:false}`
|
||||
- `freshness: {retrievedAt: ISO8601|null, sourceUpdatedAt:null, stale:null}`. Retrieval time is NOT a guarantee of provider freshness. The source exposes no authoritative updated-at for aggregates. No last-good cache is served.
|
||||
- `capabilities: {errors:false, reasoningTokens:false, cacheWriteTokens:false, quota:false, customTimeRange:false}`
|
||||
- `data: null | {totals, providers:[], models:[], accounts:[]}`
|
||||
|
||||
Every metrics object contains `requests`, `inputTokens`, `outputTokens`, `cacheReadTokens`, `cacheWriteTokens`, `reasoningTokens`, `errors` (number|null). Zero is retained only if upstream reported zero; absent/invalid counters remain null. Input/output/cache map to promptTokens/completionTokens/cachedTokens; cache-read is a subset of input, never add it again. Cache-write/reasoning/errors are always null because the stats contract does not expose these aggregates.
|
||||
|
||||
Provider rows: `{provider,...metrics}`. Model rows: `{model,provider,...metrics}`. Account rows: `{accountId,model,provider,...metrics,quota:{status:"unknown",remaining:null,resetAt:null,reason:"upstream_quota_get_mutates_credentials"}}`. Account rows are upstream account/model summaries, NOT unique account inventory; accounts without usage are absent. IDs are validated, nullable if unsafe; account names/emails are never returned. No raw upstream maps, logs, prompts, provider data or credentials are returned. Dimensions are different views of the same consumption: do NOT sum totals+models+accounts. Hermes attribution remains unknown; do NOT add Hermes telemetry to router totals.
|
||||
|
||||
## Deployed-source inspection and real probe
|
||||
Read-only inspected running `9router` image `decolua/9router:vpn`: compiled `/app/.next/server/app/api/usage/stats/route.js`, `/app/.next/server/chunks/9100.js`, `/app/.next/server/middleware.js`, `/app/.next/server/chunks/7211.js`, providers routes and `/app/open-sse/services/usage.js`. No credential tables or router DB contents were dumped/modified.
|
||||
|
||||
Verified stats route accepts the periods above. `today` uses router-local midnight, `24h` rolling history; 7/30/60d use router-local daily buckets, `all` all retained daily aggregates. This is not arbitrary UTC timestamp filtering; retention/completeness is upstream-owned.
|
||||
|
||||
Authenticated internal GET probe returned HTTP 200, 5 provider summaries, 21 model summaries, 21 account/model summaries. Verified model fields: requests, promptTokens, completionTokens, cachedTokens, cost, rawModel, provider, lastUsed. Account fields additionally include connectionId/accountName. Only schema/counts printed; no keys or account values printed. Public HTTPS reverse proxy path was not live-authenticated, so its separate proxy authentication/network reachability remains an operator verification step.
|
||||
|
||||
Dashboard routes authenticate using `x-9r-cli-token` or valid `auth_token` session cookie. Normal inference API Bearer keys do NOT authenticate these dashboard routes. CLI token is NOT the contents of cli-secret: deployed middleware computes first 16 hex characters of SHA256(machine-id + "9r-cli-auth" + cli-secret). Probe derived it only inside the router process command and never emitted it; no new token or configuration was created.
|
||||
|
||||
**Security finding:** stats `byApiKey` map keys contain raw inference keys, even when row fields are masked. Adapter discards this map entirely and never logs response bodies/errors.
|
||||
|
||||
**Quota blocker:** `GET /api/usage/[connectionId]` calls refreshAndUpdateCredentials, including updateProviderConnection; OAuth refresh/retry can persist credentials. It is NOT read-only despite being GET. Therefore adapter does NOT call it. Provider quota handlers can return quotas (used/total/remaining/resetAt), messages or synthesized unlimited defaults; these cannot safely be treated as verified provider truth here. Quota reset grants exist in provider helpers but must never be consumed by this adapter. No safe deployed cache-only provider quota route was established. A separately reviewed router-side non-mutating, provenance/timestamp-bearing quota snapshot API is required before exposing live remaining/reset. Quota is unknown, never zero/unlimited fabricated. Connection inventory/status refresh is also not represented as quota truth.
|
||||
|
||||
## Bounds and verification
|
||||
Only fixed-origin authenticated GET `/api/usage/stats` is invoked; redirect:error, abort after 5 seconds, streaming cap 1 MiB, <=2000 rows per dimension, <=4 concurrent requests per backend process. No retries or stale cache. Schema/transport/auth/rate-limit/oversize failures produce unavailable + null data without raw errors. No SQL, POST or token refresh.
|
||||
|
||||
Strict test-first slices observed missing contract, adapter, module failures before implementation. Disposable containers used existing backend image dependencies, read-only source mounts, network disabled and copied source into ephemeral /work; no host dependencies/build output or running containers changed. `npm run build` passed. Focused: 3 suites/24 tests passed. Full backend regression: 92 suites/781 tests passed (existing negative-path tests log expected payment/SSL errors). HTTP guard tests replace JWT authentication only and exercise real RolesGuard; deployed JWT strategy remains application-owned.
|
||||
@@ -0,0 +1,46 @@
|
||||
# Integration milestone: read-only v4
|
||||
|
||||
This integration supersedes mutation/chat expectations below. All orchestration POST/PUT routes return 403 **before calling legacy services**, including task creation, transitions, gate decisions, budget writes, kill-switch and chat. No feature flag can enable them. `availableActions` is always `[]`. Do not enable mutation controls until hardened core is merged and independently verified.
|
||||
|
||||
GET `/admin/orchestration/overview` returns `{items:[{id:"tasks",title:"Persisted task inventory",count:number}], measuredAt, capabilities:{mutations:false,chat:false,runtime:false},reason:"security_hardening_pending"}`. The timestamp describes this DB inventory observation, not runtime health. Frontend capability fetch defaults to all false on failure or missing fields.
|
||||
|
||||
GET tasks and detail use explicit allowlists: task identity/state/version/mode/budget; run identity/status/commit/environment; artifact identity/kind/hash; decision identity/gate/decision/expiry/bindings; event identity/type/states/sequence/time; ledger identity/amount/kind/time. Arbitrary metadata, notes, event payloads, artifact URI/signature and BigInt size are not exposed. Scope/acceptance metadata remains withheld pending a reviewed structured schema.
|
||||
|
||||
GET `/releases` is persisted run evidence only, not a claim of release authorization or deployment. GET `/agents`, `/schedules`, `/model-policy` return 503 with explicit unavailable reasons: there are no trusted runtime identity/auth or persisted model policy read contracts. HermesManagementModule is registered deny-all with an empty token and no HTTP controllers; no runtime calls or cron changes occur. RouterUsageModule is registered with its admin-protected read-only endpoint and returns unavailable when credentials are absent. No new secrets are configured.
|
||||
|
||||
## Historical component contract (mutation proposals disabled)
|
||||
|
||||
# Admin orchestration v4 adapter contract
|
||||
|
||||
All client traffic uses existing authenticated Axios client (`src/services/api.ts`). Relative `/admin/...` paths are served below `/api`. No runtime secrets, Hermes tokens, PTY, terminal websocket or direct gateway credentials may enter these DTOs. Backend must project/redact task metadata, artifacts, audit payloads and chat text before returning them. Browser does not enforce authorization.
|
||||
|
||||
## Implemented core API observed in sibling core worktree
|
||||
- GET `/admin/orchestration/tasks`: bare Task[] or `{success:true,data:Task[]}`.
|
||||
- GET `/admin/orchestration/tasks/:id`: immutable task detail with runs/artifacts, decisions, events and budgetLedger.
|
||||
- POST `/admin/orchestration/tasks`: key,title,department,operationMode,budgetLimitCents,metadata {scope,acceptanceCriteria[]} (no execution authorization).
|
||||
- PUT `/admin/orchestration/tasks/:id/transition`: toState,expectedVersion,idempotencyKey,reason.
|
||||
- POST `/admin/orchestration/tasks/:id/gates/{1|2}/decide`: decision,expectedVersion,idempotencyKey,expiresAt,notes. Gate2 APPROVED additionally binds runId,artifactHash,commitSha,environment to registered immutable run and artifact.
|
||||
- PUT `/admin/orchestration/kill-switch`: level,reason. Levels FREEZE_NEW_WORK,STOP_AGENTS,DISABLE_MUTATIONS,EMERGENCY_HALT. No invented reset/resume route.
|
||||
|
||||
Task fields and optional service DTOs are declared in `src/services/orchestration.ts`.
|
||||
|
||||
## Required integration additions (fail closed until backend provides)
|
||||
Task `availableActions: {id,label,toState?,gate?:1|2,decision?:APPROVED|REJECTED,disabledReason?}[]` must be advertised by backend after permission, state, gate, policy and kill-switch evaluation. Browser never derives transitions from state. Missing actions means read-only, not an invitation to synthesize controls. Backend core inspected initially did not advertise these actions. This is an integration blocker for execution.
|
||||
|
||||
Optional read-only resources GET `/admin/orchestration/{agents|model-policy|schedules|releases}` return `{items:[{id,title?,status?,department?,readiness?,model?,budgetLimitCents?,spentCents?,cron?,timezone?,environment?,commitSha?,reason?}],measuredAt:ISO8601}`. May be wrapped in `{success:true,data:...}`. 404/403/network/malformed replies render unavailable, not mock cards. These endpoint contracts are proposals requiring backend reconciliation, not claims that endpoints exist. Schedule editing, model policy editing, budget adjustments, agent start/stop and release execution require separately advertised typed backend commands; intentionally not implemented against guessed routes. Existing task run/evidence, decisions, ledger and ordered events remain inspectable independent of optional feeds.
|
||||
|
||||
POST `/admin/orchestration/chat/messages`: {sessionId,message,idempotencyKey} -> {id,role:'assistant',content}. Advisory-only bridge; no browser runtime connection or auto-execution of text. Backend must bind sessions to authenticated user and redact sensitive output.
|
||||
|
||||
## Retry and concurrency
|
||||
Command dialog snapshots immutable task version and allocates one key. On first attempt inputs lock; failed retries use identical payload/key. Cancel and refresh to reconcile 409 conflict; refresh invalidates selection and dialog. Successful command refetches authoritative tasks; no optimistic status. Backend must enforce idempotency transactionally, compare payload bindings and versions; frontend is not a safety boundary. Task creation is keyed by unique business key; reconcile ambiguous failures by refreshing before retry.
|
||||
|
||||
## 9router usage concrete contract (aligned with backend worker b0f4636)
|
||||
GET `/admin/router-usage?period=today|24h|7d|30d|60d|all` default7d; authenticated admin. Response: source,period,status available|unavailable,reason,data null|{totals,providers[],models[],accounts[]},freshness {retrievedAt,sourceUpdatedAt,stale},attribution {scope:9router_total,hermes:null,additive:false}.
|
||||
Metrics: requests,inputTokens,outputTokens,cacheReadTokens,cacheWriteTokens,reasoningTokens,errors. Last three unsupported=null. Account quota {status:unknown,remaining:null,resetAt:null,reason:upstream_quota_get_mutates_credentials}. No upstream quota GET because it refreshes credentials. No estimates or raw credentials. Nullable provider/model/account IDs are sanitized by backend.
|
||||
Breakdowns overlap and are never summed. Hermes attribution unknown, not zero and not added. Retrieved timestamp is not source freshness. SourceUpdatedAt and stale remain explicitly unknown. Frontend explicitly projects DTO fields and rejects malformed/unavailable replies. No direct gateway connection.
|
||||
|
||||
## Monitoring
|
||||
Existing payment stats/health and SMS credit are read independently. Only returned values displayed. Request failures remain unknown with source and client observation timestamp. Database/Redis/Post/OCR/uptime/environment/agent runtime remain unknown without measured endpoints. No fabricated 14-day uptime, Production label, derived DB ping, SMS count or healthy post service.
|
||||
|
||||
## Verification caveats
|
||||
All verification uses disposable node:22-bookworm Docker runners against this worktree. Plain `npm run typecheck` uses solution-style config and does not verify app files. `tsc --noEmit -p tsconfig.app.json` exposes pre-existing errors in legacy Approvals/Audit/HQ/Tasks imports and Orders/Symptoms types; report these separately, not as a green full application typecheck. Build warning: unresolved existing Shabnam font remains runtime-resolved.
|
||||
@@ -0,0 +1,21 @@
|
||||
# Verification and remaining integration work
|
||||
|
||||
Remote branch: feature/orchestration-v4-admin. All source changes limited to frontend/admin-panel. No push, deployment, production container command, or live operational mutation performed.
|
||||
|
||||
Disposable node:22-bookworm runners, --userns=host:
|
||||
- Full `vitest run --maxWorkers=2`: 57 files, 326 tests passed, zero failed.
|
||||
- Scoped ESLint for all new services/components/tests plus Monitoring: exit 0.
|
||||
- `npm run typecheck` (solution config): exit 0, not an app check.
|
||||
- `tsc --noEmit -p tsconfig.app.json`: exit 2, 33 pre-existing diagnostics (legacy unused imports/locals, Orders requiresRx type, Symptoms ConfirmModal props). No diagnostics in new files or Monitoring. Baseline captured before implementation had same legacy errors.
|
||||
- `npm run build`: exit 0; pre-existing unresolved Shabnam font warning.
|
||||
|
||||
TDD red/green cycles exercised adapter missing exports, unadvertised actions, incomplete/expired Gate2 bindings, exact version/idempotency payloads and retry lock, task creation bounds, UI explicit confirmation, monitoring fake values and failures, navigation, router usage contract migration/unavailable state. Full UI tests use mocked HTTP boundary with realistic backend DTOs; they are not a live backend integration test. Additional UI tests cover immutable artifact binding, kill authorization failure, readiness BLOCKED response, chat escaping and typed bridge. Router usage aligned to concrete backend b0f4636 contract.
|
||||
|
||||
Remaining gaps / do not claim full end-to-end operation:
|
||||
- Backend must advertise availableActions. Initial core worktree lacks them; client intentionally fails closed read-only without actions.
|
||||
- Agents/model-policy/schedules/releases snapshots and typed chat bridge are proposed contracts, not initially present core routes. UI displays explicit unavailable errors, never synthetic content. Mutating model policy/schedules/agent operations not implemented against guessed endpoints.
|
||||
- Kill switch current level cannot be read until backend exposes a status contract. No invented resume command.
|
||||
- No live auth credentials used; endpoint auth/RBAC and cross-worker DTO integration still need isolated stack smoke tests.
|
||||
- Legacy Approvals/Tasks/HQ/Audit pages remain separately available and unchanged. New v4 control center is at /orchestration inside existing protected layout; these legacy pages are not v4 authority and should be retired/migrated during integration.
|
||||
- Full app typecheck is not green due existing errors listed above.
|
||||
- Browser chat is advisory; no Hermes terminal or raw runtime connection.
|
||||
@@ -0,0 +1,14 @@
|
||||
import {fireEvent,render,screen} from '@testing-library/react';
|
||||
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 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:'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();
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import {useState} from 'react';
|
||||
import Button from './ui/Button';
|
||||
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:'',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>;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { render,screen } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { it,expect,vi } from 'vitest';
|
||||
import Sidebar from './Sidebar';
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn().mockResolvedValue({data:{success:true,data:{}}})}}));
|
||||
it('exposes command center inside existing authenticated navigation',async()=>{
|
||||
render(<MemoryRouter initialEntries={['/orchestration']}><Sidebar isOpen setIsOpen={vi.fn()}/></MemoryRouter>);
|
||||
expect(await screen.findByRole('link',{name:'Orchestration command center'})).toHaveAttribute('href','/orchestration');
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import Button from './ui/Button';
|
||||
import {routerUsage,usagePeriods} from '../services/routerUsage';
|
||||
import type {RouterUsageSnapshot,UsageCounters,UsagePeriod} from '../services/routerUsage';
|
||||
const shown=(value:unknown)=>value===null||value===undefined?'Unknown — not reported':String(value);
|
||||
function Counters({data}:{data:UsageCounters|null}) {return <dl className="grid grid-cols-2 gap-2">{(['requests','inputTokens','outputTokens','cacheReadTokens','cacheWriteTokens','reasoningTokens','errors'] as const).map(key=><div key={key}><dt>{key}</dt><dd>{shown(data?.[key])}</dd></div>)}</dl>}
|
||||
export default function RouterUsagePanel(){
|
||||
const [data,setData]=useState<RouterUsageSnapshot|null>(null);const [error,setError]=useState('');const [revision,setRevision]=useState(0);const [loading,setLoading]=useState(false);const [period,setPeriod]=useState<UsagePeriod>('7d');
|
||||
useEffect(()=>{let active=true;setLoading(true);setError('');setData(null);routerUsage.snapshot(period).then(value=>{if(active)setData(value)}).catch(e=>{if(active)setError(e instanceof Error?e.message:'Usage unavailable')}).finally(()=>{if(active)setLoading(false)});return()=>{active=false}},[revision,period]);
|
||||
return <section className="bg-white border rounded-2xl p-5 space-y-4"><header className="flex justify-between"><h2 className="font-bold">9router usage & provider-reported quota</h2><Button disabled={loading} onClick={()=>setRevision(n=>n+1)}>Refresh usage</Button></header>
|
||||
<label>Usage period<select aria-label="Usage period" value={period} onChange={e=>setPeriod(e.target.value as UsagePeriod)}>{usagePeriods.map(p=><option key={p}>{p}</option>)}</select></label>
|
||||
<p>Gateway totals include all clients. Provider/model/account breakdowns overlap; never add them together. Cache/reasoning counters may overlap token counts. No derived totals or quota estimates.</p>
|
||||
<p>Hermes attribution: Unknown — not reported; do not add to gateway totals.</p>
|
||||
{loading&&<p role="status">Loading gateway usage…</p>}{error&&<p role="alert">Unknown / unavailable: {error}</p>}
|
||||
{data&&<><dl><dt>Source</dt><dd>{data.source}</dd><dt>Retrieved at (not source freshness)</dt><dd>{shown(data.freshness.retrievedAt)}</dd><dt>Source updated at</dt><dd>{shown(data.freshness.sourceUpdatedAt)}</dd><dt>Stale</dt><dd>{shown(data.freshness.stale)}</dd><dt>Reported period</dt><dd>{data.period}</dd></dl><article className="border p-4 rounded-xl"><h3>Gateway totals (includes Hermes)</h3><Counters data={data.data.totals}/></article>
|
||||
{(['providers','models','accounts'] as const).map(group=><section key={group}><h3 className="font-bold">{group}</h3>{!data.data[group].length&&<p>No {group} reported.</p>}<div className="grid md:grid-cols-2 gap-4">{data.data[group].map((row,i)=><article key={i} className="border p-4 rounded-xl"><h4>{shown(row.provider)} · {shown(row.model)}</h4>{row.accountId&&<p>{row.accountId}</p>}<Counters data={row}/>{group==='accounts'&&<dl><dt>Provider-reported quota remaining</dt><dd>{shown(row.quota?.remaining)}</dd><dt>Provider-reported quota reset</dt><dd>{shown(row.quota?.resetAt)}</dd><dt>Quota availability reason</dt><dd>{shown(row.quota?.reason)}</dd></dl>}</article>)}</div></section>)}
|
||||
<p>Quota is unknown: upstream quota GET refreshes credentials, so this read-only adapter does not call it.</p></>}
|
||||
</section>;
|
||||
}
|
||||
@@ -117,7 +117,10 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
|
||||
title: 'حاکمیت، تاییدات و وظایف',
|
||||
icon: CheckSquare,
|
||||
items: [
|
||||
{ icon: CheckSquare, label: 'کارتابل تاییدات مدیریت', path: '/approvals' },
|
||||
{ icon: Building2, label: 'Orchestration command center', path: '/orchestration' },
|
||||
{ icon: Building2, label: 'نمای وضعیت دپارتمانها', path: '/governance/hq' },
|
||||
{ icon: Briefcase, label: 'اقدامات مدیریتی و همکاریها', path: '/manager-actions' },
|
||||
{ icon: CheckSquare, label: 'مجوزهای عملیاتی', path: '/approvals' },
|
||||
{ icon: Briefcase, label: 'وظایف دپارتمانها و ایجنتها', path: '/tasks' },
|
||||
{ icon: History, label: 'تاریخچه تغییرات دیتابیس (Audit)', path: '/history' },
|
||||
],
|
||||
|
||||
@@ -12,6 +12,9 @@ interface TopbarProps {
|
||||
}
|
||||
|
||||
const SEARCHABLE_PAGES = [
|
||||
{ label: "اقدامات مدیریتی و همکاریها (Manager Actions)", path: "/manager-actions", keywords: ["اقدامات", "مدیریتی", "همکاری", "b2b", "تامین", "استراتژی", "actions"] },
|
||||
{ label: "مجوزهای عملیاتی مدیریت (Operational Approvals)", path: "/approvals", keywords: ["مجوز", "مجوزها", "تاییدات", "approvals", "عملیاتی", "تایید"] },
|
||||
{ label: "وضعیت دپارتمانها و ارکستراسیون (HQ)", path: "/governance/hq", keywords: ["ارکستراسیون", "دپارتمان", "hq", "governance", "وضعیت"] },
|
||||
{ label: 'داشبورد (خلاصه وضعیت فروشگاه)', path: '/', keywords: ['dashboard', 'آمار', 'فروش', 'خانه'] },
|
||||
{ label: 'مرکز مانیتورینگ و سلامت سرویسها', path: '/monitoring', keywords: ['monitoring', 'مانیتورینگ', 'سلامت', 'پینگ', 'وضعیت', 'سرعت'] },
|
||||
{ label: 'مدیریت نسخههای پزشکی (Prescriptions)', path: '/prescriptions', keywords: ['نسخه', 'نسخهها', 'پزشک', 'دارو', 'تجویز', 'rx', 'prescription', 'بررسی نسخه'] },
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import api from "../services/api";
|
||||
import ApprovalsPage from "./ApprovalsPage";
|
||||
|
||||
vi.mock("../services/api", () => {
|
||||
return {
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-hot-toast", () => ({
|
||||
default: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("ApprovalsPage Component", () => {
|
||||
const mockApprovals = [
|
||||
{
|
||||
id: "app-1",
|
||||
department: "CONTENT",
|
||||
category: "CAMPAIGN",
|
||||
title: "کمپین تخصصی مفاصل: برتری بالینی صدف لبسبز کنینا نسبت به وتاکسپرت",
|
||||
status: "PENDING",
|
||||
createdAt: "2026-10-19T10:00:00Z",
|
||||
payload: {
|
||||
"1_مسئله_و_شکاف_بازار": "قیمت گزاف قرص مفاصل وتاکسپرت لهستان باعث شکست دورههای درمانی شده است.",
|
||||
"2_راهحل_و_مزیت_کنینا": "معرفی مکمل بیرقیب Velox Gelenkenergie ۱۰۰٪ عصاره صدف لبسبز با نصف قیمت رقیب.",
|
||||
"3_طرح_اقدام_عملیاتی": "تولید لندینگپیج جامع و سئومحور و اتصال مستقیم به ترب.",
|
||||
"4_دپارتمانهای_مسئول": "CONTENT, SEO, CLINICAL_RD",
|
||||
"5_معیار_پذیرش_و_تکمیل": "رندر شدن لندینگ بدون خطای SSR و افزایش ایمپرشن ارگانیک."
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "app-2",
|
||||
department: "PRICING",
|
||||
category: "PRICE_CHANGE",
|
||||
title: "پیشنهاد اصلاح قیمت و همگامسازی با ترب: Canina Flexan 150g",
|
||||
status: "PENDING",
|
||||
createdAt: "2026-10-19T11:00:00Z",
|
||||
payload: {
|
||||
product_name: "Canina Flexan 150g",
|
||||
current_price: 34800000,
|
||||
suggested_price: 36500000,
|
||||
margin_percent: 20.5,
|
||||
competitor_min_torob: 37200000,
|
||||
reason: "افزایش قیمت تامینکننده و میانگین قیمت ترب روی ۳۷.۲ میلیون ریال است."
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "app-3",
|
||||
department: "MARKETING",
|
||||
category: "SMS_CAMPAIGN",
|
||||
title: "کمپین یادآوری تمدید دوره مکملهای مفاصل و GAG",
|
||||
status: "APPROVED",
|
||||
createdAt: "2026-10-18T09:00:00Z",
|
||||
executedAt: "2026-10-18T10:00:00Z",
|
||||
ceoNotes: "تایید شد و پیامکها ارسال شدند.",
|
||||
payload: {
|
||||
campaign_name: "Refill GAG 60-Day Reminder",
|
||||
sms_pattern: "سلام {name} عزیز، دوره مکمل مفاصل کنینا رو به اتمام است.",
|
||||
target_count: 86,
|
||||
estimated_cost_irr: 860000,
|
||||
expected_revenue_irr: 54000000,
|
||||
expected_conversion_rate: "18%"
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(api.get as any).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: mockApprovals,
|
||||
meta: {
|
||||
total: 3,
|
||||
pendingCount: 2,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("renders header, KPI cards, and maps strategic 5-part proposal nicely", async () => {
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
expect(await screen.findByText(/کارتابل حاکمیت سازمانی و تاییدات مدیرعامل/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/2 پیشنهاد منتظر تصمیم شما/i)).toBeInTheDocument();
|
||||
|
||||
// Verify 5-part structured fields are cleanly mapped
|
||||
expect(screen.getByText(/مسئله و شکاف شناساییشده در بازار:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/قیمت گزاف قرص مفاصل وتاکسپرت لهستان/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/راهحل، محصول و مزیت رقابتی کنینا:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Velox Gelenkenergie/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders pricing payload with current price, suggested price, and margin", async () => {
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
expect(await screen.findByText(/پیشنهاد اصلاح قیمت و همگامسازی با ترب/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/محاسبه قیمتگذاری و سود ناخالص:/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/20.5٪/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("approves a pending request with CEO directive note", async () => {
|
||||
(api.put as any).mockResolvedValue({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
expect(await screen.findByText(/کمپین تخصصی مفاصل/i)).toBeInTheDocument();
|
||||
|
||||
const approveButtons = screen.getAllByRole("button", { name: /تایید و صدور مجوز اجرا/i });
|
||||
expect(approveButtons.length).toBeGreaterThan(0);
|
||||
|
||||
fireEvent.click(approveButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith(
|
||||
"/admin/approvals/app-2/decide",
|
||||
expect.objectContaining({ decision: "APPROVED" })
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("runs simulation test when clicking play button", async () => {
|
||||
(api.post as any).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
testResult: {
|
||||
status: "SIMULATION_SUCCESS",
|
||||
executionSafe: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
render(<ApprovalsPage />);
|
||||
|
||||
const runTestButtons = await screen.findAllByRole("button", { name: /اجرای تست و شبیهسازی/i });
|
||||
expect(runTestButtons.length).toBeGreaterThan(0);
|
||||
|
||||
fireEvent.click(runTestButtons[0]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith("/admin/approvals/app-2/test");
|
||||
});
|
||||
|
||||
expect(await screen.findByText(/نتیجه تست سلامت و شبیهسازی:/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,20 +1,12 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
History,
|
||||
Search,
|
||||
Filter,
|
||||
RefreshCw,
|
||||
Clock,
|
||||
User,
|
||||
Database,
|
||||
ArrowRight,
|
||||
Shield,
|
||||
Layers,
|
||||
ChevronDown,
|
||||
Calendar,
|
||||
AlertCircle,
|
||||
Eye,
|
||||
CheckCircle2
|
||||
} from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
|
||||
|
||||
@@ -251,6 +251,10 @@ describe("Blogs Page Component", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("submits authorship fields and intentional material update control", async () => {
|
||||
renderComponent(); await screen.findByText("راهنمای جامع نگهداری سگ پامرانین"); fireEvent.click(screen.getAllByTitle("ویرایش مقاله")[0]); fireEvent.change(screen.getByLabelText("تیم نویسندگی"),{target:{value:"Science"}}); fireEvent.change(screen.getByLabelText("نقش نویسنده"),{target:{value:"Vet"}}); fireEvent.click(screen.getByText("۳. زمانبندی و انتشار")); fireEvent.click(screen.getByLabelText("ثبت بهروزرسانی محتوایی مهم")); fireEvent.click(screen.getByTestId("blog-save-btn")); await waitFor(()=>expect(api.put).toHaveBeenCalledWith("/admin/blogs/blog-1",expect.objectContaining({authorTeam:"Science",authorRole:"Vet",markContentUpdated:true})));
|
||||
});
|
||||
|
||||
it("shows delete confirmation and deletes blog article", async () => {
|
||||
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
|
||||
@@ -70,6 +70,9 @@ export interface BlogPost {
|
||||
content: string;
|
||||
excerpt?: string;
|
||||
authorId?: string;
|
||||
authorTeam?: string;
|
||||
authorRole?: string;
|
||||
contentUpdatedAt?: string | null;
|
||||
author?: {
|
||||
id?: string;
|
||||
firstName?: string;
|
||||
@@ -168,6 +171,9 @@ export default function Blogs() {
|
||||
content: '',
|
||||
excerpt: '',
|
||||
authorId: '',
|
||||
authorTeam: '',
|
||||
authorRole: '',
|
||||
markContentUpdated: false,
|
||||
categoryId: '',
|
||||
tagNames: [] as string[],
|
||||
imageUrl: '',
|
||||
@@ -245,6 +251,9 @@ export default function Blogs() {
|
||||
content: blog.content || '',
|
||||
excerpt: blog.excerpt || '',
|
||||
authorId: blog.authorId || (blog.author?.id || ''),
|
||||
authorTeam: blog.authorTeam || '',
|
||||
authorRole: blog.authorRole || '',
|
||||
markContentUpdated: false,
|
||||
categoryId: blog.categoryId || '',
|
||||
tagNames: blog.tags ? blog.tags.map((t) => t.name) : [],
|
||||
imageUrl: blog.imageUrl || '',
|
||||
@@ -281,6 +290,9 @@ export default function Blogs() {
|
||||
content: '',
|
||||
excerpt: '',
|
||||
authorId: authors[0]?.id || '',
|
||||
authorTeam: '',
|
||||
authorRole: '',
|
||||
markContentUpdated: false,
|
||||
categoryId: '',
|
||||
tagNames: [],
|
||||
imageUrl: '',
|
||||
@@ -1003,6 +1015,11 @@ export default function Blogs() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div><label htmlFor="author-team" className="text-xs font-bold text-gray-700">تیم نویسندگی</label><input id="author-team" value={formData.authorTeam} onChange={(e)=>setFormData({...formData,authorTeam:e.target.value})} className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs" /></div>
|
||||
<div><label htmlFor="author-role" className="text-xs font-bold text-gray-700">نقش نویسنده</label><input id="author-role" value={formData.authorRole} onChange={(e)=>setFormData({...formData,authorRole:e.target.value})} className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs" /></div>
|
||||
</div>
|
||||
|
||||
{/* Chips Tag Input */}
|
||||
<div className="space-y-2 p-3.5 bg-gray-50/70 border border-gray-200 rounded-2xl">
|
||||
<label className="text-xs font-bold text-gray-700 block">برچسبها و تگهای مقاله (Tag Input)</label>
|
||||
@@ -1161,6 +1178,8 @@ export default function Blogs() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="flex items-center gap-3 p-4 border border-blue-200 rounded-2xl bg-blue-50 cursor-pointer"><input type="checkbox" aria-label="ثبت بهروزرسانی محتوایی مهم" checked={formData.markContentUpdated} onChange={(e)=>setFormData({...formData,markContentUpdated:e.target.checked})}/><span className="text-xs font-black">ثبت بهروزرسانی محتوایی مهم</span></label>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
|
||||
<label className="flex items-center gap-3 p-4 border border-gray-200 rounded-2xl bg-white hover:bg-gray-50 transition-colors cursor-pointer">
|
||||
<input
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
Building2,
|
||||
ArrowUpRight,
|
||||
RefreshCw,
|
||||
ShieldCheck,
|
||||
Briefcase,
|
||||
FileText,
|
||||
Stethoscope,
|
||||
Search,
|
||||
Headphones,
|
||||
Cpu,
|
||||
Terminal,
|
||||
Activity,
|
||||
XCircle,
|
||||
} from 'lucide-react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import api from '../services/api';
|
||||
|
||||
interface DepartmentCard {
|
||||
id: string;
|
||||
name: string;
|
||||
role: string;
|
||||
agentName: string;
|
||||
avatarColor: string;
|
||||
icon: any;
|
||||
status: 'ACTIVE' | 'PROCESSING' | 'STANDBY';
|
||||
currentFocus: string;
|
||||
pendingApprovals: number;
|
||||
completedTasks: number;
|
||||
recentReasoningSnippet: string;
|
||||
}
|
||||
|
||||
const BASE_DEPARTMENTS: Omit<DepartmentCard, 'status' | 'pendingApprovals' | 'completedTasks' | 'recentReasoningSnippet' | 'currentFocus'>[] = [
|
||||
{
|
||||
id: 'CONTENT',
|
||||
name: 'واحد محتوا و وبلاگ تخصصی',
|
||||
role: 'تحقیق عمیق، مقالات بالینی، تولید تصویر و سئوی محتوایی',
|
||||
agentName: 'Canina-Content-Agent',
|
||||
avatarColor: 'from-blue-600 to-indigo-700',
|
||||
icon: FileText,
|
||||
},
|
||||
{
|
||||
id: 'CLINICAL_RD',
|
||||
name: 'واحد تحقیق و توسعه بالینی (R&D)',
|
||||
role: 'فکتچکینگ پزشکی، اعتبارسنجی دوزها و مراجع داروسازی آلمان',
|
||||
agentName: 'Canina-Medical-Agent',
|
||||
avatarColor: 'from-emerald-600 to-teal-700',
|
||||
icon: Stethoscope,
|
||||
},
|
||||
{
|
||||
id: 'SEO',
|
||||
name: 'واحد سئو و هوش بازار',
|
||||
role: 'پایش سرچ کنسول، شناسایی کلمات کلیدی، بهینهسازی اسکیما و فید ترب',
|
||||
agentName: 'Canina-SEO-Agent',
|
||||
avatarColor: 'from-amber-500 to-orange-600',
|
||||
icon: Search,
|
||||
},
|
||||
{
|
||||
id: 'B2B',
|
||||
name: 'واحد توسعه سازمانی و B2B',
|
||||
role: 'پایپلاین کلینیکها، بیمارستانهای دامپزشکی و بستههای نمایندگی',
|
||||
agentName: 'Canina-B2B-Agent',
|
||||
avatarColor: 'from-purple-600 to-violet-800',
|
||||
icon: Building2,
|
||||
},
|
||||
{
|
||||
id: 'DEVOPS',
|
||||
name: 'واحد مهندسی، زیرساخت و امنیت',
|
||||
role: 'پایش سلامت کانتینرها، مصرف دیسک، SSL و پایپلاین آزمونمحور TDD',
|
||||
agentName: 'Canina-DevOps-Agent',
|
||||
avatarColor: 'from-rose-600 to-red-700',
|
||||
icon: Cpu,
|
||||
},
|
||||
{
|
||||
id: 'SUPPORT',
|
||||
name: 'واحد پشتیبانی و مشاوره هوشمند',
|
||||
role: 'پاسخگویی به مشتریان، تریاژ پرسشهای پت و ثبت تیکتهای پیگیری',
|
||||
agentName: 'Canina-Support-Agent',
|
||||
avatarColor: 'from-cyan-600 to-blue-700',
|
||||
icon: Headphones,
|
||||
}
|
||||
];
|
||||
|
||||
export default function CompanyOrchestrationHQ() {
|
||||
const [departments, setDepartments] = useState<DepartmentCard[]>([]);
|
||||
const [totalPendingApprovals, setTotalPendingApprovals] = useState<number>(0);
|
||||
const [totalTasksCount, setTotalTasksCount] = useState<number>(0);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(true);
|
||||
const [hasError, setHasError] = useState<boolean>(false);
|
||||
|
||||
const fetchLiveStatus = async () => {
|
||||
setIsLoading(true);
|
||||
setHasError(false);
|
||||
try {
|
||||
const [_statsRes, tasksRes, approvalsRes] = await Promise.all([
|
||||
api.get('/admin/department-tasks/stats'),
|
||||
api.get('/admin/department-tasks?limit=100'),
|
||||
api.get('/admin/approvals?limit=100')
|
||||
]);
|
||||
|
||||
const tasks = tasksRes.data?.data || [];
|
||||
const approvals = approvalsRes.data?.data || [];
|
||||
|
||||
// Calculate operational pending approvals (excluding non-authorization items)
|
||||
const pendingApprovalsList = approvals.filter((a: any) =>
|
||||
a.status === 'PENDING' && a.category !== 'B2B_SUPPLIER_STRATEGY'
|
||||
);
|
||||
setTotalPendingApprovals(pendingApprovalsList.length);
|
||||
setTotalTasksCount(tasks.length);
|
||||
|
||||
const mapped: DepartmentCard[] = BASE_DEPARTMENTS.map(base => {
|
||||
const deptTasks = tasks.filter((t: any) =>
|
||||
t.department === base.id || (base.id === 'DEVOPS' && t.department === 'DEV')
|
||||
);
|
||||
const inProgress = deptTasks.find((t: any) => t.status === 'IN_PROGRESS');
|
||||
const latestTask = deptTasks[0];
|
||||
const completedCount = deptTasks.filter((t: any) => t.status === 'DONE').length;
|
||||
|
||||
let status: 'ACTIVE' | 'PROCESSING' | 'STANDBY' = 'STANDBY';
|
||||
if (inProgress) status = 'ACTIVE';
|
||||
else if (deptTasks.some((t: any) => t.status === 'TEST' || t.status === 'WAITING_DEPENDENCIES')) {
|
||||
status = 'PROCESSING';
|
||||
}
|
||||
|
||||
let currentFocus = 'آمادهباش / بدون وظیفه فعال در حال حاضر';
|
||||
if (inProgress) currentFocus = inProgress.title;
|
||||
else if (latestTask) currentFocus = latestTask.title;
|
||||
|
||||
let snippet = 'بدون ثبت لاگ اجرایی در وظایف اخیر.';
|
||||
if (latestTask?.executionLogs?.length) {
|
||||
const lastLog = latestTask.executionLogs[latestTask.executionLogs.length - 1];
|
||||
snippet = lastLog?.summary || lastLog?.note || (lastLog?.deliverable?.type ? `تحویل خروجی: ${lastLog.deliverable.type}` : snippet);
|
||||
}
|
||||
|
||||
// Real department-specific pending approvals (strictly from live data, no synthetic telemetry)
|
||||
const deptPendingCount = pendingApprovalsList.filter((a: any) =>
|
||||
a.department === base.id || (base.id === 'DEVOPS' && a.department === 'DEV')
|
||||
).length;
|
||||
|
||||
return {
|
||||
...base,
|
||||
status,
|
||||
currentFocus,
|
||||
pendingApprovals: deptPendingCount,
|
||||
completedTasks: completedCount,
|
||||
recentReasoningSnippet: snippet
|
||||
};
|
||||
});
|
||||
|
||||
setDepartments(mapped);
|
||||
} catch (err) {
|
||||
console.error('Error fetching live orchestration telemetry:', err);
|
||||
setHasError(true);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchLiveStatus();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="space-y-6 font-vazir" dir="rtl">
|
||||
{/* Honest Executive Header */}
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-3xl border border-gray-200 shadow-sm">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-3 bg-purple-100 text-purple-700 rounded-2xl border border-purple-200">
|
||||
<Building2 className="w-8 h-8" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl md:text-2xl font-black text-gray-900 flex items-center gap-3">
|
||||
وضعیت و ارکستراسیون دپارتمانها (Department Governance Status)
|
||||
{hasError ? (
|
||||
<span className="text-[10px] px-2.5 py-1 rounded-full font-black bg-rose-100 text-rose-800 border border-rose-300">
|
||||
خطا در همگامسازی وضعیت
|
||||
</span>
|
||||
) : isLoading ? (
|
||||
<span className="text-[10px] px-2.5 py-1 rounded-full font-black bg-blue-100 text-blue-800 border border-blue-300">
|
||||
در حال دریافت دادهها...
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-[10px] px-2.5 py-1 rounded-full font-black bg-emerald-100 text-emerald-800 border border-emerald-300">
|
||||
دادههای زنده سیستم
|
||||
</span>
|
||||
)}
|
||||
</h1>
|
||||
<p className="text-xs text-gray-500 mt-1 font-medium">
|
||||
پایش وظایف، وضعیت و خروجی عملیاتی دپارتمانها و ایجنتها بر اساس دادههای واقعی سرویس
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2.5">
|
||||
<Link
|
||||
to="/manager-actions"
|
||||
className="flex items-center gap-1.5 px-3.5 py-2 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 border border-indigo-200 rounded-xl text-xs font-bold transition-all"
|
||||
>
|
||||
<Briefcase className="w-4 h-4 text-indigo-600" />
|
||||
<span>اقدامات مدیریتی و همکاریها</span>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to="/approvals"
|
||||
className="flex items-center gap-1.5 px-3.5 py-2 bg-amber-50 hover:bg-amber-100 text-amber-800 border border-amber-300 rounded-xl text-xs font-bold transition-all"
|
||||
>
|
||||
<ShieldCheck className="w-4 h-4 text-amber-600" />
|
||||
<span>مجوزهای عملیاتی ({totalPendingApprovals} مورد)</span>
|
||||
</Link>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchLiveStatus}
|
||||
disabled={isLoading}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs font-bold transition-all border border-gray-200 cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-3.5 h-3.5 ${isLoading ? 'animate-spin' : ''}`} />
|
||||
<span>تازهسازی</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Honest Error State */}
|
||||
{hasError ? (
|
||||
<div className="bg-white p-8 rounded-3xl border border-rose-200 shadow-sm text-center space-y-3">
|
||||
<XCircle className="w-12 h-12 text-rose-500 mx-auto" />
|
||||
<h3 className="text-base font-black text-gray-900">دادههای وضعیت در دسترس نیست</h3>
|
||||
<p className="text-xs text-gray-500 max-w-md mx-auto">
|
||||
امکان ارتباط با سرویس ارکستراسیون یا دریافت آمار وظایف دپارتمانها وجود ندارد. به منظور حفظ صداقت عملیاتی، هیچ وضعیت شبیهسازیشدهای رندر نمیشود.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchLiveStatus}
|
||||
className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-xl text-xs font-bold transition-all"
|
||||
>
|
||||
تلاش مجدد جهت اتصال
|
||||
</button>
|
||||
</div>
|
||||
) : isLoading ? (
|
||||
<div className="py-24 flex flex-col justify-center items-center gap-3">
|
||||
<RefreshCw className="w-8 h-8 text-purple-600 animate-spin" />
|
||||
<span className="text-xs font-bold text-gray-500">در حال واکشی وضعیت واقعی دپارتمانها...</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Honest Metrics Summary */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs">
|
||||
<span className="text-[11px] font-bold text-gray-500">کل دپارتمانهای سازمانی</span>
|
||||
<p className="text-2xl font-black text-gray-900 mt-1 font-mono">{departments.length}</p>
|
||||
</div>
|
||||
<div className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs">
|
||||
<span className="text-[11px] font-bold text-gray-500">کل وظایف ثبتشده</span>
|
||||
<p className="text-2xl font-black text-gray-900 mt-1 font-mono">{totalTasksCount}</p>
|
||||
</div>
|
||||
<div className="bg-white p-4 rounded-2xl border border-amber-200 shadow-xs">
|
||||
<span className="text-[11px] font-bold text-amber-700">مجوزهای عملیاتی معلق</span>
|
||||
<p className="text-2xl font-black text-amber-700 mt-1 font-mono">{totalPendingApprovals}</p>
|
||||
</div>
|
||||
<div className="bg-white p-4 rounded-2xl border border-emerald-200 shadow-xs">
|
||||
<span className="text-[11px] font-bold text-emerald-700">دپارتمانهای در حال کار</span>
|
||||
<p className="text-2xl font-black text-emerald-700 mt-1 font-mono">
|
||||
{departments.filter(d => d.status === 'ACTIVE').length}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Department Cards Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||
{departments.map((dept) => (
|
||||
<div
|
||||
key={dept.id}
|
||||
className="bg-white border border-gray-200 rounded-3xl p-5 hover:border-purple-300 hover:shadow-md transition-all flex flex-col justify-between shadow-xs"
|
||||
>
|
||||
<div>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`p-3 rounded-2xl bg-gradient-to-br ${dept.avatarColor} text-white shadow-xs`}>
|
||||
<dept.icon className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-sm font-black text-gray-900">{dept.name}</h3>
|
||||
<p className="text-[11px] text-purple-700 font-bold">{dept.agentName}</p>
|
||||
</div>
|
||||
</div>
|
||||
<span className={`text-[10px] font-black px-2 py-0.5 rounded-full border ${
|
||||
dept.status === 'ACTIVE'
|
||||
? 'bg-emerald-50 text-emerald-800 border-emerald-200'
|
||||
: dept.status === 'PROCESSING'
|
||||
? 'bg-amber-50 text-amber-800 border-amber-200'
|
||||
: 'bg-gray-100 text-gray-600 border-gray-200'
|
||||
}`}>
|
||||
{dept.status === 'ACTIVE' ? 'در حال کار' : dept.status === 'PROCESSING' ? 'در حال تست' : 'آمادهباش'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-gray-600 mt-3 font-medium leading-relaxed">
|
||||
{dept.role}
|
||||
</p>
|
||||
|
||||
<div className="mt-4 p-3 rounded-2xl bg-gray-50 border border-gray-100 space-y-1">
|
||||
<div className="text-[10px] font-bold text-gray-500 flex items-center gap-1.5">
|
||||
<Activity className="w-3.5 h-3.5 text-purple-600" />
|
||||
<span>تمرکز فعلی دپارتمان:</span>
|
||||
</div>
|
||||
<p className="text-xs text-gray-800 font-medium line-clamp-1">
|
||||
{dept.currentFocus}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-2 p-3 rounded-2xl bg-gray-50 border border-gray-100 space-y-1">
|
||||
<div className="text-[10px] font-bold text-gray-500 flex items-center gap-1.5">
|
||||
<Terminal className="w-3.5 h-3.5 text-purple-600" />
|
||||
<span>آخرین لاگ و استدلال واقعی:</span>
|
||||
</div>
|
||||
<p className="text-[11px] text-gray-700 font-mono leading-relaxed line-clamp-2">
|
||||
{dept.recentReasoningSnippet}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-5 pt-4 border-t border-gray-100 flex items-center justify-between text-xs">
|
||||
<div className="space-x-2 space-x-reverse text-gray-600">
|
||||
<span>وظایف انجامشده: <strong className="text-gray-900 font-bold">{dept.completedTasks}</strong></span>
|
||||
{dept.pendingApprovals > 0 && (
|
||||
<span className="text-amber-700 font-bold">({dept.pendingApprovals} مجوز معلق)</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Link
|
||||
to="/tasks"
|
||||
className="flex items-center gap-1 text-purple-700 hover:text-purple-800 font-bold text-xs"
|
||||
>
|
||||
<span>مشاهده وظایف</span>
|
||||
<ArrowUpRight className="w-3.5 h-3.5" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Activity, DollarSign, ShoppingCart, Users, ShieldAlert, ArrowLeft, History, Briefcase, Clock, Database } from "lucide-react";
|
||||
import { Activity, DollarSign, ShoppingCart, Users, ShieldAlert, ArrowLeft, History, Briefcase, Database } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { CartesianGrid, Cell, Line, LineChart, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
|
||||
@@ -117,10 +117,10 @@ export default function Dashboard() {
|
||||
const COLORS = ['#8b5cf6', '#3b82f6', '#10b981'];
|
||||
|
||||
const stats = [
|
||||
{ title: 'درآمد کل', value: `${data.revenue.toLocaleString()} تومان`, icon: DollarSign, color: 'text-green-600', bg: 'bg-green-100', link: '/reports' },
|
||||
{ title: 'سفارشات جدید', value: data.newOrders.toString(), icon: ShoppingCart, color: 'text-blue-600', bg: 'bg-blue-100', link: '/orders' },
|
||||
{ title: 'کاربران فعال', value: data.users.toString(), icon: Users, color: 'text-purple-600', bg: 'bg-purple-100', link: '/users' },
|
||||
{ title: 'بازدید امروز', value: data.todayVisits.toString(), icon: Activity, color: 'text-orange-600', bg: 'bg-orange-100', link: '/reports' },
|
||||
{ title: 'درآمد کل', value: `${(data?.revenue || 0).toLocaleString()} تومان`, icon: DollarSign, color: 'text-green-600', bg: 'bg-green-100', link: '/reports' },
|
||||
{ title: 'سفارشات جدید', value: (data?.newOrders || 0).toString(), icon: ShoppingCart, color: 'text-blue-600', bg: 'bg-blue-100', link: '/orders' },
|
||||
{ title: 'کاربران فعال', value: (data?.users || 0).toString(), icon: Users, color: 'text-purple-600', bg: 'bg-purple-100', link: '/users' },
|
||||
{ title: 'بازدید امروز', value: (data?.todayVisits || 0).toString(), icon: Activity, color: 'text-orange-600', bg: 'bg-orange-100', link: '/reports' },
|
||||
];
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import CompanyOrchestrationHQ from './CompanyOrchestrationHQ';
|
||||
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn() } }));
|
||||
|
||||
describe('governance source integrity', () => {
|
||||
beforeEach(() => { vi.clearAllMocks(); });
|
||||
it('shows unavailable instead of a synthetic active department when APIs fail', async () => {
|
||||
vi.mocked(api.get).mockRejectedValue(new Error('offline'));
|
||||
render(<MemoryRouter><CompanyOrchestrationHQ /></MemoryRouter>);
|
||||
expect(await screen.findByText(/دادههای وضعیت در دسترس نیست/)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/سیستم زنده و فعال/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/نمای سهبعدی و بصری/)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import ManagerActionsPage from './ManagerActionsPage';
|
||||
|
||||
vi.mock('../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
put: vi.fn(),
|
||||
post: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('react-hot-toast', () => ({
|
||||
default: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockItems = [
|
||||
{
|
||||
id: 'act-supplier-1',
|
||||
category: 'B2B_SUPPLIER_STRATEGY',
|
||||
department: 'B2B',
|
||||
title: 'توسعه استراتژی تامینکننده صدف لبسبز آلمان',
|
||||
status: 'IN_PROGRESS',
|
||||
createdAt: '2026-10-19T08:00:00Z',
|
||||
payload: {
|
||||
'1_مسئله_و_شکاف_بازار': 'کمبود ماده موثره پودر صدف در خطوط تولید داخلی',
|
||||
'2_راهحل_و_مزیت_کنینا': 'عقد تفاهمنامه مستقیم با تامینکننده لوکزامبورگ/آلمان',
|
||||
'3_طرح_اقدام_عملیاتی': 'مذاکره بازرگانی جهت دریافت نمونه آزمایشگاهی و بچ آزمایشی',
|
||||
'4_دپارتمانهای_مسئول': 'B2B, CLINICAL_RD',
|
||||
},
|
||||
// No outcome or evidence yet
|
||||
outcome: null,
|
||||
evidence: null,
|
||||
},
|
||||
{
|
||||
id: 'act-supplier-2',
|
||||
category: 'B2B_SUPPLIER_STRATEGY',
|
||||
department: 'B2B',
|
||||
title: 'قرارداد عاملیت توزیع کلینیکی بیمارستان دامپزشکی مرکزی',
|
||||
status: 'COMPLETED',
|
||||
createdAt: '2026-10-18T10:00:00Z',
|
||||
payload: {
|
||||
partner_name: 'بیمارستان دامپزشکی مرکزی',
|
||||
scope: 'توزیع انحصاری مکملهای مفاصل و آرامبخش',
|
||||
},
|
||||
outcome: 'انعقاد قرارداد رسمی عاملیت توزیع سالانه با سهمیه ماهانه ۵۰ بسته',
|
||||
evidence: 'قرارداد امضاشده شماره B2B-1405-091 در بایگانی حقوقی',
|
||||
},
|
||||
{
|
||||
id: 'auth-seo-1',
|
||||
category: 'SEO',
|
||||
department: 'SEO',
|
||||
title: 'تغییر عنوان متاتگ و ریدایرکتهای مقالات مفاصل',
|
||||
status: 'PENDING',
|
||||
createdAt: '2026-10-19T09:00:00Z',
|
||||
payload: {
|
||||
target_url: '/blog/joint-supplements-guide',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
describe('ManagerActionsPage Component', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: mockItems,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('renders B2B_SUPPLIER_STRATEGY items and excludes operational SEO authorizations', async () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ManagerActionsPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(await screen.findByText('توسعه استراتژی تامینکننده صدف لبسبز آلمان')).toBeInTheDocument();
|
||||
expect(screen.getByText('قرارداد عاملیت توزیع کلینیکی بیمارستان دامپزشکی مرکزی')).toBeInTheDocument();
|
||||
|
||||
// SEO item belongs strictly in operational authorization queue, not here!
|
||||
expect(screen.queryByText('تغییر عنوان متاتگ و ریدایرکتهای مقالات مفاصل')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('never displays an approval button; requires explicit outcome and evidence for completion', async () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ManagerActionsPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
await screen.findByText('توسعه استراتژی تامینکننده صدف لبسبز آلمان');
|
||||
|
||||
// Rule: Manager actions are NOT operational authorizations. No "approval" button allowed!
|
||||
expect(screen.queryByRole('button', { name: /تایید و صدور مجوز اجرا/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /تایید درخواست/i })).not.toBeInTheDocument();
|
||||
|
||||
// Incomplete manager action shows explicit requirement indicator
|
||||
expect(screen.getByText(/نیازمند ثبت نتیجه و مدرک جهت احراز تکمیل/i)).toBeInTheDocument();
|
||||
|
||||
// Completed action displays its explicit outcome and evidence
|
||||
expect(screen.getByText(/انعقاد قرارداد رسمی عاملیت توزیع سالانه با سهمیه ماهانه ۵۰ بسته/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/قرارداد امضاشده شماره B2B-1405-091 در بایگانی حقوقی/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/تکمیلشده و احراز شده با مستندات/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('allows recording explicit outcome and evidence for an action', async () => {
|
||||
vi.mocked(api.put).mockResolvedValue({
|
||||
data: { success: true },
|
||||
});
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ManagerActionsPage />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(await screen.findByText('توسعه استراتژی تامینکننده صدف لبسبز آلمان')).toBeInTheDocument();
|
||||
|
||||
const outcomeInput = screen.getByPlaceholderText(/نتیجه حاصله از این اقدام مدیریتی.../i);
|
||||
const evidenceInput = screen.getByPlaceholderText(/مستندات، شماره سند، لینک گزارش یا فایل.../i);
|
||||
|
||||
fireEvent.change(outcomeInput, { target: { value: 'نمونه اولیه آزمایشگاهی با خلوص ۹۸٪ تایید شد' } });
|
||||
fireEvent.change(evidenceInput, { target: { value: 'گواهی آنالیز آزمایشگاه رازی کد QA-9921' } });
|
||||
|
||||
const submitBtn = screen.getByRole('button', { name: /ثبت نتیجه و مستندات اقدام/i });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.put).toHaveBeenCalledWith(
|
||||
'/admin/approvals/act-supplier-1/decide',
|
||||
expect.objectContaining({
|
||||
outcome: 'نمونه اولیه آزمایشگاهی با خلوص ۹۸٪ تایید شد',
|
||||
evidence: 'گواهی آنالیز آزمایشگاه رازی کد QA-9921',
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,477 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import {
|
||||
Building2,
|
||||
Briefcase,
|
||||
CheckCircle2,
|
||||
AlertTriangle,
|
||||
Clock,
|
||||
RefreshCw,
|
||||
Search,
|
||||
FileText,
|
||||
ShieldCheck,
|
||||
Send,
|
||||
AlertCircle,
|
||||
Layers,
|
||||
} from 'lucide-react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import toast from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
|
||||
interface ManagerActionItem {
|
||||
id: string;
|
||||
department: string;
|
||||
category: string;
|
||||
title: string;
|
||||
payload: any;
|
||||
status: string;
|
||||
ceoNotes?: string;
|
||||
outcome?: string | null;
|
||||
evidence?: string | null;
|
||||
createdAt: string;
|
||||
executedAt?: string;
|
||||
}
|
||||
|
||||
export default function ManagerActionsPage() {
|
||||
const [items, setItems] = useState<ManagerActionItem[]>([]);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [error, setError] = useState<boolean>(false);
|
||||
const [searchQuery, setSearchQuery] = useState<string>('');
|
||||
const [statusFilter, setStatusFilter] = useState<'ALL' | 'VERIFIED' | 'PENDING_EVIDENCE'>('ALL');
|
||||
|
||||
// Input states for outcome and evidence editing
|
||||
const [actionForm, setActionForm] = useState<Record<string, { outcome: string; evidence: string }>>({});
|
||||
const [submittingId, setSubmittingId] = useState<string | null>(null);
|
||||
|
||||
const fetchActions = async () => {
|
||||
setLoading(true);
|
||||
setError(false);
|
||||
try {
|
||||
const res = await api.get('/admin/approvals?limit=100');
|
||||
if (res.data?.success && Array.isArray(res.data.data)) {
|
||||
// Manager actions are strategic categories like B2B_SUPPLIER_STRATEGY or PARTNERSHIP
|
||||
// Operational authorizations (SEO, PRICING, SMS, etc.) are strictly excluded!
|
||||
const managerActions = res.data.data.filter((item: any) =>
|
||||
item.category === 'B2B_SUPPLIER_STRATEGY' ||
|
||||
item.category === 'PARTNERSHIP' ||
|
||||
(item.department === 'B2B' && item.category?.includes('STRATEGY'))
|
||||
);
|
||||
|
||||
const initialForms: Record<string, { outcome: string; evidence: string }> = {};
|
||||
managerActions.forEach((item: ManagerActionItem) => {
|
||||
initialForms[item.id] = {
|
||||
outcome: item.outcome || item.payload?.outcome || item.payload?.['نتیجه_اقدام'] || '',
|
||||
evidence: item.evidence || item.payload?.evidence || item.payload?.['مستندات_و_مدرک'] || '',
|
||||
};
|
||||
});
|
||||
|
||||
setItems(managerActions);
|
||||
setActionForm(initialForms);
|
||||
} else {
|
||||
setError(true);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch manager actions:', err);
|
||||
setError(true);
|
||||
toast.error('خطا در دریافت لیست اقدامات مدیریتی');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchActions();
|
||||
}, []);
|
||||
|
||||
const handleSaveEvidence = async (id: string) => {
|
||||
const form = actionForm[id] || { outcome: '', evidence: '' };
|
||||
if (!form.outcome.trim() || !form.evidence.trim()) {
|
||||
toast.error('برای ثبت اقدام، درج هر دو مورد نتیجه و مدرک/مستندات الزامی است.');
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmittingId(id);
|
||||
try {
|
||||
const res = await api.put(`/admin/approvals/${id}/decide`, {
|
||||
decision: 'APPROVED',
|
||||
outcome: form.outcome.trim(),
|
||||
evidence: form.evidence.trim(),
|
||||
ceoNotes: `اقدام تکمیل شد با نتیجه: ${form.outcome.trim()}`,
|
||||
});
|
||||
|
||||
if (res.data?.success) {
|
||||
toast.success('نتیجه و مستندات اقدام مدیریتی با موفقیت ثبت شد');
|
||||
// Update local item with verified outcome and evidence
|
||||
setItems((prev) =>
|
||||
prev.map((item) =>
|
||||
item.id === id
|
||||
? {
|
||||
...item,
|
||||
status: 'COMPLETED',
|
||||
outcome: form.outcome.trim(),
|
||||
evidence: form.evidence.trim(),
|
||||
}
|
||||
: item
|
||||
)
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to update manager action evidence:', err);
|
||||
toast.error('خطا در ثبت نتیجه و مستندات اقدام');
|
||||
} finally {
|
||||
setSubmittingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredItems = useMemo(() => {
|
||||
return items.filter((item) => {
|
||||
const isVerified = Boolean(item.outcome?.trim()) && Boolean(item.evidence?.trim());
|
||||
|
||||
if (statusFilter === 'VERIFIED' && !isVerified) return false;
|
||||
if (statusFilter === 'PENDING_EVIDENCE' && isVerified) return false;
|
||||
|
||||
if (searchQuery.trim()) {
|
||||
const q = searchQuery.toLowerCase().trim();
|
||||
const form = actionForm[item.id] || { outcome: '', evidence: '' };
|
||||
const matchTitle = item.title?.toLowerCase().includes(q);
|
||||
const matchDept = item.department?.toLowerCase().includes(q);
|
||||
const matchPayload = JSON.stringify(item.payload || {}).toLowerCase().includes(q);
|
||||
const matchOutcome = (item.outcome || form.outcome)?.toLowerCase().includes(q);
|
||||
if (!matchTitle && !matchDept && !matchPayload && !matchOutcome) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}, [items, actionForm, statusFilter, searchQuery]);
|
||||
|
||||
const verifiedCount = items.filter(
|
||||
(item) => Boolean(item.outcome?.trim()) && Boolean(item.evidence?.trim())
|
||||
).length;
|
||||
const pendingEvidenceCount = items.length - verifiedCount;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-7xl mx-auto p-4 md:p-6 font-vazir text-gray-900 bg-gray-50 min-h-screen" dir="rtl">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white p-6 rounded-3xl border border-gray-200/80 shadow-xs">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-2xl bg-indigo-100 flex items-center justify-center text-indigo-700 shadow-xs">
|
||||
<Briefcase className="w-6 h-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl md:text-2xl font-black text-gray-900 tracking-tight">
|
||||
اقدامات مدیریتی و همکاریها (Manager Strategic Actions & Partnerships)
|
||||
</h1>
|
||||
<p className="text-xs text-gray-500 font-medium mt-1 leading-relaxed">
|
||||
طرحهای راهبردی، پروژههای B2B و تامینکنندگان. این موارد مجوز سیستمی نیستند؛ تکمیل اقدام صرفاً با احراز نتیجه و مستندات معتبر صورت میگیرد.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2.5">
|
||||
<Link
|
||||
to="/approvals"
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-2xl bg-amber-50 hover:bg-amber-100 text-amber-800 text-xs font-bold transition-all border border-amber-300"
|
||||
>
|
||||
<ShieldCheck className="w-4 h-4 text-amber-600" />
|
||||
<span>رفتن به مجوزهای عملیاتی</span>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to="/tasks"
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-2xl bg-purple-50 hover:bg-purple-100 text-purple-700 text-xs font-bold transition-all border border-purple-200"
|
||||
>
|
||||
<Layers className="w-4 h-4 text-purple-600" />
|
||||
<span>مشاهده وظایف دپارتمانها</span>
|
||||
</Link>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchActions}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-2xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs font-bold transition-all border border-gray-200 cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span className="hidden sm:inline">تازهسازی</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Governance Directive Banner */}
|
||||
<div className="bg-indigo-50/80 border border-indigo-200 p-4 rounded-2xl flex items-start gap-3">
|
||||
<AlertCircle className="w-5 h-5 text-indigo-700 shrink-0 mt-0.5" />
|
||||
<div className="text-xs text-indigo-950 space-y-1">
|
||||
<p className="font-bold">قانون تفکیک حاکمیتی اقدامات مدیریتی از مجوزهای عملیاتی:</p>
|
||||
<p className="leading-relaxed text-indigo-900">
|
||||
طرحهای استراتژیک تامینکنندگان (B2B_SUPPLIER_STRATEGY) و همکاریهای تجاری، وظایف انسانی و راهبردی هستند که دکمه تایید فوری ندارند. تکمیل این موارد صرفاً با درج صریح نتیجه واقعی (Outcome) و مستندات قابل اعتبارسنجی (Evidence) محقق میشود.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* KPI Cards */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3.5">
|
||||
<div className="bg-white p-4 rounded-2xl border border-gray-200/80 shadow-xs flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-[11px] font-bold text-gray-500">کل اقدامات مدیریتی</p>
|
||||
<p className="text-2xl font-black text-gray-900 mt-1 font-mono">{items.length}</p>
|
||||
</div>
|
||||
<div className="w-10 h-10 rounded-xl bg-indigo-50 text-indigo-700 flex items-center justify-center font-bold">
|
||||
<Building2 className="w-5 h-5" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-4 rounded-2xl border border-amber-300 shadow-xs flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-[11px] font-bold text-amber-700">نیازمند ثبت نتیجه و مدرک</p>
|
||||
<p className="text-2xl font-black text-amber-700 mt-1 font-mono">{pendingEvidenceCount}</p>
|
||||
</div>
|
||||
<div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-700 flex items-center justify-center font-bold">
|
||||
<Clock className="w-5 h-5" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-4 rounded-2xl border border-emerald-200 shadow-xs flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-[11px] font-bold text-emerald-700">تکمیل و احراز شده با مستندات</p>
|
||||
<p className="text-2xl font-black text-emerald-700 mt-1 font-mono">{verifiedCount}</p>
|
||||
</div>
|
||||
<div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-700 flex items-center justify-center font-bold">
|
||||
<CheckCircle2 className="w-5 h-5" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filters Bar */}
|
||||
<div className="bg-white p-4 rounded-3xl border border-gray-200/80 shadow-xs flex flex-col md:flex-row gap-3 items-center justify-between">
|
||||
<div className="relative w-full md:w-96">
|
||||
<Search className="w-4 h-4 text-gray-400 absolute right-3.5 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="جستجو در عنوان اقدام، تامینکننده، دپارتمان..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full pr-10 pl-4 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-indigo-500 font-medium text-gray-900"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 w-full md:w-auto">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('ALL')}
|
||||
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
|
||||
statusFilter === 'ALL'
|
||||
? 'bg-indigo-600 text-white shadow-xs'
|
||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
همه موارد ({items.length})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('PENDING_EVIDENCE')}
|
||||
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
|
||||
statusFilter === 'PENDING_EVIDENCE'
|
||||
? 'bg-amber-600 text-white shadow-xs'
|
||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
نیازمند نتیجه ({pendingEvidenceCount})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('VERIFIED')}
|
||||
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
|
||||
statusFilter === 'VERIFIED'
|
||||
? 'bg-emerald-600 text-white shadow-xs'
|
||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
احراز شده ({verifiedCount})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main List */}
|
||||
{error ? (
|
||||
<div className="bg-white p-8 rounded-3xl border border-rose-200 text-center space-y-3">
|
||||
<AlertTriangle className="w-12 h-12 text-rose-500 mx-auto" />
|
||||
<h3 className="text-base font-black text-gray-900">دریافت اقدامات ناموفق بود</h3>
|
||||
<p className="text-xs text-gray-500">امکان برقراری ارتباط با سرور و واکشی اقدامات مدیریتی وجود ندارد.</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={fetchActions}
|
||||
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold transition-all"
|
||||
>
|
||||
تلاش مجدد
|
||||
</button>
|
||||
</div>
|
||||
) : loading ? (
|
||||
<div className="py-24 flex flex-col justify-center items-center gap-3">
|
||||
<RefreshCw className="w-8 h-8 text-indigo-600 animate-spin" />
|
||||
<span className="text-xs font-bold text-gray-500">در حال دریافت اقدامات مدیریتی...</span>
|
||||
</div>
|
||||
) : filteredItems.length === 0 ? (
|
||||
<div className="bg-white p-12 text-center rounded-3xl border border-gray-200/80 shadow-xs space-y-2">
|
||||
<CheckCircle2 className="w-12 h-12 text-indigo-500 mx-auto mb-2" />
|
||||
<h3 className="text-base font-black text-gray-900">اقدامی در این فهرست یافت نشد</h3>
|
||||
<p className="text-xs text-gray-500">موردی با شرایط فیلتر انتخابشده مطابقت ندارد.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-5">
|
||||
{filteredItems.map((item) => {
|
||||
const form = actionForm[item.id] || { outcome: item.outcome || '', evidence: item.evidence || '' };
|
||||
const isCompleted = Boolean(item.outcome?.trim()) && Boolean(item.evidence?.trim());
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className={`bg-white rounded-3xl border transition-all overflow-hidden ${
|
||||
isCompleted ? 'border-emerald-200 shadow-xs' : 'border-amber-300 shadow-md ring-1 ring-amber-300/40'
|
||||
}`}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="p-5 border-b border-gray-100 flex flex-col md:flex-row justify-between items-start md:items-center gap-3 bg-gray-50/60">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-xl text-[11px] font-black border bg-indigo-50 text-indigo-800 border-indigo-200">
|
||||
<Building2 className="w-3.5 h-3.5 shrink-0" />
|
||||
<span>{item.category === 'B2B_SUPPLIER_STRATEGY' ? 'طرح استراتژیک تامینکننده' : item.category}</span>
|
||||
</span>
|
||||
<div>
|
||||
<h3 className="font-black text-gray-900 text-sm md:text-base leading-snug">
|
||||
{item.title}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2 mt-1 text-[11px] text-gray-500 font-medium">
|
||||
<span>دپارتمان: <strong className="text-gray-800">{item.department}</strong></span>
|
||||
<span>•</span>
|
||||
<span>
|
||||
ثبت: {new Intl.DateTimeFormat('fa-IR', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(item.createdAt))}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{isCompleted ? (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-black bg-emerald-50 text-emerald-800 border border-emerald-200">
|
||||
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" />
|
||||
<span>تکمیلشده و احراز شده با مستندات</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-black bg-amber-50 text-amber-800 border border-amber-300">
|
||||
<Clock className="w-3.5 h-3.5 text-amber-600" />
|
||||
<span>نیازمند ثبت نتیجه و مدرک جهت احراز تکمیل</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="p-5 space-y-4">
|
||||
{/* Strategic 5-Part Proposal Mapping */}
|
||||
{item.payload && (
|
||||
<div className="space-y-2.5">
|
||||
{item.payload['1_مسئله_و_شکاف_بازار'] && (
|
||||
<div className="p-3 bg-rose-50/60 border border-rose-200/80 rounded-xl text-xs">
|
||||
<span className="font-black text-rose-800 block mb-1">مسئله و شکاف بازار:</span>
|
||||
<span className="text-gray-800">{item.payload['1_مسئله_و_شکاف_بازار']}</span>
|
||||
</div>
|
||||
)}
|
||||
{item.payload['2_راهحل_و_مزیت_کنینا'] && (
|
||||
<div className="p-3 bg-emerald-50/60 border border-emerald-200/80 rounded-xl text-xs">
|
||||
<span className="font-black text-emerald-800 block mb-1">راهحل و مزیت کنینا:</span>
|
||||
<span className="text-gray-800">{item.payload['2_راهحل_و_مزیت_کنینا']}</span>
|
||||
</div>
|
||||
)}
|
||||
{item.payload['3_طرح_اقدام_عملیاتی'] && (
|
||||
<div className="p-3 bg-blue-50/60 border border-blue-200/80 rounded-xl text-xs">
|
||||
<span className="font-black text-blue-800 block mb-1">طرح اقدام عملیاتی:</span>
|
||||
<span className="text-gray-800">{item.payload['3_طرح_اقدام_عملیاتی']}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Explicit Outcome & Evidence Section */}
|
||||
<div className="bg-gray-50/90 rounded-2xl p-4 border border-gray-200 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-black text-gray-800 flex items-center gap-1.5">
|
||||
<FileText className="w-4 h-4 text-indigo-600" />
|
||||
<span>نتیجه و مدرک تحقق اقدام (Outcome & Evidence)</span>
|
||||
</span>
|
||||
<span className="text-[11px] text-gray-500 font-medium">
|
||||
تکمیل صرفاً با مستندات معتبر احراز میشود
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{isCompleted ? (
|
||||
<div className="space-y-2 text-xs">
|
||||
<div className="p-3 bg-white rounded-xl border border-emerald-200 space-y-1">
|
||||
<span className="text-emerald-800 font-bold block">نتیجه حاصله (Outcome):</span>
|
||||
<p className="text-gray-800 font-medium">{item.outcome}</p>
|
||||
</div>
|
||||
<div className="p-3 bg-white rounded-xl border border-emerald-200 space-y-1">
|
||||
<span className="text-emerald-800 font-bold block">مستندات و مدرک تحقق (Evidence):</span>
|
||||
<p className="text-gray-800 font-medium">{item.evidence}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
<label className="text-[11px] font-bold text-gray-700 block">
|
||||
نتیجه حاصله از این اقدام مدیریتی (Outcome):
|
||||
</label>
|
||||
<textarea
|
||||
rows={2}
|
||||
placeholder="نتیجه حاصله از این اقدام مدیریتی..."
|
||||
value={form.outcome}
|
||||
onChange={(e) =>
|
||||
setActionForm((prev) => ({
|
||||
...prev,
|
||||
[item.id]: { ...form, outcome: e.target.value },
|
||||
}))
|
||||
}
|
||||
className="w-full p-2.5 text-xs bg-white border border-gray-200 rounded-xl focus:outline-none focus:border-indigo-500 font-medium"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-[11px] font-bold text-gray-700 block">
|
||||
مستندات و مدرک تحقق (Evidence):
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="مستندات، شماره سند، لینک گزارش یا فایل..."
|
||||
value={form.evidence}
|
||||
onChange={(e) =>
|
||||
setActionForm((prev) => ({
|
||||
...prev,
|
||||
[item.id]: { ...form, evidence: e.target.value },
|
||||
}))
|
||||
}
|
||||
className="w-full p-2.5 text-xs bg-white border border-gray-200 rounded-xl focus:outline-none focus:border-indigo-500 font-medium"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end pt-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleSaveEvidence(item.id)}
|
||||
disabled={submittingId === item.id || !form.outcome.trim() || !form.evidence.trim()}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-black shadow-xs transition-all disabled:opacity-50 cursor-pointer"
|
||||
>
|
||||
<Send className="w-3.5 h-3.5" />
|
||||
<span>{submittingId === item.id ? 'در حال ثبت...' : 'ثبت نتیجه و مستندات اقدام'}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,17 +2,36 @@ import { act,fireEvent,render,screen } from '@testing-library/react';
|
||||
import { afterEach,beforeEach,describe,expect,it,vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import MonitoringPage from './MonitoringPage';
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), patch: vi.fn(), put: vi.fn(), post: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
describe('MonitoringPage', () => {
|
||||
|
||||
beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async (url) => ({ data: url === '/payment/admin/stats' ? { todayVolume: '125000', todayVerified: 4, successRate: 0 } : url === '/payment/admin/health' ? { status: 'ONLINE', latencyMs: 250 } : { credit: 0 } })); });
|
||||
afterEach(() => vi.useRealTimers());
|
||||
const load = async () => { render(<MonitoringPage />); await screen.findByText('1 رویداد ثبت شده'); };
|
||||
it('renders real volume and preserves zero success rate and SMS balance', async () => { await load(); expect(screen.getByText('۱۲۵٬۰۰۰ تومان')).toBeInTheDocument(); expect(screen.getByText('0%')).toBeInTheDocument(); expect(screen.getAllByText(/۰ پیامک/).length).toBeGreaterThan(0); });
|
||||
it('shows offline gateway and SMS on rejected endpoints instead of false healthy states', async () => { vi.mocked(api.get).mockRejectedValue(new Error('offline')); await load(); expect(screen.getAllByText('غیرفعال / قطعی')).toHaveLength(2); expect(screen.queryByText('98.4%')).not.toBeInTheDocument(); });
|
||||
it('honors explicit offline health response even when latency is low', async () => { vi.mocked(api.get).mockImplementation(async (url) => ({ data: url.includes('health') ? { status: 'OFFLINE', latencyMs: 10 } : { credit: 12 } })); await load(); expect(screen.getByText('غیرفعال / قطعی')).toBeInTheDocument(); });
|
||||
it('shows slow gateway warning and refreshes all three read-only endpoints', async () => { vi.mocked(api.get).mockImplementation(async (url) => ({ data: url.includes('health') ? { latencyMs: 2000 } : { credit: 12 } })); await load(); expect(screen.getByText('کاهش سرعت / هشدار')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: /بروزرسانی زنده/ })); await screen.findByText('2 رویداد ثبت شده'); expect(api.get).toHaveBeenCalledTimes(6); expect(api.post).not.toHaveBeenCalled(); });
|
||||
it('polls after 30 seconds and cleans timer on unmount', async () => { vi.useFakeTimers(); const view = render(<MonitoringPage />); await act(async () => { await Promise.resolve(); }); expect(api.get).toHaveBeenCalledTimes(3); for (let i=0; i<30; i++) await act(async () => { vi.advanceTimersByTime(1000); }); expect(api.get).toHaveBeenCalledTimes(6); view.unmount(); await act(async () => { vi.advanceTimersByTime(60000); }); expect(api.get).toHaveBeenCalledTimes(6); });
|
||||
|
||||
vi.mock('../services/api',()=>({default:{get:vi.fn()}}));
|
||||
describe('measured monitoring',()=>{
|
||||
beforeEach(()=>{vi.resetAllMocks();vi.mocked(api.get).mockImplementation(async url=>({data:url.includes('/stats')?{todayVolume:0,todayVerified:0,successRate:0}:url.includes('/health')?{status:'ONLINE',latencyMs:0}:{credit:0}}))});
|
||||
afterEach(()=>vi.useRealTimers());
|
||||
it('preserves measured zero but never manufactures database health, post latency, uptime or environment',async()=>{
|
||||
render(<MonitoringPage/>);await screen.findByText('0%');
|
||||
expect(screen.getByText('0 ms')).toBeInTheDocument();
|
||||
expect(screen.getByText('۰ پیامک')).toBeInTheDocument();
|
||||
expect(screen.getByText('Database: Unknown — no measured endpoint')).toBeInTheDocument();
|
||||
expect(screen.getByText('Environment: Unknown — no measured endpoint')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Production')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/۱۴ روز/)).not.toBeInTheDocument();
|
||||
});
|
||||
it.each([0,125])('accepts the real flat SMS success response with credit %s',async credit=>{
|
||||
vi.mocked(api.get).mockResolvedValue({data:{success:true,credit,message:'اعتبار پیامک'}});
|
||||
render(<MonitoringPage/>);
|
||||
expect(await screen.findByText(credit.toLocaleString('fa-IR')+' پیامک')).toBeInTheDocument();
|
||||
expect(screen.queryByText(/Invalid measurement response/)).not.toBeInTheDocument();
|
||||
});
|
||||
it('marks failures unknown rather than online and permits measured refresh',async()=>{
|
||||
vi.mocked(api.get).mockRejectedValue(new Error('connection refused'));
|
||||
render(<MonitoringPage/>);expect(await screen.findAllByText(/connection refused/)).toHaveLength(3);
|
||||
expect(screen.queryByText('ONLINE')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'Refresh measurements'}));
|
||||
await screen.findAllByText(/connection refused/);expect(api.get).toHaveBeenCalledTimes(6);
|
||||
});
|
||||
it('polls and cancels on unmount',async()=>{
|
||||
vi.useFakeTimers();const view=render(<MonitoringPage/>);await act(async()=>{});
|
||||
expect(api.get).toHaveBeenCalledTimes(3);
|
||||
await act(async()=>{vi.advanceTimersByTime(30000)});expect(api.get).toHaveBeenCalledTimes(6);
|
||||
view.unmount();await act(async()=>{vi.advanceTimersByTime(60000)});expect(api.get).toHaveBeenCalledTimes(6);
|
||||
});
|
||||
});
|
||||
@@ -1,364 +1,31 @@
|
||||
import {
|
||||
Activity,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
CreditCard,
|
||||
Database,
|
||||
FileText,
|
||||
MessageSquare,
|
||||
RefreshCw,
|
||||
Truck
|
||||
} from 'lucide-react';
|
||||
import { useCallback,useEffect,useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import Badge from '../components/ui/Badge';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import Button from '../components/ui/Button';
|
||||
import Skeleton from '../components/ui/Skeleton';
|
||||
import api from '../services/api';
|
||||
|
||||
interface MonitoringStats {
|
||||
timestamp: string;
|
||||
zibal: {
|
||||
status: 'ONLINE' | 'DEGRADED' | 'OFFLINE';
|
||||
latencyMs: number;
|
||||
merchantId?: string;
|
||||
todayVolumeTomans: number;
|
||||
todayTxCount: number;
|
||||
successRate: number;
|
||||
};
|
||||
melipayamak: {
|
||||
status: 'ONLINE' | 'DEGRADED' | 'OFFLINE';
|
||||
credit: number | string;
|
||||
latencyMs: number;
|
||||
todaySmsSent: number;
|
||||
patternActive: boolean;
|
||||
};
|
||||
post: {
|
||||
status: 'ONLINE' | 'DEGRADED' | 'OFFLINE';
|
||||
latencyMs: number;
|
||||
trackingActive: boolean;
|
||||
};
|
||||
system: {
|
||||
backendStatus: 'HEALTHY' | 'DEGRADED';
|
||||
dbStatus: 'CONNECTED' | 'DISCONNECTED';
|
||||
dbLatencyMs: number;
|
||||
uptimeSeconds: number;
|
||||
environment: string;
|
||||
};
|
||||
}
|
||||
|
||||
type Measurement = {data:Record<string,unknown>|null;error:string|null;observedAt:string};
|
||||
const endpoints = ['/payment/admin/stats','/payment/admin/health','/settings/sms/credit'] as const;
|
||||
const value=(v:unknown,suffix='') => v===null||v===undefined ? 'Unknown — not measured' : String(v)+suffix;
|
||||
export default function MonitoringPage() {
|
||||
const [stats, setStats] = useState<MonitoringStats | null>(null);
|
||||
const [, setIsLoading] = useState(true);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const [autoRefresh] = useState(true);
|
||||
const [refreshInterval] = useState(30); // seconds
|
||||
const [countdown, setCountdown] = useState(30);
|
||||
const [logs, setLogs] = useState<any[]>([]);
|
||||
|
||||
const fetchMonitoringData = useCallback(async (silent = false) => {
|
||||
try {
|
||||
if (!silent) setIsRefreshing(true);
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
// Parallel real queries to live endpoints
|
||||
const [txStatsRes, healthRes, smsRes] = await Promise.allSettled([
|
||||
api.get('/payment/admin/stats').catch(() => ({ data: null })),
|
||||
api.get('/payment/admin/health').catch(() => ({ data: null })),
|
||||
api.get('/settings/sms/credit').catch(() => ({ data: null })),
|
||||
]);
|
||||
|
||||
const roundTripMs = Date.now() - startTime;
|
||||
|
||||
const txStats = txStatsRes.status === 'fulfilled' ? txStatsRes.value?.data : null;
|
||||
const health = healthRes.status === 'fulfilled' ? healthRes.value?.data : null;
|
||||
const sms = smsRes.status === 'fulfilled' ? smsRes.value?.data : null;
|
||||
const smsCreditVal = typeof sms === 'object' && sms !== null ? sms.credit ?? sms.balance ?? sms.data : sms;
|
||||
|
||||
const newStats: MonitoringStats = {
|
||||
timestamp: new Date().toLocaleTimeString('fa-IR'),
|
||||
zibal: {
|
||||
status: !health || health.status === 'OFFLINE' ? 'OFFLINE' : health.status === 'DEGRADED' || health.latencyMs > 1500 ? 'DEGRADED' : 'ONLINE',
|
||||
latencyMs: health?.latencyMs ?? 0,
|
||||
merchantId: health?.activeMerchant || health?.merchantId || 'zibal-live-merchant',
|
||||
todayVolumeTomans: txStats?.todayVolume ? Math.floor(Number(txStats.todayVolume)) : 0,
|
||||
todayTxCount: txStats?.todayVerified || txStats?.verifiedCount || 0,
|
||||
successRate: txStats?.successRate ?? 0,
|
||||
},
|
||||
melipayamak: {
|
||||
status: smsCreditVal !== undefined && smsCreditVal !== null ? 'ONLINE' : 'OFFLINE',
|
||||
credit: smsCreditVal !== undefined && smsCreditVal !== null ? `${Number(smsCreditVal).toLocaleString('fa-IR')} پیامک` : 'نامشخص',
|
||||
latencyMs: 0,
|
||||
todaySmsSent: 48,
|
||||
patternActive: true,
|
||||
},
|
||||
|
||||
post: {
|
||||
status: 'ONLINE',
|
||||
latencyMs: 0,
|
||||
trackingActive: true,
|
||||
},
|
||||
system: {
|
||||
backendStatus: 'HEALTHY',
|
||||
dbStatus: 'CONNECTED',
|
||||
dbLatencyMs: Math.max(12, roundTripMs - 120),
|
||||
uptimeSeconds: 86400 * 14 + 3600 * 5,
|
||||
environment: 'Production',
|
||||
},
|
||||
};
|
||||
|
||||
setStats(newStats);
|
||||
|
||||
// Append live log
|
||||
setLogs((prev) => [
|
||||
{
|
||||
id: Date.now(),
|
||||
time: new Date().toLocaleTimeString('fa-IR'),
|
||||
service: 'HealthCheck',
|
||||
type: 'INFO',
|
||||
message: `پایش بلادرنگ انجام شد. زیبال: ${newStats.zibal.latencyMs}ms | پیامک: ${newStats.melipayamak.credit} | سیستم: ${newStats.system.dbLatencyMs}ms`,
|
||||
},
|
||||
...prev.slice(0, 19),
|
||||
]);
|
||||
} catch (e) {
|
||||
console.error('Failed to load monitoring data', e);
|
||||
if (!silent) toast.error('خطا در دریافت وضعیت سرور و سرویسهای واسط');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setIsRefreshing(false);
|
||||
setCountdown(refreshInterval);
|
||||
}
|
||||
}, [refreshInterval]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchMonitoringData();
|
||||
}, [fetchMonitoringData]);
|
||||
|
||||
// Auto-refresh countdown ticker
|
||||
useEffect(() => {
|
||||
if (!autoRefresh) return;
|
||||
const interval = setInterval(() => {
|
||||
setCountdown((prev) => {
|
||||
if (prev <= 1) {
|
||||
fetchMonitoringData(true);
|
||||
return refreshInterval;
|
||||
}
|
||||
return prev - 1;
|
||||
});
|
||||
}, 1000);
|
||||
return () => clearInterval(interval);
|
||||
}, [autoRefresh, refreshInterval, fetchMonitoringData]);
|
||||
|
||||
const getStatusBadge = (status: 'ONLINE' | 'DEGRADED' | 'OFFLINE' | 'HEALTHY' | 'CONNECTED' | 'DISCONNECTED') => {
|
||||
switch (status) {
|
||||
case 'ONLINE':
|
||||
case 'HEALTHY':
|
||||
case 'CONNECTED':
|
||||
return <Badge variant="success" size="sm">آنلاین و فعال</Badge>;
|
||||
case 'DEGRADED':
|
||||
return <Badge variant="warning" size="sm">کاهش سرعت / هشدار</Badge>;
|
||||
case 'OFFLINE':
|
||||
case 'DISCONNECTED':
|
||||
return <Badge variant="danger" size="sm">غیرفعال / قطعی</Badge>;
|
||||
default:
|
||||
return <Badge variant="slate" size="sm">نامشخص</Badge>;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 font-vazir pb-12" dir="rtl">
|
||||
{/* Top Action Header */}
|
||||
<div className="bg-white p-5 sm:p-6 rounded-3xl border border-gray-100 shadow-xs flex flex-col md:flex-row md:items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3.5">
|
||||
<div className="w-12 h-12 rounded-2xl bg-gradient-to-tr from-purple-600 to-indigo-600 text-white flex items-center justify-center shadow-lg shadow-purple-500/20 shrink-0">
|
||||
<Activity className="w-6 h-6 animate-pulse" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-black text-gray-900 flex items-center gap-2">
|
||||
مرکز مانیتورینگ بلادرنگ سیستم و درگاهها
|
||||
<span className="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-ping inline-block" />
|
||||
</h1>
|
||||
<p className="text-xs text-gray-500 font-medium mt-1">
|
||||
پایش آنلاین وضعیت اتصالات بانکی زیبال، سامانه پیامک ملیپیامک، وبسرویس پستی و دیتابیس
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2.5 self-end md:self-center">
|
||||
<div className="flex items-center gap-2 bg-gray-50 border border-gray-200 px-3 py-1.5 rounded-2xl text-xs font-bold text-gray-600">
|
||||
<Clock className="w-3.5 h-3.5 text-purple-600" />
|
||||
<span>بروزرسانی بعدی: {countdown} ثانیه</span>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
startIcon={RefreshCw}
|
||||
isLoading={isRefreshing}
|
||||
onClick={() => fetchMonitoringData(false)}
|
||||
>
|
||||
بروزرسانی زنده
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main Service Cards Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
|
||||
{/* Zibal Payment Gateway */}
|
||||
<div className="bg-white p-5 rounded-3xl border border-gray-100 shadow-xs space-y-4 hover:border-purple-200 transition-all">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="w-10 h-10 rounded-2xl bg-blue-50 text-blue-600 flex items-center justify-center">
|
||||
<CreditCard className="w-5 h-5" />
|
||||
</div>
|
||||
{stats ? getStatusBadge(stats.zibal.status) : <Skeleton className="w-16 h-6 rounded-full" />}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 className="font-black text-gray-900 text-sm">درگاه پرداخت زیبال (شاپرک)</h3>
|
||||
<p className="text-[11px] text-gray-400 font-medium">سرویس پرداخت و استرداد آنلاین</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 p-3.5 rounded-2xl space-y-2 text-xs">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">تاخیر پاسخگویی (Latency):</span>
|
||||
<span className="font-mono font-black text-blue-600">{stats?.zibal.latencyMs || 142} ms</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">حجم تراکنشهای امروز:</span>
|
||||
<span className="font-mono font-bold text-gray-900">{stats ? `${stats.zibal.todayVolumeTomans.toLocaleString('fa-IR')} تومان` : '...'}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">درصد موفقیت (Success Rate):</span>
|
||||
<span className="font-mono font-bold text-emerald-600">{stats?.zibal.successRate ?? 0}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Melipayamak SMS Gateway */}
|
||||
<div className="bg-white p-5 rounded-3xl border border-gray-100 shadow-xs space-y-4 hover:border-purple-200 transition-all">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="w-10 h-10 rounded-2xl bg-emerald-50 text-emerald-600 flex items-center justify-center">
|
||||
<MessageSquare className="w-5 h-5" />
|
||||
</div>
|
||||
{stats ? getStatusBadge(stats.melipayamak.status) : <Skeleton className="w-16 h-6 rounded-full" />}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 className="font-black text-gray-900 text-sm">سامانه پیامک (ملیپیامک)</h3>
|
||||
<p className="text-[11px] text-gray-400 font-medium">ارسال پترن کد تایید و لاگ وضعیت سفارش</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 p-3.5 rounded-2xl space-y-2 text-xs">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">موجودی پنل:</span>
|
||||
<span className="font-mono font-black text-emerald-700">{stats?.melipayamak.credit || '...'}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">تاخیر وبسرویس SOAP:</span>
|
||||
<span className="font-mono font-black text-emerald-600">{stats?.melipayamak.latencyMs || 88} ms</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">ارسالهای امروز:</span>
|
||||
<span className="font-mono font-bold text-gray-900">{stats?.melipayamak.todaySmsSent || 48} پیامک</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Postal Tracking Service */}
|
||||
<div className="bg-white p-5 rounded-3xl border border-gray-100 shadow-xs space-y-4 hover:border-purple-200 transition-all">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="w-10 h-10 rounded-2xl bg-amber-50 text-amber-600 flex items-center justify-center">
|
||||
<Truck className="w-5 h-5" />
|
||||
</div>
|
||||
{stats ? getStatusBadge(stats.post.status) : <Skeleton className="w-16 h-6 rounded-full" />}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 className="font-black text-gray-900 text-sm">سامانه رهگیری پستی و تیپاکس</h3>
|
||||
<p className="text-[11px] text-gray-400 font-medium">استعلام آنلاین وضعیت بارنامه و مرسولات</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 p-3.5 rounded-2xl space-y-2 text-xs">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">وضعیت اتصال:</span>
|
||||
<span className="font-bold text-amber-700">برقرار و فعال</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">پاسخگویی سرور پست:</span>
|
||||
<span className="font-mono font-black text-amber-600">{stats?.post.latencyMs || 155} ms</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">سرویس بارکدخوان:</span>
|
||||
<span className="font-bold text-emerald-600">فعال (OCR / Text)</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Database & Core System */}
|
||||
<div className="bg-white p-5 rounded-3xl border border-gray-100 shadow-xs space-y-4 hover:border-purple-200 transition-all">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="w-10 h-10 rounded-2xl bg-purple-50 text-purple-600 flex items-center justify-center">
|
||||
<Database className="w-5 h-5" />
|
||||
</div>
|
||||
{stats ? getStatusBadge(stats.system.dbStatus) : <Skeleton className="w-16 h-6 rounded-full" />}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 className="font-black text-gray-900 text-sm">پایگاه داده و سرور اصلی</h3>
|
||||
<p className="text-[11px] text-gray-400 font-medium">PostgreSQL / Redis Cache</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 p-3.5 rounded-2xl space-y-2 text-xs">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">پینگ دیتابیس:</span>
|
||||
<span className="font-mono font-black text-purple-600">{stats?.system.dbLatencyMs || 18} ms</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">محیط استقرار:</span>
|
||||
<span className="font-bold text-gray-900">{stats?.system.environment || 'Production'}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">آپتایم سرور:</span>
|
||||
<span className="font-mono font-bold text-emerald-600">۱۴ روز و ۵ ساعت</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Live Activity & Inspection Feed */}
|
||||
<div className="bg-white rounded-3xl p-6 border border-gray-100 shadow-xs space-y-4">
|
||||
<div className="flex items-center justify-between border-b border-gray-100 pb-4">
|
||||
<h3 className="font-black text-gray-900 text-sm flex items-center gap-2">
|
||||
<FileText className="w-4 h-4 text-purple-600" />
|
||||
لاگ بلادرنگ بررسی سلامت سرویسها (Live Health Inspection Log)
|
||||
</h3>
|
||||
<span className="text-xs text-gray-400 font-bold">{logs.length} رویداد ثبت شده</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 overflow-x-auto">
|
||||
{logs.length === 0 ? (
|
||||
<div className="text-center py-6 text-xs text-gray-400">در حال دریافت لاگهای زنده...</div>
|
||||
) : (
|
||||
logs.map((log) => (
|
||||
<div
|
||||
key={log.id}
|
||||
className="flex items-center justify-between p-3 rounded-2xl bg-gray-50 border border-gray-100 text-xs gap-3"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="font-mono font-bold text-gray-400">{log.time}</span>
|
||||
<Badge variant="blue" size="sm">{log.service}</Badge>
|
||||
<span className="font-medium text-gray-700">{log.message}</span>
|
||||
</div>
|
||||
<span className="font-bold text-emerald-600 flex items-center gap-1 shrink-0">
|
||||
<CheckCircle2 className="w-3.5 h-3.5" />
|
||||
موفق
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
const [measurements,setMeasurements]=useState<Measurement[]>([]);
|
||||
const [loading,setLoading]=useState(false); const active=useRef(true);const inFlight=useRef(false);
|
||||
const refresh=useCallback(async()=>{
|
||||
if(inFlight.current)return;inFlight.current=true;setLoading(true);
|
||||
const results=await Promise.all(endpoints.map(async url=>{
|
||||
try {const {data:raw}=await api.get(url);const data=raw?.success===true&&Object.hasOwn(raw,'data')?raw.data:raw;
|
||||
if(!data||typeof data!=='object'||raw?.success===false)throw new Error('Invalid measurement response');
|
||||
return {data,error:null,observedAt:new Date().toISOString()};
|
||||
}catch(e){return {data:null,error:e instanceof Error?e.message:'Request failed',observedAt:new Date().toISOString()}}
|
||||
}));
|
||||
if(active.current){setMeasurements(results);setLoading(false)}inFlight.current=false;
|
||||
},[]);
|
||||
useEffect(()=>{active.current=true;void refresh();const timer=setInterval(()=>void refresh(),30000);return()=>{active.current=false;clearInterval(timer)}},[refresh]);
|
||||
const [stats,health,sms]=measurements;const tx=stats?.data;const gateway=health?.data;const credit=sms?.data?.credit??sms?.data?.balance;
|
||||
return <div className="space-y-5 font-vazir pb-12"><header className="bg-white p-5 border rounded-2xl flex justify-between"><div><h1 className="font-black text-xl">Measured service monitoring</h1><p>Only backend-reported values. Unknown is not healthy. Polling every 30 seconds.</p></div><Button disabled={loading} onClick={()=>void refresh()}>Refresh measurements</Button></header>
|
||||
{loading&&<p role="status">Loading measurements…</p>}
|
||||
<div className="grid md:grid-cols-3 gap-4">{['Payment statistics','Payment gateway health','SMS credit'].map((title,index)=><section key={title} className="bg-white border rounded-2xl p-5 space-y-3"><h2 className="font-bold">{title}</h2><p className="text-xs break-all">Source: {endpoints[index]}</p><p>Observed at: {measurements[index]?.observedAt??'Unknown'}</p>{measurements[index]?.error&&<p role="alert" className="text-red-700">Unknown — {measurements[index].error}</p>}
|
||||
{index===0&&<dl><dt>Today volume (toman)</dt><dd>{value(tx?.todayVolume)}</dd><dt>Verified transactions</dt><dd>{value(tx?.todayVerified??tx?.verifiedCount)}</dd><dt>Success rate</dt><dd>{value(tx?.successRate,'%')}</dd></dl>}
|
||||
{index===1&&<dl><dt>Reported status</dt><dd>{value(gateway?.status)}</dd><dt>Reported latency</dt><dd>{value(gateway?.latencyMs,' ms')}</dd><dt>Merchant</dt><dd>{value(gateway?.activeMerchant??gateway?.merchantId)}</dd></dl>}
|
||||
{index===2&&<p>{typeof credit==='number'?credit.toLocaleString('fa-IR')+' پیامک':value(credit)}</p>}
|
||||
</section>)}</div>
|
||||
<section className="bg-amber-50 border rounded-2xl p-5 space-y-2"><h2 className="font-bold">Uninstrumented services</h2>{['Database','Redis','Post service','OCR','Uptime','Environment','SMS sent today','SMS latency','Agent runtime'].map(label=><p key={label}>{label}: Unknown — no measured endpoint</p>)}</section>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import api from '../services/api';
|
||||
import ApprovalsPage from './ApprovalsPage';
|
||||
|
||||
vi.mock('../services/api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }));
|
||||
vi.mock('react-hot-toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
|
||||
|
||||
const item = (id: string, category: string, status = 'PENDING') => ({
|
||||
id, category, status, department: category === 'SEO' ? 'SEO' : 'B2B',
|
||||
title: id, payload: {}, createdAt: '2026-10-19T10:00:00Z',
|
||||
});
|
||||
|
||||
describe('operational authorization boundary', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({ data: {
|
||||
success: true,
|
||||
data: [item('supplier-action', 'B2B_SUPPLIER_STRATEGY'), item('seo-approval', 'SEO')],
|
||||
meta: { pendingCount: 2 },
|
||||
} });
|
||||
});
|
||||
|
||||
it('does not expose a supplier manager action as authorization while SEO remains', async () => {
|
||||
render(<ApprovalsPage />);
|
||||
expect(await screen.findByText('seo-approval')).toBeInTheDocument();
|
||||
expect(screen.queryByText('supplier-action')).not.toBeInTheDocument();
|
||||
expect(screen.getAllByRole('button', { name: /تایید و صدور مجوز اجرا/ })).toHaveLength(1);
|
||||
expect(screen.getByText(/1 پیشنهاد منتظر تصمیم شما/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
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';
|
||||
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,chat:true,runtime:false}}};
|
||||
if(url.endsWith('/tasks')) return {data:[task]};
|
||||
if(url.endsWith('/tasks/t1')) return {data:task};
|
||||
throw new Error('Unavailable: '+url);
|
||||
}); });
|
||||
it('loads server tasks, immutable bounds and only server actions; unavailable data is never fabricated', async () => {
|
||||
render(<OrchestrationCommandCenter />);
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
expect(await screen.findByText(/Only staging/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button',{name:'Approve bounded work'})).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button',{name:'RUNNING'})).not.toBeInTheDocument();
|
||||
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('Scope / acceptance criteria unavailable — omitted by the safe backend projection.')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Immutable scope / acceptance criteria')).not.toBeInTheDocument();
|
||||
});
|
||||
it('requires explicit confirmation and expiry; retains idempotency across failed retry', async () => {
|
||||
vi.mocked(api.post).mockRejectedValue(new Error('network failure'));
|
||||
render(<OrchestrationCommandCenter />);
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Bounded SEO audit'}));
|
||||
fireEvent.click(await screen.findByRole('button',{name:'Approve bounded work'}));
|
||||
const dialog=screen.getByRole('dialog');
|
||||
expect(within(dialog).getByRole('button',{name:'Confirm command'})).toBeDisabled();
|
||||
fireEvent.change(within(dialog).getByLabelText('Expires at'),{target:{value:'2099-01-01T12:00'}});
|
||||
fireEvent.change(within(dialog).getByLabelText('Reason'),{target:{value:'Scope checked'}});
|
||||
fireEvent.click(within(dialog).getByLabelText('I reviewed the immutable scope and binding'));
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'Confirm command'}));
|
||||
expect(await within(dialog).findByRole('alert')).toHaveTextContent('network failure');
|
||||
expect(within(dialog).getByLabelText('Reason')).toBeDisabled();
|
||||
expect(within(dialog).getByLabelText('Expires at')).toBeDisabled();
|
||||
fireEvent.click(within(dialog).getByRole('button',{name:'Confirm command'}));
|
||||
await within(dialog).findByRole('alert');
|
||||
expect(api.post).toHaveBeenCalledTimes(2);
|
||||
const first=vi.mocked(api.post).mock.calls[0][1];
|
||||
expect(first).toEqual(expect.objectContaining({expectedVersion:4,decision:'APPROVED'}));
|
||||
expect(vi.mocked(api.post).mock.calls[1][1]).toEqual(first);
|
||||
});
|
||||
it('shows measured readiness snapshot and unknown optional services without synthetic cards',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>{
|
||||
if(url.endsWith('/tasks'))return {data:[]};
|
||||
return {data:{measuredAt:'2026-10-22T12:00:00Z',items:[{id:'agent-1',title:'SEO worker',status:'BLOCKED',readiness:'Missing model policy',department:'SEO'}]}};
|
||||
});
|
||||
render(<OrchestrationCommandCenter/>);
|
||||
fireEvent.click(screen.getByRole('button',{name:'Agents & departments'}));
|
||||
expect(await screen.findByText('Missing model policy')).toBeInTheDocument();
|
||||
expect(screen.getByText('BLOCKED')).toBeInTheDocument();
|
||||
});
|
||||
it('binds Gate2 using registered evidence, never editable commit or environment',async()=>{
|
||||
const release={...task,state:'GATE2_PENDING',availableActions:[{id:'g2',label:'Approve release',gate:2,decision:'APPROVED'}],runs:[{id:'run-1',status:'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'}));
|
||||
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:'Kill switch'}));
|
||||
expect(screen.getAllByRole('option')).toHaveLength(4);
|
||||
expect(screen.getByRole('button',{name:'Apply kill switch'})).toBeDisabled();
|
||||
fireEvent.change(screen.getByLabelText('Kill level'),{target:{value:'EMERGENCY_HALT'}});
|
||||
fireEvent.change(screen.getByLabelText('Kill reason'),{target:{value:'Incident'}});
|
||||
fireEvent.click(screen.getByLabelText('I confirm global operational impact'));
|
||||
fireEvent.click(screen.getByRole('button',{name:'Apply kill switch'}));
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Forbidden: role');
|
||||
expect(api.put).toHaveBeenCalledWith('/admin/orchestration/kill-switch',{level:'EMERGENCY_HALT',reason:'Incident'});
|
||||
});
|
||||
it('sends advisory chat via typed bridge and renders text, not HTML',async()=>{
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'reply',role:'assistant',content:'<script>unsafe</script>'}});
|
||||
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Chat'}));
|
||||
fireEvent.change(screen.getByLabelText('Session ID'),{target:{value:'session-1'}});
|
||||
fireEvent.change(screen.getByLabelText('Message'),{target:{value:'Explain bounded work'}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Send advisory message'}));
|
||||
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'}));
|
||||
});
|
||||
it('fails closed for creation, kill and chat when overview cannot authorize capabilities',async()=>{
|
||||
vi.mocked(api.get).mockImplementation(async url=>{if(url.endsWith('/tasks'))return {data:[task]};throw new Error('Unavailable');});
|
||||
render(<OrchestrationCommandCenter/>);await screen.findByRole('button',{name:'Bounded SEO audit'});
|
||||
fireEvent.click(screen.getByRole('button',{name:'Tasks & approvals'}));
|
||||
expect(screen.queryByText('Create bounded work')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'Kill switch'}));
|
||||
expect(screen.queryByRole('button',{name:'Apply kill switch'})).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button',{name:'Chat'}));
|
||||
expect(screen.queryByRole('button',{name:'Send advisory message'})).not.toBeInTheDocument();
|
||||
expect(api.post).not.toHaveBeenCalled();expect(api.put).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import Button from '../components/ui/Button';
|
||||
import RouterUsagePanel from '../components/RouterUsagePanel';
|
||||
import CreateOrchestrationTask from '../components/CreateOrchestrationTask';
|
||||
import { orchestration, killLevels } from '../services/orchestration';
|
||||
import type { Task, ServerAction, Resource, ResourceSnapshot, KillLevel, ChatMessage } from '../services/orchestration';
|
||||
const sections = ['Overview','Tasks & approvals','Runs & artifacts','Agents & departments','Models & budgets','Schedules','Audit & releases','Kill switch','9router usage & quota','Chat'] as const;
|
||||
type Section = typeof sections[number];
|
||||
const resources:Partial<Record<Section,Resource>> = {'Agents & departments':'agents','Models & budgets':'model-policy','Schedules':'schedules','Audit & releases':'releases'};
|
||||
const errorText=(e:unknown)=> e instanceof Error ? e.message : 'Unknown backend error';
|
||||
function Json({value}:{value:unknown}) {return <pre className="text-xs whitespace-pre-wrap break-all bg-gray-50 border rounded-xl p-3" dir="ltr">{JSON.stringify(value,null,2)}</pre>}
|
||||
export default function OrchestrationCommandCenter() {
|
||||
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 [snapshot,setSnapshot]=useState<ResourceSnapshot|null>(null);
|
||||
const [error,setError]=useState(''); const [loading,setLoading]=useState(false);
|
||||
const [search,setSearch]=useState('');
|
||||
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 [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})).catch(()=>setCapabilities({mutations:false,chat:false,runtime:false}));},[]);
|
||||
useEffect(()=> {
|
||||
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)=>{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)return;
|
||||
setAttempted(true);setBusy(true);setCommandError('');
|
||||
try { const [runId,artifactHash]=binding.split('|');
|
||||
await orchestration.command(pending.task,pending.action,{idempotencyKey:pending.key,reason,expiresAt:expires?new Date(expires).toISOString():undefined,runId,artifactHash});
|
||||
setPending(null);setSelected(null);setSuccess('Command accepted by backend; refreshed authoritative state.');await loadTasks();
|
||||
} catch(e) {setCommandError(errorText(e)+' — Refresh before retrying a version conflict; network retries keep the same key.')} finally {setBusy(false)}
|
||||
};
|
||||
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 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==='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>}
|
||||
{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>}
|
||||
{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>;
|
||||
}
|
||||
@@ -37,6 +37,7 @@ export interface OrderItem {
|
||||
priceValue?: number;
|
||||
quantity?: number;
|
||||
product?: {
|
||||
requiresRx?: boolean;
|
||||
id?: string;
|
||||
nameFa?: string;
|
||||
name?: string;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import api from "../services/api";
|
||||
import SymptomsPage from "./SymptomsPage";
|
||||
vi.mock("../services/api", () => ({default: {get: vi.fn(), delete: vi.fn()}}));
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({data: {data: [{id:"symptom-1", name:"Anemia", slug:"anemia"}], meta:{lastPage:1}}});
|
||||
vi.mocked(api.delete).mockResolvedValue({data:{}});
|
||||
});
|
||||
it("shows deletion consequences and cancels without deleting, then confirms the selected symptom", async () => {
|
||||
render(<MemoryRouter><SymptomsPage/></MemoryRouter>);
|
||||
await screen.findByText("Anemia");
|
||||
fireEvent.click(screen.getByTitle("حذف"));
|
||||
expect(screen.getByText(/با حذف این علامت، ارتباط آن/)).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button",{name:"لغو"}));
|
||||
expect(screen.queryByText(/با حذف این علامت، ارتباط آن/)).not.toBeInTheDocument();
|
||||
expect(api.delete).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByTitle("حذف"));
|
||||
fireEvent.click(screen.getByRole("button",{name:"تایید"}));
|
||||
await waitFor(() => expect(api.delete).toHaveBeenCalledWith("/admin/symptoms/symptom-1"));
|
||||
await waitFor(() => expect(screen.queryByText(/با حذف این علامت، ارتباط آن/)).not.toBeInTheDocument());
|
||||
});
|
||||
@@ -22,7 +22,7 @@ export interface Symptom {
|
||||
}
|
||||
|
||||
export default function SymptomsPage() {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [searchParams] = useSearchParams();
|
||||
const [symptoms, setSymptoms] = useState<Symptom[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [search, setSearch] = useState(() => searchParams.get('search') || '');
|
||||
@@ -311,10 +311,10 @@ export default function SymptomsPage() {
|
||||
{/* Delete Confirmation */}
|
||||
<ConfirmModal
|
||||
isOpen={!!deleteTargetId}
|
||||
onClose={() => setDeleteTargetId(null)}
|
||||
onCancel={() => setDeleteTargetId(null)}
|
||||
onConfirm={handleDelete}
|
||||
title="حذف علامت بالینی"
|
||||
description="با حذف این علامت، ارتباط آن از تمام محصولات کاتالوگ نیز به طور خودکار حذف خواهد شد. آیا مطمئن هستید؟"
|
||||
message="با حذف این علامت، ارتباط آن از تمام محصولات کاتالوگ نیز به طور خودکار حذف خواهد شد. آیا مطمئن هستید؟"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Search,
|
||||
RefreshCw,
|
||||
@@ -7,10 +7,6 @@ import {
|
||||
ChevronDown,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Play,
|
||||
CheckCircle,
|
||||
Clock,
|
||||
Filter
|
||||
} from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
import toast from 'react-hot-toast';
|
||||
@@ -36,6 +32,7 @@ export default function TasksManagementPage() {
|
||||
const [tasks, setTasks] = useState<DepartmentTask[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [sortOrder, setSortOrder] = useState<'desc' | 'asc'>('desc');
|
||||
const [selectedDept, setSelectedDept] = useState('ALL');
|
||||
const [selectedStatus, setSelectedStatus] = useState('ALL');
|
||||
const [selectedPriority, setSelectedPriority] = useState('ALL');
|
||||
@@ -85,7 +82,12 @@ export default function TasksManagementPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const filteredTasks = tasks.filter((t) => {
|
||||
const sortedTasks = [...tasks].sort((a, b) => {
|
||||
const tA = new Date(a.createdAt || 0).getTime();
|
||||
const tB = new Date(b.createdAt || 0).getTime();
|
||||
return sortOrder === 'desc' ? tB - tA : tA - tB;
|
||||
});
|
||||
const filteredTasks = sortedTasks.filter((t) => {
|
||||
const matchesSearch =
|
||||
!searchTerm ||
|
||||
t.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
@@ -128,10 +130,22 @@ export default function TasksManagementPage() {
|
||||
۳. تست استیج و QA (TEST)
|
||||
</span>
|
||||
);
|
||||
case 'WAITING_DEPENDENCIES':
|
||||
return (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-violet-100 text-violet-800 border border-violet-200">
|
||||
۳. منتظر تکمیل اقدامات وابسته
|
||||
</span>
|
||||
);
|
||||
case 'DONE':
|
||||
return (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-emerald-100 text-emerald-800 border border-emerald-200">
|
||||
۴. مستقر پروداکشن (DONE)
|
||||
۴. خروجی راستیآزماییشده (DONE)
|
||||
</span>
|
||||
);
|
||||
case 'REJECTED':
|
||||
return (
|
||||
<span className="px-2 py-0.5 rounded-full text-[10px] font-black bg-rose-100 text-rose-800 border border-rose-200">
|
||||
رد شده (REJECTED)
|
||||
</span>
|
||||
);
|
||||
default:
|
||||
@@ -139,8 +153,28 @@ export default function TasksManagementPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusTransitionsSummary = (logsRaw: any) => {
|
||||
const list = Array.isArray(logsRaw) ? logsRaw : (typeof logsRaw === 'object' && logsRaw ? [logsRaw] : []);
|
||||
let inProgressCount = 0;
|
||||
let testCount = 0;
|
||||
let qaRejectedCount = 0;
|
||||
let qaPassedCount = 0;
|
||||
|
||||
list.forEach((entry: any) => {
|
||||
const st = String(entry?.status || '');
|
||||
if (st.includes('STARTED') || st === 'IN_PROGRESS') inProgressCount += 1;
|
||||
if (st.includes('COMPLETED') || st === 'TEST') testCount += 1;
|
||||
if (st === 'QA_FAILED') qaRejectedCount += 1;
|
||||
if (st === 'QA_PASSED') qaPassedCount += 1;
|
||||
});
|
||||
|
||||
return { inProgressCount, testCount, qaRejectedCount, qaPassedCount, totalEvents: list.length };
|
||||
};
|
||||
|
||||
const getPriorityBadge = (priority: string) => {
|
||||
switch (priority) {
|
||||
case 'CEO_EXPEDITE':
|
||||
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-purple-700 text-white rounded animate-pulse shadow-sm shadow-purple-300">⚡ فوری مدیرعامل</span>;
|
||||
case 'CRITICAL':
|
||||
return <span className="px-1.5 py-0.5 text-[9px] font-black bg-rose-600 text-white rounded">فوری / بحرانی</span>;
|
||||
case 'HIGH':
|
||||
@@ -248,11 +282,16 @@ export default function TasksManagementPage() {
|
||||
>
|
||||
<option value="ALL">همه دپارتمانها</option>
|
||||
<option value="DEV">مهندسی و توسعه (DEV)</option>
|
||||
<option value="DEVOPS">زیرساخت و سرور (DEVOPS)</option>
|
||||
<option value="SEO">سئو و مارکتپلیس (SEO)</option>
|
||||
<option value="CONTENT">محتوا و وبلاگ (CONTENT)</option>
|
||||
<option value="CLINICAL_RD">تحقیق و توسعه بالینی (CLINICAL_RD)</option>
|
||||
<option value="B2B">بازرگانی و توسعه کلینیکها (B2B)</option>
|
||||
<option value="SUPPORT">پشتیبانی مشتریان و CRM (SUPPORT)</option>
|
||||
<option value="QA">تضمین کیفیت و تست (QA)</option>
|
||||
<option value="COMMERCE">بازرگانی و مالی (COMMERCE)</option>
|
||||
<option value="PRODUCT">کاتالوگ و استوک (PRODUCT)</option>
|
||||
<option value="CONTENT">محتوا و وبلاگ (CONTENT)</option>
|
||||
<option value="SEO">سئو و مارکتپلیس (SEO)</option>
|
||||
<option value="PMO">مدیریت محصول و تضمین کیفیت (PMO)</option>
|
||||
<option value="PMO">مدیریت محصول و ارکستراسیون (PMO)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -268,8 +307,10 @@ export default function TasksManagementPage() {
|
||||
<option value="ALL">همه وضعیتها</option>
|
||||
<option value="TODO">۱. صف اقدام (TODO)</option>
|
||||
<option value="IN_PROGRESS">۲. در حال اجرا (IN_PROGRESS)</option>
|
||||
<option value="TEST">۳. تست و QA (TEST)</option>
|
||||
<option value="DONE">۴. تکمیل شده (DONE)</option>
|
||||
<option value="TEST">۳. تست استیج و QA (TEST)</option>
|
||||
<option value="WAITING_DEPENDENCIES">۴. منتظر اقدامات وابسته (WAITING_DEPENDENCIES)</option>
|
||||
<option value="DONE">۵. تکمیل و راستیآزماییشده (DONE)</option>
|
||||
<option value="REJECTED">۶. رد شده (REJECTED)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -283,6 +324,7 @@ export default function TasksManagementPage() {
|
||||
className="w-full px-3 py-2 text-xs bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:border-purple-500 font-bold text-gray-700"
|
||||
>
|
||||
<option value="ALL">همه اولویتها</option>
|
||||
<option value="CEO_EXPEDITE">⚡ فوری مدیرعامل (CEO_EXPEDITE)</option>
|
||||
<option value="CRITICAL">بحرانی / فوری</option>
|
||||
<option value="HIGH">بالا</option>
|
||||
<option value="MEDIUM">متوسط</option>
|
||||
@@ -310,6 +352,12 @@ export default function TasksManagementPage() {
|
||||
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black">
|
||||
<tr>
|
||||
<th className="py-3 px-4">کد تسک</th>
|
||||
<th className="py-3 px-4 cursor-pointer select-none hover:text-purple-700" onClick={() => setSortOrder(prev => prev === 'desc' ? 'asc' : 'desc')}>
|
||||
<div className="flex items-center gap-1">
|
||||
<span>تاریخ و ساعت (تهران)</span>
|
||||
<span className="text-[10px] text-purple-600">({sortOrder === 'desc' ? '▼ جدیدترین' : '▲ قدیمیترین'})</span>
|
||||
</div>
|
||||
</th>
|
||||
<th className="py-3 px-4">عنوان و شرح وظیفه</th>
|
||||
<th className="py-3 px-4">دپارتمان</th>
|
||||
<th className="py-3 px-4">اولویت</th>
|
||||
@@ -326,6 +374,16 @@ export default function TasksManagementPage() {
|
||||
{task.code}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-3.5 px-4 whitespace-nowrap text-xs text-gray-600 font-medium" dir="ltr">
|
||||
{task.createdAt ? new Intl.DateTimeFormat('fa-IR', {
|
||||
timeZone: 'Asia/Tehran',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
}).format(new Date(task.createdAt)) : '-'}
|
||||
</td>
|
||||
<td className="py-3.5 px-4">
|
||||
<div className="font-black text-gray-900 text-xs mb-0.5">{task.title}</div>
|
||||
{task.description && (
|
||||
@@ -443,8 +501,8 @@ export default function TasksManagementPage() {
|
||||
{/* Status Update Options */}
|
||||
<div className="pt-2">
|
||||
<label className="block text-xs font-black text-gray-700 mb-2">تغییر وضعیت تسک به:</label>
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
{['TODO', 'IN_PROGRESS', 'TEST', 'DONE'].map((st) => (
|
||||
<div className="grid grid-cols-3 sm:grid-cols-6 gap-2">
|
||||
{['TODO', 'IN_PROGRESS', 'TEST', 'WAITING_DEPENDENCIES', 'DONE', 'REJECTED'].map((st) => (
|
||||
<button
|
||||
key={st}
|
||||
type="button"
|
||||
@@ -473,16 +531,52 @@ export default function TasksManagementPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Execution Logs */}
|
||||
{/* Status History & Transitions Summary */}
|
||||
{activeTaskModal.executionLogs && (() => {
|
||||
const summary = getStatusTransitionsSummary(activeTaskModal.executionLogs);
|
||||
return (
|
||||
<div className="p-3 bg-purple-50/50 rounded-2xl border border-purple-100 space-y-2">
|
||||
<div className="font-bold text-purple-900 text-[11px] flex items-center justify-between">
|
||||
<span>آمار چرخهها و وضعیتهای طیشده تسک:</span>
|
||||
<span className="font-mono text-[10px] text-purple-700 bg-white px-2 py-0.5 rounded-full border border-purple-200">
|
||||
{summary.totalEvents} رکورد ثبتی
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
|
||||
<div className="bg-white p-2 rounded-xl border border-blue-100 text-center shadow-xs">
|
||||
<span className="block text-[10px] text-gray-500 font-bold">دفعات ارجاع به اجرا</span>
|
||||
<span className="text-xs font-black text-blue-700 font-mono">{summary.inProgressCount} بار</span>
|
||||
</div>
|
||||
<div className="bg-white p-2 rounded-xl border border-amber-100 text-center shadow-xs">
|
||||
<span className="block text-[10px] text-gray-500 font-bold">بررسی تست و QA</span>
|
||||
<span className="text-xs font-black text-amber-700 font-mono">{summary.testCount} بار</span>
|
||||
</div>
|
||||
<div className="bg-white p-2 rounded-xl border border-rose-100 text-center shadow-xs">
|
||||
<span className="block text-[10px] text-gray-500 font-bold">عدم تایید QA</span>
|
||||
<span className="text-xs font-black text-rose-700 font-mono">{summary.qaRejectedCount} بار</span>
|
||||
</div>
|
||||
<div className="bg-white p-2 rounded-xl border border-emerald-100 text-center shadow-xs">
|
||||
<span className="block text-[10px] text-gray-500 font-bold">تاییدیه کیفی</span>
|
||||
<span className="text-xs font-black text-emerald-700">{summary.qaPassedCount > 0 ? 'دارد (تایید)' : 'در جریان'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* Execution Logs Timeline */}
|
||||
{activeTaskModal.executionLogs && (
|
||||
<div className="pt-2 space-y-1">
|
||||
<div className="font-bold text-gray-600 text-[11px]">تاریخچه اقدامات انجامشده روی این تسک:</div>
|
||||
<div className="space-y-1 max-h-36 overflow-y-auto">
|
||||
<div className="pt-2 space-y-1.5">
|
||||
<div className="font-bold text-gray-600 text-[11px] flex items-center justify-between">
|
||||
<span>تایملاین رویدادها و تغییر وضعیتها:</span>
|
||||
<span className="text-[10px] text-gray-400">(به وقت تهران)</span>
|
||||
</div>
|
||||
<div className="space-y-1.5 max-h-48 overflow-y-auto p-1">
|
||||
{renderExecutionLogs(activeTaskModal.executionLogs).map((lg: any, i: number) => (
|
||||
<div key={i} className="text-[10px] p-2 bg-gray-50 rounded-lg flex items-center justify-between">
|
||||
<span className="font-bold text-gray-800">{lg.note || JSON.stringify(lg)}</span>
|
||||
<span className="text-gray-400 font-mono">
|
||||
{lg.timestamp ? new Date(lg.timestamp).toLocaleTimeString('fa-IR') : '-'}
|
||||
<div key={i} className="text-[10px] p-2.5 bg-gray-50 hover:bg-gray-100/70 rounded-xl flex items-start justify-between gap-3 border border-gray-100 transition-colors">
|
||||
<span className="font-bold text-gray-800 leading-relaxed text-right flex-1">{lg.note || JSON.stringify(lg)}</span>
|
||||
<span className="text-gray-400 font-mono text-[9px] whitespace-nowrap dir-ltr pt-0.5">
|
||||
{lg.timestamp ? new Date(lg.timestamp).toLocaleString('fa-IR', { hour: '2-digit', minute: '2-digit', second: '2-digit', day: '2-digit', month: '2-digit' }) : '-'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -50,9 +50,12 @@ const DoctorsManager = lazyWithRetry(() => import('../pages/DoctorsManager'));
|
||||
const FAQManager = lazyWithRetry(() => import('../pages/FAQManager'));
|
||||
const MenuManager = lazyWithRetry(() => import('../pages/MenuManager'));
|
||||
const MonitoringPage = lazyWithRetry(() => import('../pages/MonitoringPage'));
|
||||
const ManagerActionsPage = lazyWithRetry(() => import('../pages/ManagerActionsPage'));
|
||||
const ApprovalsPage = lazyWithRetry(() => import('../pages/ApprovalsPage'));
|
||||
const AuditHistoryPage = lazyWithRetry(() => import('../pages/AuditHistoryPage'));
|
||||
const TasksManagementPage = lazyWithRetry(() => import('../pages/TasksManagementPage'));
|
||||
const OrchestrationCommandCenter = lazyWithRetry(() => import('../pages/OrchestrationCommandCenter'));
|
||||
const CompanyOrchestrationHQ = lazyWithRetry(() => import('../pages/CompanyOrchestrationHQ'));
|
||||
|
||||
export interface AdminRouteConfig {
|
||||
path: string;
|
||||
@@ -119,8 +122,11 @@ export const router = createBrowserRouter([
|
||||
{ path: 'menu/*', element: <MenuManager /> },
|
||||
{ path: 'monitoring/*', element: <MonitoringPage /> },
|
||||
{ path: 'approvals/*', element: <ApprovalsPage /> },
|
||||
{ path: 'manager-actions/*', element: <ManagerActionsPage /> },
|
||||
{ path: 'history/*', element: <AuditHistoryPage /> },
|
||||
{ path: 'tasks/*', element: <TasksManagementPage /> },
|
||||
{ path: 'orchestration/*', element: <OrchestrationCommandCenter /> },
|
||||
{ path: 'governance/hq/*', element: <CompanyOrchestrationHQ /> },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import api from './api';
|
||||
import { orchestration } from './orchestration';
|
||||
import type { Task } from './orchestration';
|
||||
vi.mock('./api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn() } }));
|
||||
const task = {id:'t/1',version:7,state:'GATE2_PENDING',availableActions:[{id:'approve',label:'Approve',gate:2,decision:'APPROVED'}]} as Task;
|
||||
describe('orchestration adapter', () => {
|
||||
beforeEach(() => vi.resetAllMocks());
|
||||
it('loads bare task lists through existing authenticated client and fails closed without actions', async () => {
|
||||
vi.mocked(api.get).mockResolvedValue({data:[{id:'t1',title:'Bounded work',version:2,state:'READY'}]});
|
||||
const tasks = await orchestration.tasks();
|
||||
expect(api.get).toHaveBeenCalledWith('/admin/orchestration/tasks');
|
||||
expect(tasks[0].availableActions).toEqual([]);
|
||||
});
|
||||
it('rejects unadvertised transitions and incomplete Gate2 binding without a request', async () => {
|
||||
await expect(orchestration.command(task, {id:'invented',label:'Run',toState:'RUNNING'}, {idempotencyKey:'k',reason:'reviewed'})).rejects.toThrow(/advertised/);
|
||||
await expect(orchestration.command(task, task.availableActions[0], {idempotencyKey:'k',expiresAt:'2099-01-01T00:00:00Z'})).rejects.toThrow(/binding/);
|
||||
expect(api.put).not.toHaveBeenCalled(); expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
it('binds Gate2 to immutable registered run and sends version and retry-stable key', async () => {
|
||||
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,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(/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(/Invalid/);
|
||||
});
|
||||
it('requires kill reason and uses only typed message bridge', async () => {
|
||||
await expect(orchestration.kill('EMERGENCY_HALT','')).rejects.toThrow(/reason/);
|
||||
await expect(orchestration.chat('session',' ','key')).rejects.toThrow(/message/);
|
||||
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'});
|
||||
vi.mocked(api.post).mockResolvedValue({data:{id:'reply',role:'assistant',content:'Review complete'}});
|
||||
expect(await orchestration.chat('session','Review task','key')).toEqual({id:'reply',role:'assistant',content:'Review complete'});
|
||||
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:{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: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']}});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import api from './api';
|
||||
export interface ServerAction { id: string; label: string; toState?: string; gate?: 1 | 2; decision?: 'APPROVED' | 'REJECTED'; disabledReason?: string }
|
||||
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; 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}; 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:'OBSERVE'|'PREPARE'|'MUTATE_PRODUCTION';budgetLimitCents:number;metadata:{scope:string;acceptanceCriteria:string[]}}
|
||||
export const orchestration = {
|
||||
async create(input:CreateTaskInput):Promise<unknown> {
|
||||
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('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('Invalid resource snapshot');
|
||||
return data;
|
||||
},
|
||||
async kill(level:KillLevel,reason:string):Promise<unknown> {
|
||||
if (!killLevels.includes(level) || !reason.trim()) throw new Error('Kill switch level and reason required');
|
||||
return (await api.put('/admin/orchestration/kill-switch',{level,reason})).data;
|
||||
},
|
||||
async chat(sessionId:string,message:string,idempotencyKey:string):Promise<ChatMessage> {
|
||||
if (!sessionId.trim() || !message.trim() || !idempotencyKey) throw new Error('Session and message required');
|
||||
const data=unwrap<ChatMessage>((await api.post('/admin/orchestration/chat/messages',{sessionId,message,idempotencyKey})).data);
|
||||
if (!data?.id || data.role!=='assistant' || typeof data.content!=='string') throw new Error('Invalid typed chat reply');
|
||||
return data;
|
||||
},
|
||||
async command(task: Task, requested: ServerAction, input: CommandInput): Promise<unknown> {
|
||||
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.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?.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,expiresAt:input.expiresAt,notes:input.reason,...binding})).data;
|
||||
}
|
||||
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('Invalid orchestration task response');
|
||||
return rows.map(row => ({ ...row, availableActions: row.availableActions ?? [] }));
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
import {render,screen,fireEvent} from '@testing-library/react';
|
||||
import {it,expect,vi} from 'vitest';
|
||||
import api from './api';
|
||||
import {routerUsage} from './routerUsage';
|
||||
import RouterUsagePanel from '../components/RouterUsagePanel';
|
||||
vi.mock('./api',()=>({default:{get:vi.fn()}}));
|
||||
const metrics={requests:20,inputTokens:100,outputTokens:50,cacheReadTokens:0,cacheWriteTokens:null,reasoningTokens:null,errors:null};
|
||||
const snapshot={source:'9router',period:'7d',status:'available',reason:null,attribution:{scope:'9router_total',hermes:null,additive:false},freshness:{retrievedAt:'2026-10-22T12:00:00Z',sourceUpdatedAt:null,stale:null},data:{totals:metrics,providers:[{provider:'provider-a',...metrics}],models:[{model:'model-b',provider:'provider-a',...metrics}],accounts:[{accountId:'opaque-1',provider:'provider-a',model:'model-b',...metrics,quota:{status:'unknown',remaining:null,resetAt:null,reason:'upstream_quota_get_mutates_credentials'}}]}};
|
||||
it('renders concrete backend contract, unknown quota and source freshness; period selects backend filter',async()=>{
|
||||
vi.mocked(api.get).mockResolvedValue({data:snapshot});render(<RouterUsagePanel/>);
|
||||
expect(await screen.findByText('opaque-1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Gateway totals (includes Hermes)')).toBeInTheDocument();
|
||||
expect(screen.getByText('Hermes attribution: Unknown — not reported; do not add to gateway totals.')).toBeInTheDocument();
|
||||
expect(screen.getByText('9router')).toBeInTheDocument();
|
||||
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('Usage period'),{target:{value:'today'}});
|
||||
await screen.findByText('opaque-1');
|
||||
expect(api.get).toHaveBeenLastCalledWith('/admin/router-usage',{params:{period:'today'}});
|
||||
});
|
||||
it('rejects missing provenance instead of inventing freshness',async()=>{
|
||||
vi.mocked(api.get).mockResolvedValue({data:{accounts:[]}});
|
||||
await expect(routerUsage.snapshot()).rejects.toThrow(/Invalid/);
|
||||
});
|
||||
it('shows unavailable configuration honestly and discards arbitrary credential properties',async()=>{
|
||||
vi.mocked(api.get).mockResolvedValueOnce({data:{...snapshot,status:'unavailable',reason:'not_configured',data:null}});
|
||||
await expect(routerUsage.snapshot()).rejects.toThrow('not_configured');
|
||||
vi.mocked(api.get).mockResolvedValueOnce({data:{...snapshot,token:'secret',data:{...snapshot.data,credentials:'secret'}}});
|
||||
expect(JSON.stringify(await routerUsage.snapshot())).not.toContain('secret');
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import api from './api';
|
||||
export const usagePeriods=['today','24h','7d','30d','60d','all'] as const;
|
||||
export type UsagePeriod=typeof usagePeriods[number];
|
||||
export interface UsageCounters {requests:number|null;inputTokens:number|null;outputTokens:number|null;cacheReadTokens:number|null;cacheWriteTokens:number|null;reasoningTokens:number|null;errors:number|null}
|
||||
export interface UsageRow extends UsageCounters {provider:string|null;model?:string|null;accountId?:string|null;quota?:{status:string;remaining:number|null;resetAt:string|null;reason:string|null}}
|
||||
export interface RouterUsageSnapshot {source:string;period:UsagePeriod;freshness:{retrievedAt:string|null;sourceUpdatedAt:string|null;stale:boolean|null};attribution:{scope:'9router_total';hermes:null;additive:false};data:{totals:UsageCounters;providers:UsageRow[];models:UsageRow[];accounts:UsageRow[]}}
|
||||
const count=(v:unknown):number|null=>typeof v==='number'&&Number.isSafeInteger(v)&&v>=0?v:null;
|
||||
const text=(v:unknown):string|null=>typeof v==='string'?v:null;
|
||||
function counters(raw:UsageCounters):UsageCounters {
|
||||
return {requests:count(raw?.requests),inputTokens:count(raw?.inputTokens),outputTokens:count(raw?.outputTokens),cacheReadTokens:count(raw?.cacheReadTokens),cacheWriteTokens:count(raw?.cacheWriteTokens),reasoningTokens:count(raw?.reasoningTokens),errors:count(raw?.errors)};
|
||||
}
|
||||
function rows(list:UsageRow[]):UsageRow[]{return list.map(a=>({provider:text(a.provider),model:text(a.model),accountId:text(a.accountId),...counters(a),...(a.quota?{quota:{status:a.quota.status,remaining:count(a.quota.remaining),resetAt:text(a.quota.resetAt),reason:text(a.quota.reason)}}:{})}))}
|
||||
export const routerUsage={async snapshot(period:UsagePeriod='7d'):Promise<RouterUsageSnapshot>{
|
||||
const {data:raw}=await api.get('/admin/router-usage',{params:{period}});
|
||||
const data=raw?.success===true?raw.data:raw;
|
||||
if(data?.status==='unavailable')throw new Error('Usage unavailable: '+(data.reason??'unknown'));
|
||||
if(data?.status!=='available'||data.source!=='9router'||!usagePeriods.includes(data.period)||!data.freshness||!data.data||!Array.isArray(data.data.providers)||!Array.isArray(data.data.models)||!Array.isArray(data.data.accounts))throw new Error('Invalid usage snapshot contract');
|
||||
// Explicit allowlist; never forward raw gateway configuration or arbitrary response properties.
|
||||
return {source:data.source,period:data.period,freshness:{retrievedAt:text(data.freshness.retrievedAt),sourceUpdatedAt:text(data.freshness.sourceUpdatedAt),stale:typeof data.freshness.stale==='boolean'?data.freshness.stale:null},attribution:{scope:'9router_total',hermes:null,additive:false},data:{totals:counters(data.data.totals),providers:rows(data.data.providers),models:rows(data.data.models),accounts:rows(data.data.accounts)}};
|
||||
}};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import { defineConfig } from 'vitest/config'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// https://vite.dev/config/
|
||||
|
||||
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user