diff --git a/backend/prisma/migrations/20261028120000_corporate_orchestration/migration.sql b/backend/prisma/migrations/20261028120000_corporate_orchestration/migration.sql new file mode 100644 index 00000000..05493582 --- /dev/null +++ b/backend/prisma/migrations/20261028120000_corporate_orchestration/migration.sql @@ -0,0 +1,244 @@ +-- CreateEnum +CREATE TYPE "CorporateTaskStatus" AS ENUM ('TODO', 'IN_PROGRESS', 'TEST', 'DONE', 'BLOCKED', 'REJECTED', 'CANCELLED'); + +-- CreateEnum +CREATE TYPE "CorporatePriority" AS ENUM ('CEO_EXPEDITE', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW'); + +-- CreateTable +CREATE TABLE "corporate_tasks" ( + "id" UUID NOT NULL, + "taskCode" TEXT NOT NULL, + "title" TEXT NOT NULL, + "normalizedTitle" TEXT NOT NULL, + "normalizedCode" TEXT NOT NULL, + "description" TEXT NOT NULL, + "department" TEXT NOT NULL, + "priority" "CorporatePriority" NOT NULL DEFAULT 'CEO_EXPEDITE', + "status" "CorporateTaskStatus" NOT NULL DEFAULT 'TODO', + "actionType" TEXT NOT NULL DEFAULT 'CEO_DIRECTIVE', + "dueCycle" TEXT, + "parentId" UUID, + "goalId" UUID, + "assignedAgent" TEXT, + "claimToken" UUID, + "leasedUntil" TIMESTAMPTZ, + "executionCount" INTEGER NOT NULL DEFAULT 0, + "qaCount" INTEGER NOT NULL DEFAULT 0, + "rejectionCount" INTEGER NOT NULL DEFAULT 0, + "createdBy" TEXT NOT NULL, + "createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMPTZ NOT NULL, + + CONSTRAINT "corporate_tasks_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "corporate_events" ( + "id" UUID NOT NULL, + "taskId" UUID NOT NULL, + "speaker" TEXT NOT NULL, + "speakerName" TEXT NOT NULL, + "step" TEXT NOT NULL, + "content" TEXT NOT NULL, + "payload" JSONB, + "timestamp" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "corporate_events_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "corporate_evidence" ( + "id" UUID NOT NULL, + "taskId" UUID NOT NULL, + "claimToken" UUID NOT NULL, + "executor" TEXT NOT NULL, + "artifactUri" TEXT NOT NULL, + "sha256" TEXT NOT NULL, + "summary" TEXT NOT NULL, + "tool" TEXT NOT NULL, + "result" TEXT NOT NULL, + "createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "corporate_evidence_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "corporate_reviews" ( + "id" UUID NOT NULL, + "taskId" UUID NOT NULL, + "evidenceId" UUID NOT NULL, + "reviewer" TEXT NOT NULL, + "passed" BOOLEAN NOT NULL, + "findings" TEXT NOT NULL, + "verification" JSONB NOT NULL, + "createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "corporate_reviews_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "corporate_research" ( + "id" UUID NOT NULL, + "title" TEXT NOT NULL, + "category" TEXT NOT NULL, + "source" TEXT NOT NULL, + "opportunity" TEXT NOT NULL, + "impact" TEXT NOT NULL, + "recommendedAction" TEXT NOT NULL, + "status" TEXT NOT NULL DEFAULT 'DISCOVERED', + "cadence" TEXT NOT NULL, + "provenance" JSONB NOT NULL, + "createdBy" TEXT NOT NULL, + "createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "corporate_research_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "corporate_sources" ( + "id" UUID NOT NULL, + "researchId" UUID NOT NULL, + "url" TEXT NOT NULL, + "title" TEXT NOT NULL, + "excerpt" TEXT NOT NULL, + "retrievedAt" TIMESTAMPTZ NOT NULL, + "sha256" TEXT NOT NULL, + + CONSTRAINT "corporate_sources_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "corporate_roadmaps" ( + "id" UUID NOT NULL, + "researchId" UUID NOT NULL, + "cycleName" TEXT NOT NULL, + "month" TEXT NOT NULL, + "seasonalTheme" TEXT NOT NULL, + "strategicGoals" TEXT[], + "plannedArticlesCount" INTEGER NOT NULL, + "plannedRefreshesCount" INTEGER NOT NULL, + "plannedCatalogEnrichments" INTEGER NOT NULL, + "isActive" BOOLEAN NOT NULL DEFAULT false, + "createdBy" TEXT NOT NULL, + "createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "corporate_roadmaps_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "corporate_goals" ( + "id" UUID NOT NULL, + "roadmapId" UUID NOT NULL, + "title" TEXT NOT NULL, + "department" TEXT NOT NULL, + "acceptanceCriteria" TEXT NOT NULL, + "metric" TEXT NOT NULL, + "target" DOUBLE PRECISION, + "createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "corporate_goals_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "corporate_effects" ( + "id" UUID NOT NULL, + "taskId" UUID NOT NULL, + "metric" TEXT NOT NULL, + "availability" TEXT NOT NULL, + "baseline" DOUBLE PRECISION, + "observed" DOUBLE PRECISION, + "source" TEXT NOT NULL, + "observedAt" TIMESTAMPTZ NOT NULL, + "recordedBy" TEXT NOT NULL, + "createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "corporate_effects_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "corporate_reports" ( + "id" UUID NOT NULL, + "day" TEXT NOT NULL, + "summary" TEXT NOT NULL, + "snapshot" JSONB NOT NULL, + "createdBy" TEXT NOT NULL, + "createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "corporate_reports_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "corporate_operations" ( + "key" TEXT NOT NULL, + "payloadHash" TEXT NOT NULL, + "response" JSONB NOT NULL, + "createdAt" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "corporate_operations_pkey" PRIMARY KEY ("key") +); + +-- CreateIndex +CREATE UNIQUE INDEX "corporate_tasks_taskCode_key" ON "corporate_tasks"("taskCode"); + +-- CreateIndex +CREATE INDEX "corporate_tasks_status_priority_updatedAt_idx" ON "corporate_tasks"("status", "priority", "updatedAt"); + +-- CreateIndex +CREATE INDEX "corporate_tasks_parentId_idx" ON "corporate_tasks"("parentId"); + +-- CreateIndex +CREATE INDEX "corporate_tasks_goalId_idx" ON "corporate_tasks"("goalId"); + +-- CreateIndex +CREATE INDEX "corporate_events_taskId_timestamp_idx" ON "corporate_events"("taskId", "timestamp"); + +-- CreateIndex +CREATE INDEX "corporate_evidence_taskId_idx" ON "corporate_evidence"("taskId"); + +-- CreateIndex +CREATE INDEX "corporate_reviews_taskId_idx" ON "corporate_reviews"("taskId"); + +-- CreateIndex +CREATE INDEX "corporate_sources_researchId_idx" ON "corporate_sources"("researchId"); + +-- CreateIndex +CREATE INDEX "corporate_roadmaps_month_idx" ON "corporate_roadmaps"("month"); + +-- CreateIndex +CREATE INDEX "corporate_goals_roadmapId_idx" ON "corporate_goals"("roadmapId"); + +-- CreateIndex +CREATE INDEX "corporate_effects_taskId_idx" ON "corporate_effects"("taskId"); + +-- CreateIndex +CREATE UNIQUE INDEX "corporate_reports_day_key" ON "corporate_reports"("day"); + +-- AddForeignKey +ALTER TABLE "corporate_tasks" ADD CONSTRAINT "corporate_tasks_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "corporate_tasks"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "corporate_tasks" ADD CONSTRAINT "corporate_tasks_goalId_fkey" FOREIGN KEY ("goalId") REFERENCES "corporate_goals"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "corporate_events" ADD CONSTRAINT "corporate_events_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "corporate_evidence" ADD CONSTRAINT "corporate_evidence_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "corporate_reviews" ADD CONSTRAINT "corporate_reviews_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "corporate_reviews" ADD CONSTRAINT "corporate_reviews_evidenceId_fkey" FOREIGN KEY ("evidenceId") REFERENCES "corporate_evidence"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "corporate_sources" ADD CONSTRAINT "corporate_sources_researchId_fkey" FOREIGN KEY ("researchId") REFERENCES "corporate_research"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "corporate_roadmaps" ADD CONSTRAINT "corporate_roadmaps_researchId_fkey" FOREIGN KEY ("researchId") REFERENCES "corporate_research"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "corporate_goals" ADD CONSTRAINT "corporate_goals_roadmapId_fkey" FOREIGN KEY ("roadmapId") REFERENCES "corporate_roadmaps"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "corporate_effects" ADD CONSTRAINT "corporate_effects_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "corporate_tasks"("id") ON DELETE RESTRICT ON UPDATE CASCADE; \ No newline at end of file diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 094467b9..43765881 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -1,3 +1,202 @@ +enum CorporateTaskStatus { + TODO + IN_PROGRESS + TEST + DONE + BLOCKED + REJECTED + CANCELLED +} + +enum CorporatePriority { + CEO_EXPEDITE + CRITICAL + HIGH + MEDIUM + LOW +} + +model CorporateTask { + id String @id @default(uuid()) @db.Uuid + taskCode String @unique + title String + normalizedTitle String + normalizedCode String + description String + department String + priority CorporatePriority @default(CEO_EXPEDITE) + status CorporateTaskStatus @default(TODO) + actionType String @default("CEO_DIRECTIVE") + dueCycle String? + parentId String? @db.Uuid + parent CorporateTask? @relation("TaskChildren", fields: [parentId], references: [id]) + children CorporateTask[] @relation("TaskChildren") + goalId String? @db.Uuid + goal CorporateGoal? @relation(fields: [goalId], references: [id]) + assignedAgent String? + claimToken String? @db.Uuid + leasedUntil DateTime? @db.Timestamptz() + executionCount Int @default(0) + qaCount Int @default(0) + rejectionCount Int @default(0) + createdBy String + createdAt DateTime @default(now()) @db.Timestamptz() + updatedAt DateTime @updatedAt @db.Timestamptz() + logs CorporateEvent[] + evidence CorporateEvidence[] + reviews CorporateReview[] + effects CorporateEffect[] + @@index([status, priority, updatedAt]) + @@index([parentId]) + @@index([goalId]) + @@map("corporate_tasks") +} + +model CorporateEvent { + id String @id @default(uuid()) @db.Uuid + taskId String @db.Uuid + task CorporateTask @relation(fields: [taskId], references: [id]) + speaker String + speakerName String + step String + content String + payload Json? + timestamp DateTime @default(now()) @db.Timestamptz() + @@index([taskId, timestamp]) + @@map("corporate_events") +} + +model CorporateEvidence { + id String @id @default(uuid()) @db.Uuid + taskId String @db.Uuid + task CorporateTask @relation(fields: [taskId], references: [id]) + claimToken String @db.Uuid + executor String + artifactUri String + sha256 String + summary String + tool String + result String + createdAt DateTime @default(now()) @db.Timestamptz() + reviews CorporateReview[] + @@index([taskId]) + @@map("corporate_evidence") +} + +model CorporateReview { + id String @id @default(uuid()) @db.Uuid + taskId String @db.Uuid + task CorporateTask @relation(fields: [taskId], references: [id]) + evidenceId String @db.Uuid + evidence CorporateEvidence @relation(fields: [evidenceId], references: [id]) + reviewer String + passed Boolean + findings String + verification Json + createdAt DateTime @default(now()) @db.Timestamptz() + @@index([taskId]) + @@map("corporate_reviews") +} + +model CorporateResearch { + id String @id @default(uuid()) @db.Uuid + title String + category String + source String + opportunity String + impact String + recommendedAction String + status String @default("DISCOVERED") + cadence String + provenance Json + createdBy String + createdAt DateTime @default(now()) @db.Timestamptz() + sources CorporateSource[] + roadmaps CorporateRoadmap[] + @@map("corporate_research") +} + +model CorporateSource { + id String @id @default(uuid()) @db.Uuid + researchId String @db.Uuid + research CorporateResearch @relation(fields: [researchId], references: [id]) + url String + title String + excerpt String + retrievedAt DateTime @db.Timestamptz() + sha256 String + @@index([researchId]) + @@map("corporate_sources") +} + +model CorporateRoadmap { + id String @id @default(uuid()) @db.Uuid + researchId String @db.Uuid + research CorporateResearch @relation(fields: [researchId], references: [id]) + cycleName String + month String + seasonalTheme String + strategicGoals String[] + plannedArticlesCount Int + plannedRefreshesCount Int + plannedCatalogEnrichments Int + isActive Boolean @default(false) + createdBy String + createdAt DateTime @default(now()) @db.Timestamptz() + goals CorporateGoal[] + @@index([month]) + @@map("corporate_roadmaps") +} + +model CorporateGoal { + id String @id @default(uuid()) @db.Uuid + roadmapId String @db.Uuid + roadmap CorporateRoadmap @relation(fields: [roadmapId], references: [id]) + title String + department String + acceptanceCriteria String + metric String + target Float? + createdAt DateTime @default(now()) @db.Timestamptz() + tasks CorporateTask[] + @@index([roadmapId]) + @@map("corporate_goals") +} + +model CorporateEffect { + id String @id @default(uuid()) @db.Uuid + taskId String @db.Uuid + task CorporateTask @relation(fields: [taskId], references: [id]) + metric String + availability String + baseline Float? + observed Float? + source String + observedAt DateTime @db.Timestamptz() + recordedBy String + createdAt DateTime @default(now()) @db.Timestamptz() + @@index([taskId]) + @@map("corporate_effects") +} + +model CorporateReport { + id String @id @default(uuid()) @db.Uuid + day String @unique + summary String + snapshot Json + createdBy String + createdAt DateTime @default(now()) @db.Timestamptz() + @@map("corporate_reports") +} + +model CorporateOperation { + key String @id + payloadHash String + response Json + createdAt DateTime @default(now()) @db.Timestamptz() + @@map("corporate_operations") +} + generator client { provider = "prisma-client-js" binaryTargets = ["native", "linux-musl-openssl-3.0.x"] diff --git a/backend/src/admin/admin.module.ts b/backend/src/admin/admin.module.ts index 6a722c5f..abc86ef6 100644 --- a/backend/src/admin/admin.module.ts +++ b/backend/src/admin/admin.module.ts @@ -1,3 +1,5 @@ +import { CorporateController } from "./hermes/corporate.controller"; +import { CorporateService } from "./hermes/corporate.service"; import { Module } from "@nestjs/common"; import { AdminController } from "./admin.controller"; import { AdminService } from "./admin.service"; @@ -30,6 +32,7 @@ import { SupportChatAnalyticsService } from "./support-chat-analytics.service"; @Module({ imports: [PrismaModule, RedisModule, SettingsModule], controllers: [ + CorporateController, AdminController, ReportsController, MediaController, @@ -46,6 +49,7 @@ import { SupportChatAnalyticsService } from "./support-chat-analytics.service"; SupportChatAnalyticsController, ], providers: [ + CorporateService, AdminService, ReportsService, MediaService, diff --git a/backend/src/admin/hermes/corporate-policy.spec.ts b/backend/src/admin/hermes/corporate-policy.spec.ts new file mode 100644 index 00000000..fa7bd23e --- /dev/null +++ b/backend/src/admin/hermes/corporate-policy.spec.ts @@ -0,0 +1,32 @@ +import { normalizeSearch, pagination, taskInput } from './corporate-policy'; +describe('corporate contract policy', () => { + it('normalizes Persian letters, digits and separators', () => { + expect(normalizeSearch('كيك ۱۲۳ (ة)‌')).toBe('کیک 123 ه'); + }); + it('bounds pagination and sort keys', () => { + expect(pagination({ limit: '100' }).limit).toBe(100); + expect(() => pagination({ limit: '101' })).toThrow(); + expect(() => pagination({ page: '-1' })).toThrow(); + expect(() => pagination({ sortBy: 'password' })).toThrow(); + }); + it('defaults CEO priority and rejects status/command injection', () => { + expect( + taskInput({ + title: 'عنوان', + description: 'کار', + department: 'CONTENT_SEO', + }).priority, + ).toBe('CEO_EXPEDITE'); + expect(() => + taskInput({ + title: 'x', + description: 'x', + department: 'CONTENT_SEO', + status: 'DONE', + }), + ).toThrow(); + expect(() => + taskInput({ title: '', description: 'x', department: 'CONTENT_SEO' }), + ).toThrow(); + }); +}); diff --git a/backend/src/admin/hermes/corporate-policy.ts b/backend/src/admin/hermes/corporate-policy.ts new file mode 100644 index 00000000..08fb08c0 --- /dev/null +++ b/backend/src/admin/hermes/corporate-policy.ts @@ -0,0 +1,174 @@ +import { BadRequestException } from '@nestjs/common'; +export const departments = [ + 'CONTENT_SEO', + 'CATALOG_COMMERCE', + 'WIKI_SCIENTIFIC', + 'TECH_DEVOPS', + 'MARKET_INTELLIGENCE', +]; +export const priorities = ['CEO_EXPEDITE', 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW']; +export const statuses = [ + 'TODO', + 'IN_PROGRESS', + 'TEST', + 'DONE', + 'BLOCKED', + 'REJECTED', + 'CANCELLED', +]; +export function object(value: unknown, keys: string[]): Record { + if ( + !value || + typeof value !== 'object' || + Array.isArray(value) || + Object.keys(value).some((k) => !keys.includes(k)) + ) + throw new BadRequestException('Invalid fields'); + return value as Record; +} +export function text(value: unknown, max = 10000): string { + if (typeof value !== 'string' || !value.trim() || value.length > max) + throw new BadRequestException('Invalid text'); + return value.trim(); +} +export function uuid(value: unknown): string { + const id = text(value, 36); + if ( + !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test( + id, + ) + ) + throw new BadRequestException('Invalid UUID'); + return id; +} +export function choice(value: unknown, values: string[]): string { + if (typeof value !== 'string' || !values.includes(value)) + throw new BadRequestException('Invalid enum'); + return value; +} +export function normalizeSearch(value: string): string { + return value + .normalize('NFKC') + .toLowerCase() + .replace(/[يى]/g, 'ی') + .replace(/ك/g, 'ک') + .replace(/ة/g, 'ه') + .replace(/[۰-۹٠-٩]/g, (c) => + String( + '۰۱۲۳۴۵۶۷۸۹'.includes(c) + ? '۰۱۲۳۴۵۶۷۸۹'.indexOf(c) + : '٠١٢٣٤٥٦٧٨٩'.indexOf(c), + ), + ) + .replace(/[\u200c\u200d()()]/g, ' ') + .replace(/[\u064b-\u065f]/g, '') + .replace(/\s+/g, ' ') + .trim(); +} +export function pagination(q: Record) { + const page = Number(q.page ?? 1), + limit = Number(q.limit ?? 20); + if ( + !Number.isSafeInteger(page) || + page < 1 || + page > 1000000 || + !Number.isInteger(limit) || + limit < 1 || + limit > 100 + ) + throw new BadRequestException('Invalid pagination'); + const sortBy = choice(q.sortBy ?? 'createdAt', [ + 'createdAt', + 'updatedAt', + 'title', + 'taskCode', + 'priority', + 'status', + ]); + const sortOrder = choice(q.sortOrder ?? 'desc', ['asc', 'desc']) as + | 'asc' + | 'desc'; + return { page, limit, skip: (page - 1) * limit, sortBy, sortOrder }; +} +export function meta(total: number, page: number, limit: number) { + const totalPages = Math.ceil(total / limit); + return { + total, + page, + limit, + totalPages, + hasNextPage: page < totalPages, + hasPrevPage: page > 1, + }; +} +export function taskInput(input: unknown) { + const b = object(input, [ + 'title', + 'department', + 'description', + 'priority', + 'parentId', + 'goalId', + 'actionType', + 'dueCycle', + ]); + return { + title: text(b.title, 300), + description: text(b.description), + department: choice(b.department, departments), + priority: choice(b.priority ?? 'CEO_EXPEDITE', priorities), + parentId: b.parentId === undefined ? undefined : uuid(b.parentId), + goalId: b.goalId === undefined ? undefined : uuid(b.goalId), + actionType: choice(b.actionType ?? 'CEO_DIRECTIVE', [ + 'CEO_DIRECTIVE', + 'BLOG_NEW', + 'BLOG_UPDATE', + 'CATALOG_ENRICH', + 'RESEARCH', + 'ENGINEERING', + ]), + dueCycle: b.dueCycle === undefined ? undefined : text(b.dueCycle, 40), + }; +} +export function canonical(value: any): string { + if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']'; + if (value && typeof value === 'object') + return ( + '{' + + Object.keys(value) + .sort() + .map((k) => JSON.stringify(k) + ':' + canonical(value[k])) + .join(',') + + '}' + ); + return JSON.stringify(value); +} +export function evidenceInput(input: unknown) { + const b = object(input, [ + 'claimToken', + 'artifactUri', + 'sha256', + 'summary', + 'tool', + 'result', + ]); + const uri = text(b.artifactUri, 2000); + if ( + !/^(https:\/\/|urn:sha256:)/.test(uri) || + /example\.(com|org)|localhost|127\.0\.0\.1/.test(uri) + ) + throw new BadRequestException( + 'Evidence locator must be a real HTTPS artifact or content digest', + ); + const sha = text(b.sha256, 64); + if (!/^[a-f0-9]{64}$/.test(sha)) + throw new BadRequestException('Invalid digest'); + return { + claimToken: uuid(b.claimToken), + artifactUri: uri, + sha256: sha, + summary: text(b.summary), + tool: text(b.tool, 100), + result: text(b.result), + }; +} diff --git a/backend/src/admin/hermes/corporate.controller.ts b/backend/src/admin/hermes/corporate.controller.ts new file mode 100644 index 00000000..701d27be --- /dev/null +++ b/backend/src/admin/hermes/corporate.controller.ts @@ -0,0 +1,121 @@ +import { + Body, + Controller, + Get, + Headers, + Param, + Post, + Query, + Req, + UnauthorizedException, + UseGuards, +} from '@nestjs/common'; +import { JwtAuthGuard } from '../../auth/jwt-auth.guard'; +import { RolesGuard } from '../../common/guards/roles.guard'; +import { Roles } from '../../common/decorators/roles.decorator'; +import { CorporateService } from './corporate.service'; +import { randomUUID } from 'crypto'; +import { text } from './corporate-policy'; + +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('Admin', 'SUPER_ADMIN') +@Controller('admin/hermes') +export class CorporateController { + constructor(private readonly service: CorporateService) {} + private actor(req: any) { + // API keys must use their authenticated key identity, not an editable worker label. + const user = req.user; + const id = user?.id ?? user?.sub; + if (!id) throw new UnauthorizedException('Authenticated subject required'); + return (user.isApiKey ? 'apikey:' : 'user:') + text(String(id), 200); + } + private key(key?: string) { + return text(key, 200); + } + @Get('runtime') runtime() { + return { + mode: 'MANUAL_DORMANT', + schedulesEnabled: false, + externalExecutionEnabled: false, + }; + } + @Get('tasks') tasks(@Query() query: Record) { + return this.service.tasks(query); + } + @Get('tasks/:id') detail(@Param('id') id: string) { + return this.service.detail(id); + } + @Post('tasks') create( + @Req() req: any, + @Headers('idempotency-key') key: string, + @Body() body: unknown, + ) { + return this.service.create(this.actor(req), key ?? randomUUID(), body); + } + @Post('claims') claim( + @Req() req: any, + @Headers('idempotency-key') key: string, + @Body() body: unknown, + ) { + return this.service.claim(this.actor(req), this.key(key), body); + } + @Post('tasks/:id/evidence') evidence( + @Req() req: any, + @Headers('idempotency-key') key: string, + @Param('id') id: string, + @Body() body: unknown, + ) { + return this.service.submitEvidence( + this.actor(req), + this.key(key), + id, + body, + ); + } + @Post('tasks/:id/reviews') review( + @Req() req: any, + @Headers('idempotency-key') key: string, + @Param('id') id: string, + @Body() body: unknown, + ) { + return this.service.review(this.actor(req), this.key(key), id, body); + } + @Post('tasks/:id/effects') effect( + @Req() req: any, + @Headers('idempotency-key') key: string, + @Param('id') id: string, + @Body() body: unknown, + ) { + return this.service.effect(this.actor(req), this.key(key), id, body); + } + @Get('market-insights') insights(@Query() q: Record) { + return this.service.collection('market-insights', q); + } + @Post('market-insights') research( + @Req() req: any, + @Headers('idempotency-key') key: string, + @Body() body: unknown, + ) { + return this.service.research(this.actor(req), this.key(key), body); + } + @Get('monthly-roadmap') roadmaps(@Query() q: Record) { + return this.service.collection('monthly-roadmap', q); + } + @Post('monthly-roadmap') roadmap( + @Req() req: any, + @Headers('idempotency-key') key: string, + @Body() body: unknown, + ) { + return this.service.roadmap(this.actor(req), this.key(key), body); + } + @Get('reports') reports(@Query() q: Record) { + return this.service.collection('reports', q); + } + @Post('reports') report( + @Req() req: any, + @Headers('idempotency-key') key: string, + @Body() body: unknown, + ) { + return this.service.report(this.actor(req), this.key(key), body); + } +} diff --git a/backend/src/admin/hermes/corporate.integration.spec.ts b/backend/src/admin/hermes/corporate.integration.spec.ts new file mode 100644 index 00000000..545043cd --- /dev/null +++ b/backend/src/admin/hermes/corporate.integration.spec.ts @@ -0,0 +1,303 @@ +import passport from 'passport'; +import { Strategy, ExtractJwt } from 'passport-jwt'; +import { PrismaClient } from '@prisma/client'; +import { Test } from '@nestjs/testing'; +import { INestApplication } from '@nestjs/common'; +import { randomUUID } from 'crypto'; +import request from 'supertest'; +import { PrismaService } from '../../prisma/prisma.service'; +import { CorporateController } from './corporate.controller'; +import { CorporateService } from './corporate.service'; +import { ApiKeysService } from '../api-keys.service'; + +const integration = process.env.CORPORATE_TEST_DATABASE_URL + ? describe + : describe.skip; +integration('corporate API / disposable PostgreSQL', () => { + let app: INestApplication, db: PrismaService; + const key = () => randomUUID(); + const post = (path: string, body: any, actor = 'executor', op = key()) => + request(app.getHttpServer()) + .post('/admin/hermes/' + path) + .set('x-api-key', actor) + .set('Idempotency-Key', op) + .send(body); + const input = { + title: 'كيك ۱۲۳', + description: 'integration fixture', + department: 'CONTENT_SEO', + }; + beforeAll(async () => { + // Explicit disposable loopback opt-in only; never consumes runtime DATABASE_URL. + const url = new URL(process.env.CORPORATE_TEST_DATABASE_URL!); + if (url.hostname !== '127.0.0.1' || url.pathname !== '/corporate_test') + throw new Error('Disposable loopback corporate_test DB required'); + passport.use( + 'jwt', + new Strategy( + { + jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), + secretOrKey: 'test-only-not-runtime', + }, + (_payload, done) => done(null, false), + ), + ); + db = new PrismaClient({ + datasources: { db: { url: process.env.CORPORATE_TEST_DATABASE_URL } }, + }) as PrismaService; + const module = await Test.createTestingModule({ + controllers: [CorporateController], + providers: [ + CorporateService, + { provide: PrismaService, useValue: db }, + { + provide: ApiKeysService, + useValue: { + validateKey: async (id: string) => ({ + id, + isApiKey: true, + role: 'Admin', + scopes: id === 'unscoped' ? [] : ['admin'], + }), + }, + }, + ], + }).compile(); + app = module.createNestApplication(); + await app.listen(0, '127.0.0.1'); + }); + afterAll(async () => { + if (db) + await db.$executeRawUnsafe( + 'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE', + ); + await app?.close(); + await db?.$disconnect(); + passport.unuse('jwt'); + }); + beforeEach(async () => { + await db.$executeRawUnsafe( + 'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE', + ); + }); + it('auth, UI list contract, normalized search, immutable idempotent replay', async () => { + await request(app.getHttpServer()).get('/admin/hermes/tasks').expect(401); + await post('tasks', input, 'unscoped').expect(403); + const op = key(), + a = await post('tasks', input, 'executor', op).expect(201); + const b = await post('tasks', input, 'executor', op).expect(201); + expect(b.body.id).toBe(a.body.id); + await post('tasks', { ...input, title: 'changed' }, 'executor', op).expect( + 409, + ); + const list = await request(app.getHttpServer()) + .get('/admin/hermes/tasks?search=کیک%20123&limit=1') + .set('x-api-key', 'executor') + .expect(200); + expect(list.body.meta).toEqual({ + total: 1, + page: 1, + limit: 1, + totalPages: 1, + hasNextPage: false, + hasPrevPage: false, + }); + expect(list.body.data[0].priority).toBe('CEO_EXPEDITE'); + await request(app.getHttpServer()) + .get('/admin/hermes/tasks?limit=101') + .set('x-api-key', 'executor') + .expect(400); + await request(app.getHttpServer()) + .get('/admin/hermes/tasks?sortBy=password') + .set('x-api-key', 'executor') + .expect(400); + }); + it('claims exclusively, expires/reclaims, fences stale executor, requires independent QA', async () => { + const task = (await post('tasks', input).expect(201)).body; + const claims = await Promise.all([ + post('claims', {}, 'executor'), + post('claims', {}, 'competitor'), + ]); + expect(claims.filter((x) => x.body.task !== null)).toHaveLength(1); + const claimed = claims.find((x) => x.body.task !== null)!.body.task; + const oldActor = claimed.assignedAgent.replace('apikey:', ''); + await db.$executeRaw`UPDATE corporate_tasks SET "leasedUntil"=clock_timestamp()-interval '1 second' WHERE id=${task.id}::uuid`; + const renewed = (await post('claims', {}, 'new-executor').expect(201)).body + .task; + expect(renewed.claimToken).not.toBe(claimed.claimToken); + const evidence = { + claimToken: claimed.claimToken, + artifactUri: 'urn:sha256:' + 'a'.repeat(64), + sha256: 'a'.repeat(64), + summary: 'receipt', + tool: 'jest', + result: 'passed', + }; + await post(`tasks/${task.id}/evidence`, evidence, oldActor).expect(409); + const e = ( + await post( + `tasks/${task.id}/evidence`, + { ...evidence, claimToken: renewed.claimToken }, + 'new-executor', + ).expect(201) + ).body; + const review = { + evidenceId: e.id, + passed: true, + findings: 'verified', + verification: { + artifactUri: e.artifactUri, + sha256: e.sha256, + method: 'digest readback', + result: 'match', + }, + }; + await post(`tasks/${task.id}/reviews`, review, 'new-executor').expect(409); + await post(`tasks/${task.id}/reviews`, review, 'reviewer').expect(201); + const detail = await request(app.getHttpServer()) + .get('/admin/hermes/tasks/' + task.id) + .set('x-api-key', 'reviewer') + .expect(200); + expect(detail.body.status).toBe('DONE'); + expect(detail.body.logs.map((x: any) => x.step)).toContain('QA_PASSED'); + await post(`tasks/${task.id}/effects`, { + metric: 'engagement', + availability: 'UNAVAILABLE', + observed: 0, + source: 'provider unavailable', + observedAt: new Date().toISOString(), + }).expect(400); + }); + it('skips a held row lock and gives CEO priority before lower priorities', async () => { + const urgent = (await post('tasks', input).expect(201)).body; + const low = (await post('tasks', { ...input, priority: 'LOW' }).expect(201)) + .body; + let release!: () => void, locked!: () => void; + const ready = new Promise((r) => (locked = r)), + hold = new Promise((r) => (release = r)); + const locking = db.$transaction(async (tx) => { + await tx.$queryRaw`SELECT id FROM corporate_tasks WHERE id=${urgent.id}::uuid FOR UPDATE`; + locked(); + await hold; + }); + await ready; + try { + const claim = (await post('claims', {}).expect(201)).body.task; + expect(claim.id).toBe(low.id); + } finally { + release(); + await locking; + } + const next = (await post('claims', {}, 'other').expect(201)).body.task; + expect(next.id).toBe(urgent.id); + }); + it('serializes simultaneous duplicate mutations into one durable record', async () => { + const op = key(); + const responses = await Promise.all([ + post('tasks', input, 'executor', op), + post('tasks', input, 'executor', op), + ]); + expect(responses.map((r) => r.status)).toEqual([201, 201]); + expect(responses[0].body.id).toBe(responses[1].body.id); + expect(await db.corporateTask.count()).toBe(1); + }); + it('gates parents on children, persists provenance, roadmap/goals and reports', async () => { + const parent = (await post('tasks', input).expect(201)).body; + const child = ( + await post('tasks', { ...input, parentId: parent.id }).expect(201) + ).body; + const claim = (await post('claims', {}).expect(201)).body.task; + expect(claim.id).toBe(child.id); + const e = ( + await post(`tasks/${child.id}/evidence`, { + claimToken: claim.claimToken, + artifactUri: 'urn:sha256:' + 'b'.repeat(64), + sha256: 'b'.repeat(64), + summary: 'child artifact', + tool: 'jest', + result: 'receipt', + }).expect(201) + ).body; + await post( + `tasks/${child.id}/reviews`, + { + evidenceId: e.id, + passed: false, + findings: 'needs correction', + verification: { + artifactUri: e.artifactUri, + sha256: e.sha256, + method: 'readback', + result: 'failed', + }, + }, + 'reviewer', + ).expect(201); + expect( + (await db.corporateTask.findUniqueOrThrow({ where: { id: parent.id } })) + .status, + ).toBe('BLOCKED'); + expect((await post('claims', {}).expect(201)).body.task.id).toBe(child.id); + const research = ( + await post('market-insights', { + title: 'fixture research', + category: 'TREND', + source: 'study receipt', + opportunity: 'investigate', + impact: 'LOW', + recommendedAction: 'measure', + cadence: 'MONTHLY', + provenance: { + method: 'test fixture', + collector: 'integration', + context: 'disposable', + }, + sources: [ + { + url: 'https://pubmed.ncbi.nlm.nih.gov/', + title: 'fixture', + excerpt: 'test-only', + retrievedAt: '2026-01-01T00:00:00Z', + sha256: 'a'.repeat(64), + }, + ], + }).expect(201) + ).body; + const roadmap = ( + await post('monthly-roadmap', { + researchId: research.id, + cycleName: 'test', + month: '2026-10', + seasonalTheme: 'evidence pending seasonal analysis', + strategicGoals: ['measure'], + plannedArticlesCount: 31, + plannedRefreshesCount: 0, + plannedCatalogEnrichments: 0, + goals: [ + { + title: 'goal', + department: 'CONTENT_SEO', + acceptanceCriteria: 'QA', + metric: 'engagement', + }, + ], + }).expect(201) + ).body; + expect(roadmap.goals).toHaveLength(1); + await post('tasks', { ...input, goalId: roadmap.goals[0].id }).expect(201); + for (const path of ['market-insights', 'monthly-roadmap']) { + const r = await request(app.getHttpServer()) + .get('/admin/hermes/' + path) + .set('x-api-key', 'executor') + .expect(200); + expect(r.body.meta.total).toBe(1); + } + const report = ( + await post('reports', { + day: new Date().toISOString().slice(0, 10), + summary: 'test fixture daily report', + }).expect(201) + ).body; + expect(report.snapshot.tasks).toHaveLength(3); + }); +}); diff --git a/backend/src/admin/hermes/corporate.service.ts b/backend/src/admin/hermes/corporate.service.ts new file mode 100644 index 00000000..3579bbb0 --- /dev/null +++ b/backend/src/admin/hermes/corporate.service.ts @@ -0,0 +1,600 @@ +import { + Injectable, + BadRequestException, + ConflictException, + NotFoundException, +} from '@nestjs/common'; +import { Prisma, CorporatePriority } from '@prisma/client'; +import { createHash, randomUUID } from 'crypto'; +import { PrismaService } from '../../prisma/prisma.service'; +import { + canonical, + choice, + departments, + evidenceInput, + meta, + normalizeSearch, + object, + pagination, + priorities, + statuses, + taskInput, + text, + uuid, +} from './corporate-policy'; +type Tx = Prisma.TransactionClient; +@Injectable() +export class CorporateService { + constructor(private readonly db: PrismaService) {} + private async operation( + actor: string, + op: string, + key: string, + body: unknown, + fn: (tx: Tx) => Promise, + ) { + text(key, 200); + const scoped = createHash('sha256') + .update(canonical([actor, op, key])) + .digest('hex'); + const hash = createHash('sha256').update(canonical(body)).digest('hex'); + return this.db.$transaction( + async (tx) => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scoped}, 0))`; + const prior = await tx.corporateOperation.findUnique({ + where: { key: scoped }, + }); + if (prior) { + if (prior.payloadHash !== hash) + throw new ConflictException('Idempotency key payload mismatch'); + return prior.response; + } + const result = await fn(tx); + const response = JSON.parse(JSON.stringify(result)); + await tx.corporateOperation.create({ + data: { key: scoped, payloadHash: hash, response }, + }); + return response; + }, + { maxWait: 10000, timeout: 20000 }, + ); + } + private event( + tx: Tx, + taskId: string, + actor: string, + step: string, + content: string, + speaker = 'SYSTEM', + payload?: any, + ) { + return tx.corporateEvent.create({ + data: { taskId, speaker, speakerName: actor, step, content, payload }, + }); + } + private async lock(tx: Tx, id: string) { + uuid(id); + const rows = await tx.$queryRaw< + { id: string }[] + >`SELECT id FROM corporate_tasks WHERE id=${id}::uuid FOR UPDATE`; + if (!rows.length) throw new NotFoundException('Task not found'); + return tx.corporateTask.findUniqueOrThrow({ where: { id } }); + } + private async fenced(tx: Tx, id: string, token: string, actor: string) { + const t = await this.lock(tx, id); + const rows = await tx.$queryRaw< + { id: string }[] + >`SELECT id FROM corporate_tasks WHERE id=${id}::uuid AND "claimToken"=${token}::uuid AND "assignedAgent"=${actor} AND "leasedUntil">clock_timestamp() AND status='IN_PROGRESS'`; + if (!rows.length) throw new ConflictException('Stale lease or owner'); + return t; + } + async tasks(q: Record) { + const p = pagination(q), + where: Prisma.CorporateTaskWhereInput = {}; + if (q.department) where.department = choice(q.department, departments); + if (q.priority) + where.priority = choice(q.priority, priorities) as CorporatePriority; + if (q.status) where.status = choice(q.status, statuses) as any; + if (q.search) { + const search = normalizeSearch(text(q.search, 300)); + where.OR = [ + { normalizedTitle: { contains: search } }, + { normalizedCode: { contains: search } }, + ]; + } + if (q.goalId) where.goalId = uuid(q.goalId); + return this.db.$transaction( + async (tx) => { + const total = await tx.corporateTask.count({ where }); + const data = await tx.corporateTask.findMany({ + where, + skip: p.skip, + take: p.limit, + orderBy: [{ [p.sortBy]: p.sortOrder }, { id: 'asc' }], + }); + return { data, meta: meta(total, p.page, p.limit) }; + }, + { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead }, + ); + } + async detail(id: string) { + uuid(id); + const task = await this.db.corporateTask.findUnique({ + where: { id }, + include: { + logs: { orderBy: { timestamp: 'asc' } }, + evidence: true, + reviews: true, + effects: true, + children: true, + }, + }); + if (!task) throw new NotFoundException('Task not found'); + return task; + } + create(actor: string, key: string, input: unknown) { + const b = taskInput(input); + return this.operation(actor, 'create-task', key, b, async (tx) => { + if (b.parentId) { + const parent = await this.lock(tx, b.parentId); + if (!['TODO', 'IN_PROGRESS', 'BLOCKED'].includes(parent.status)) + throw new ConflictException('Parent no longer accepts children'); + } + const code = 'TSK-' + randomUUID(); + const task = await tx.corporateTask.create({ + data: { + ...b, + priority: b.priority as CorporatePriority, + taskCode: code, + normalizedCode: normalizeSearch(code), + normalizedTitle: normalizeSearch(b.title), + createdBy: actor, + }, + }); + await this.event(tx, task.id, actor, 'CREATED', b.description, 'CEO'); + return task; + }); + } + claim(actor: string, key: string, input: unknown) { + const b = object(input, ['department', 'leaseSeconds']); + const department = + b.department === undefined ? null : choice(b.department, departments); + const seconds = Number(b.leaseSeconds ?? 300); + if (!Number.isInteger(seconds) || seconds < 30 || seconds > 900) + throw new BadRequestException('Lease must be 30..900 seconds'); + return this.operation( + actor, + 'claim', + key, + { department, seconds }, + async (tx) => { + const candidates = await tx.$queryRaw< + { id: string }[] + >`SELECT t.id FROM corporate_tasks t + WHERE (t.status='TODO' OR (t.status='BLOCKED' AND EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id)) OR (t.status='IN_PROGRESS' AND t."leasedUntil"<=clock_timestamp())) + AND (${department}::text IS NULL OR t.department=${department}) + AND NOT EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id AND c.status<>'DONE') + ORDER BY t.priority ASC,t."updatedAt" ASC,t.id ASC FOR UPDATE OF t SKIP LOCKED LIMIT 1`; + if (!candidates.length) return { task: null }; + const id = candidates[0].id, + token = randomUUID(); + await tx.$executeRaw`UPDATE corporate_tasks SET status='IN_PROGRESS', "assignedAgent"=${actor}, "claimToken"=${token}::uuid, "leasedUntil"=clock_timestamp()+make_interval(secs=>${seconds}::int), "executionCount"="executionCount"+1,"updatedAt"=clock_timestamp() WHERE id=${id}::uuid`; + await this.event(tx, id, actor, 'CLAIMED', 'Manual lease acquired'); + return { + task: await tx.corporateTask.findUniqueOrThrow({ where: { id } }), + }; + }, + ); + } + submitEvidence(actor: string, key: string, id: string, input: unknown) { + const b = evidenceInput(input); + return this.operation(actor, 'evidence:' + id, key, b, async (tx) => { + await this.fenced(tx, id, b.claimToken, actor); + const e = await tx.corporateEvidence.create({ + data: { ...b, taskId: id, executor: actor }, + }); + await tx.corporateTask.update({ + where: { id }, + data: { status: 'TEST', leasedUntil: null }, + }); + await this.event( + tx, + id, + actor, + 'EVIDENCE_SUBMITTED', + b.summary, + 'AGENT', + { evidenceId: e.id }, + ); + return e; + }); + } + review(actor: string, key: string, id: string, input: unknown) { + const b = object(input, [ + 'evidenceId', + 'passed', + 'findings', + 'verification', + ]); + const evidenceId = uuid(b.evidenceId), + findings = text(b.findings); + if (typeof b.passed !== 'boolean') + throw new BadRequestException('passed must be boolean'); + const v = object(b.verification, [ + 'artifactUri', + 'sha256', + 'method', + 'result', + ]); + const verification = { + artifactUri: text(v.artifactUri, 2000), + sha256: text(v.sha256, 64), + method: text(v.method, 1000), + result: text(v.result), + }; + return this.operation(actor, 'review:' + id, key, b, async (tx) => { + uuid(id); + const relation = await tx.corporateTask.findUnique({ + where: { id }, + select: { parentId: true }, + }); + if (relation?.parentId) await this.lock(tx, relation.parentId); + const task = await this.lock(tx, id); + const evidence = await tx.corporateEvidence.findUnique({ + where: { id: evidenceId }, + }); + if ( + task.status !== 'TEST' || + !evidence || + evidence.taskId !== id || + evidence.claimToken !== task.claimToken + ) + throw new ConflictException('Current execution evidence required'); + if (evidence.executor === actor) + throw new ConflictException('Independent reviewer required'); + if ( + verification.sha256 !== evidence.sha256 || + verification.artifactUri !== evidence.artifactUri + ) + throw new ConflictException('QA must verify exact artifact'); + if ( + b.passed && + (await tx.corporateTask.count({ + where: { parentId: id, status: { not: 'DONE' } }, + })) + ) + throw new ConflictException('Unfinished children'); + const r = await tx.corporateReview.create({ + data: { + taskId: id, + evidenceId, + reviewer: actor, + passed: b.passed, + findings, + verification, + }, + }); + await tx.corporateTask.update({ + where: { id }, + data: { + status: b.passed ? 'DONE' : 'TODO', + claimToken: null, + leasedUntil: null, + qaCount: { increment: 1 }, + rejectionCount: { increment: b.passed ? 0 : 1 }, + }, + }); + if (!b.passed && task.parentId) { + await tx.corporateTask.update({ + where: { id: task.parentId }, + data: { status: 'BLOCKED' }, + }); + await this.event( + tx, + task.parentId, + actor, + 'CHILD_QA_REJECTED', + 'Parent blocked pending child correction', + 'QA', + { childId: id }, + ); + } + await this.event( + tx, + id, + actor, + b.passed ? 'QA_PASSED' : 'QA_REJECTED', + findings, + 'QA', + { reviewId: r.id }, + ); + return r; + }); + } + async collection( + kind: 'market-insights' | 'monthly-roadmap' | 'reports', + q: Record, + ) { + const p = pagination(q); + return this.db.$transaction( + async (tx) => { + const model = + kind === 'market-insights' + ? tx.corporateResearch + : kind === 'monthly-roadmap' + ? tx.corporateRoadmap + : tx.corporateReport; + const where: any = {}; + if (kind === 'market-insights' && q.category) + where.category = choice(q.category, [ + 'TREND', + 'COMPETITOR', + 'NEW_CHANNEL', + 'CATALOG_GAP', + ]); + if (kind === 'monthly-roadmap' && q.month) + where.month = text(q.month, 40); + const delegate = model as any; + const total = await delegate.count({ where }); + const data = await delegate.findMany({ + where, + skip: p.skip, + take: p.limit, + orderBy: [{ createdAt: 'desc' }, { id: 'asc' }], + ...(kind === 'market-insights' + ? { include: { sources: true } } + : kind === 'monthly-roadmap' + ? { include: { goals: true } } + : {}), + }); + return { data, meta: meta(total, p.page, p.limit) }; + }, + { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead }, + ); + } + research(actor: string, key: string, input: unknown) { + const b = object(input, [ + 'title', + 'category', + 'source', + 'opportunity', + 'impact', + 'recommendedAction', + 'cadence', + 'provenance', + 'sources', + ]); + if (!Array.isArray(b.sources) || !b.sources.length || b.sources.length > 30) + throw new BadRequestException('1..30 sources required'); + const sources = b.sources.map((raw) => { + const s = object(raw, [ + 'url', + 'title', + 'excerpt', + 'retrievedAt', + 'sha256', + ]); + const url = text(s.url, 2000), + sha256 = text(s.sha256, 64), + retrievedAt = new Date(s.retrievedAt); + if ( + !url.startsWith('https://') || + !/^[a-f0-9]{64}$/.test(sha256) || + !Number.isFinite(retrievedAt.getTime()) || + retrievedAt.getTime() > Date.now() + ) + throw new BadRequestException('Invalid source'); + return { + url, + sha256, + retrievedAt, + title: text(s.title, 300), + excerpt: text(s.excerpt), + }; + }); + const provenance = object(b.provenance, ['method', 'collector', 'context']); + const data = { + title: text(b.title, 300), + category: choice(b.category, [ + 'TREND', + 'COMPETITOR', + 'NEW_CHANNEL', + 'CATALOG_GAP', + ]), + source: text(b.source, 2000), + opportunity: text(b.opportunity), + impact: choice(b.impact, ['HIGH', 'MEDIUM', 'LOW']), + recommendedAction: text(b.recommendedAction), + cadence: choice(b.cadence, ['MONTHLY', 'EVENT']), + provenance: { + method: text(provenance.method), + collector: text(provenance.collector, 300), + context: text(provenance.context), + }, + createdBy: actor, + }; + return this.operation(actor, 'research', key, b, (tx) => + tx.corporateResearch.create({ + data: { ...data, sources: { create: sources } }, + include: { sources: true }, + }), + ); + } + roadmap(actor: string, key: string, input: unknown) { + const b = object(input, [ + 'researchId', + 'cycleName', + 'month', + 'seasonalTheme', + 'strategicGoals', + 'plannedArticlesCount', + 'plannedRefreshesCount', + 'plannedCatalogEnrichments', + 'isActive', + 'goals', + ]); + if ( + !Array.isArray(b.strategicGoals) || + !b.strategicGoals.length || + b.strategicGoals.length > 30 || + !Array.isArray(b.goals) || + !b.goals.length || + b.goals.length > 100 + ) + throw new BadRequestException('Goals required'); + for (const k of [ + 'plannedArticlesCount', + 'plannedRefreshesCount', + 'plannedCatalogEnrichments', + ]) + if (!Number.isInteger(b[k]) || b[k] < 0 || b[k] > 10000) + throw new BadRequestException('Invalid counts'); + if (b.isActive !== undefined && typeof b.isActive !== 'boolean') + throw new BadRequestException('Invalid active flag'); + const goals = b.goals.map((raw) => { + const g = object(raw, [ + 'title', + 'department', + 'acceptanceCriteria', + 'metric', + 'target', + ]); + if ( + g.target !== undefined && + (typeof g.target !== 'number' || !Number.isFinite(g.target)) + ) + throw new BadRequestException('Invalid target'); + return { + title: text(g.title, 300), + department: choice(g.department, departments), + acceptanceCriteria: text(g.acceptanceCriteria), + metric: text(g.metric, 300), + target: g.target, + }; + }); + const data = { + researchId: uuid(b.researchId), + cycleName: text(b.cycleName, 300), + month: text(b.month, 40), + seasonalTheme: text(b.seasonalTheme), + strategicGoals: b.strategicGoals.map((g) => text(g, 1000)), + plannedArticlesCount: b.plannedArticlesCount, + plannedRefreshesCount: b.plannedRefreshesCount, + plannedCatalogEnrichments: b.plannedCatalogEnrichments, + isActive: b.isActive ?? false, + createdBy: actor, + }; + return this.operation(actor, 'roadmap', key, b, async (tx) => { + const research = await tx.corporateResearch.findUnique({ + where: { id: data.researchId }, + include: { sources: true }, + }); + if (!research || !research.sources.length) + throw new ConflictException('Evidence-backed research required'); + const result = await tx.corporateRoadmap.create({ + data: { ...data, goals: { create: goals } }, + include: { goals: true }, + }); + await tx.corporateResearch.update({ + where: { id: research.id }, + data: { status: 'IN_BACKLOG' }, + }); + return result; + }); + } + effect(actor: string, key: string, id: string, input: unknown) { + const b = object(input, [ + 'metric', + 'availability', + 'baseline', + 'observed', + 'source', + 'observedAt', + ]); + const availability = choice(b.availability, [ + 'MEASURED', + 'UNAVAILABLE', + 'UNINSTRUMENTED', + 'BUSINESS_DISABLED', + ]); + for (const k of ['baseline', 'observed']) + if ( + b[k] !== undefined && + b[k] !== null && + (typeof b[k] !== 'number' || !Number.isFinite(b[k])) + ) + throw new BadRequestException('Invalid metric'); + if (availability === 'MEASURED' && typeof b.observed !== 'number') + throw new BadRequestException('Measured value required'); + if ( + availability !== 'MEASURED' && + (b.observed != null || b.baseline != null) + ) + throw new BadRequestException('Unavailable is not zero'); + const observedAt = new Date(b.observedAt); + if ( + !Number.isFinite(observedAt.getTime()) || + observedAt.getTime() > Date.now() + ) + throw new BadRequestException('Invalid observation time'); + return this.operation(actor, 'effect:' + id, key, b, async (tx) => { + const task = await this.lock(tx, id); + if (task.status !== 'DONE') + throw new ConflictException('Effects require completed QA'); + const e = await tx.corporateEffect.create({ + data: { + taskId: id, + metric: text(b.metric, 300), + availability, + baseline: b.baseline, + observed: b.observed, + source: text(b.source, 2000), + observedAt, + recordedBy: actor, + }, + }); + await this.event(tx, id, actor, 'EFFECT_RECORDED', e.metric, 'SYSTEM', { + effectId: e.id, + }); + return e; + }); + } + report(actor: string, key: string, input: unknown) { + const b = object(input, ['day', 'summary']); + const day = text(b.day, 10), + summary = text(b.summary); + if ( + !/^\d{4}-\d{2}-\d{2}$/.test(day) || + !Number.isFinite(Date.parse(day + 'T00:00:00Z')) + ) + throw new BadRequestException('ISO day required'); + return this.operation(actor, 'report', key, b, async (tx) => { + const start = new Date(day + 'T00:00:00Z'), + end = new Date(start.getTime() + 86400000); + const tasks = await tx.corporateTask.findMany({ + where: { updatedAt: { gte: start, lt: end } }, + select: { + id: true, + taskCode: true, + title: true, + status: true, + department: true, + updatedAt: true, + }, + }); + const events = await tx.corporateEvent.findMany({ + where: { timestamp: { gte: start, lt: end } }, + orderBy: { timestamp: 'asc' }, + }); + const effects = await tx.corporateEffect.findMany({ + where: { createdAt: { gte: start, lt: end } }, + }); + const snapshot = JSON.parse( + JSON.stringify({ timezone: 'UTC', tasks, events, effects }), + ); + return tx.corporateReport.create({ + data: { day, summary, snapshot, createdBy: actor }, + }); + }); + } +} diff --git a/specs/corporate-backend/api.md b/specs/corporate-backend/api.md new file mode 100644 index 00000000..6034179d --- /dev/null +++ b/specs/corporate-backend/api.md @@ -0,0 +1,24 @@ +# Corporate API contract + +Base `/api/admin/hermes` (application global `/api` prefix). All routes use existing JwtAuthGuard + RolesGuard, Admin/SUPER_ADMIN; API keys require explicit admin scope. Actor comes from authenticated user/key ID. Never accepts executor/reviewer identity in request bodies. + +- GET `runtime`: `{mode: MANUAL_DORMANT, schedulesEnabled:false, externalExecutionEnabled:false}`. +- GET `tasks`: `{data,meta:{total,page,limit,totalPages,hasNextPage,hasPrevPage}}`. page default 1; limit default 20, valid 1..100. Filters department, priority, status, goalId. Search only normalized title/taskCode (Persian/Arabic letters, digits, zero-width spaces, parentheses). Sort allowlist createdAt/updatedAt/title/taskCode/priority/status; sortOrder asc/desc. Deterministic id tie break, repeatable-read count/page snapshot. +- GET `tasks/:id`: raw persisted task with logs/evidence/reviews/effects/children; 404 absent, 400 malformed UUID. +- POST `tasks`: `{title,department,description,priority?='CEO_EXPEDITE',parentId?,goalId?,actionType?,dueCycle?}`. Raw persisted task, 201. Strict allowlist. actionType CEO_DIRECTIVE/BLOG_NEW/BLOG_UPDATE/CATALOG_ENRICH/RESEARCH/ENGINEERING. BLOG_NEW separate from needs-driven BLOG_UPDATE, no quota ratio. +- POST `claims`: `{department?,leaseSeconds?=300}` valid lease 30..900 seconds. Returns `{task:null|task}`. Priority enum order CEO_EXPEDITE..LOW, oldest updated first. Actual row lock SKIP LOCKED. Expired IN_PROGRESS leases reclaimable with new UUID token. Pending children exclude parent; rejected child QA sets parent BLOCKED; corrected children eventually make parent reclaimable. +- POST `tasks/:id/evidence`: `{claimToken,artifactUri,sha256,summary,tool,result}`. Current owner + unexpired lease required. Stores receipt, transitions to TEST. HTTPS or content-addressed urn:sha256 locator; digest 64 lowercase hex. No network access performed. +- POST `tasks/:id/reviews`: `{evidenceId,passed:boolean,findings,verification:{artifactUri,sha256,method,result}}`. Exact current artifact required. Reviewer must differ from executor authenticated subject. Pass -> DONE only if every child DONE. Fail -> TODO for a new execution/QA attempt; parent BLOCKED. No retry cap or approval modules. +- GET `market-insights`: `{data,meta}`, pagination, optional category. Fields match existing UI: title/category/source/opportunity/impact/recommendedAction/status/createdAt plus sources/provenance/cadence. +- POST `market-insights`: title/category/source/opportunity/impact/recommendedAction, cadence MONTHLY|EVENT, provenance `{method,collector,context}`, sources (1..30) `{url:https,title,excerpt,retrievedAt,sha256}`. +- GET `monthly-roadmap`: `{data,meta}`, pagination, optional month. Existing UI fields retained: cycleName/month/seasonalTheme/strategicGoals/plannedArticlesCount/plannedRefreshesCount/plannedCatalogEnrichments/isActive/createdAt plus goals. +- POST `monthly-roadmap`: researchId + above UI fields + goals `[ {title,department,acceptanceCriteria,metric,target?} ]`. Requires persisted source-backed research. Creates goals atomically; connect tasks through returned goal IDs. Active is declarative, not schedule activation. +- POST `tasks/:id/effects`: `{metric,availability:MEASURED|UNAVAILABLE|UNINSTRUMENTED|BUSINESS_DISABLED,baseline?,observed?,source,observedAt}`. DONE required. MEASURED requires numeric observed; other states prohibit numeric values (missing != zero). +- GET `reports`: `{data,meta}`. +- POST `reports`: `{day:YYYY-MM-DD,summary}` creates unique daily UTC snapshot of persisted tasks/events/effects. Summary is attributed user-supplied text, not generated or independently verified analytics. + +All POST operations accept `Idempotency-Key`, mandatory except task creation for compatibility with existing UI. Without the optional create key, retry creates a new task. Keys scoped to authenticated actor and operation; canonical payload digest mismatch ->409; transaction advisory lock serializes duplicate requests; immutable response saved in same transaction. Use fresh key for a new claim attempt; replaying a past claim returns original (possibly now expired) lease, never renews it. Claim token never authorizes other actors. + +## Limitations / explicit boundaries + +This is a persisted manual orchestration ledger and guarded lifecycle, not an autonomous executor. No scheduler, commands, URL fetching, LLM calls, publishing or deployment adapters. Evidence/provenance and QA verification are authenticated attestations, not server-side fetched content proof. Independent credentials do not prove independent humans. No arbitrary status PATCH, cancellation UI, lease heartbeat, research update, roadmap auto fan-out, provider metric ingestion, or push notifications. Daily publisher remains unchanged; roadmap consumption requires parent integration. Daily snapshots use UTC, not Tehran business-day boundaries. Roadmap activity need not be unique per month. GET collection sorts by createdAt descending; task list is sortable. No frontend/storefront changes or Stage deployment in this branch. diff --git a/specs/corporate-backend/plan.md b/specs/corporate-backend/plan.md new file mode 100644 index 00000000..2f0f22e5 --- /dev/null +++ b/specs/corporate-backend/plan.md @@ -0,0 +1,5 @@ +# Plan + +Base 1f01b9dab94fbd62a5cf7a3b188c894005c9aab0, clean isolated corporate-backend branch. Existing graph hash 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af; graph is navigation only (binding unverified). Graph traversal AdminModule -> PrismaService/auth confirmed by direct source. Existing UI fields inspected in hermesApi.ts. Admin JwtAuthGuard supports JWT/API keys; RolesGuard requires admin scope for API keys. + +Add standalone Prisma corporate entities with foreign keys and migration, admin/hermes controller and service wired in AdminModule. Shared validation functions explicitly validate bodies, reject unknown keys. All mutations use transactions with advisory key locks, payload digest and stored response. Per-task row locks serialize claims/evidence/review/children. Use authenticated actor identity, never submitted reviewer/executor identity. No worker/cron activation. diff --git a/specs/corporate-backend/spec.md b/specs/corporate-backend/spec.md new file mode 100644 index 00000000..e19077ca --- /dev/null +++ b/specs/corporate-backend/spec.md @@ -0,0 +1,7 @@ +# Persisted corporate backend + +Scope: backend only, manual dormant API; no schedules, approval modules, execution adapters, seeded records or external side effects. + +Authenticated administrators persist evidence-backed monthly/event research, goals and roadmaps, department tasks, execution receipts, independent QA, effects and daily reports. Preserve daily NEW articles independently from needs-based updates; no ratio policy. + +Acceptance: task lists {data,meta}, title/taskCode Persian-normalized search, filters, sort allowlist, <=100 pagination; raw detail; CEO_EXPEDITE default. Atomic SKIP LOCKED claims, expiring leases and token fencing. Idempotency keys bound to actor, operation and canonical payload. Evidence required before QA; reviewer distinct authenticated principal from executor. Children must all be DONE before parent completion. No API executes commands or fetches URLs. Real DB tests when disposable PostgreSQL is available. diff --git a/specs/corporate-backend/tasks.md b/specs/corporate-backend/tasks.md new file mode 100644 index 00000000..5fd787a4 --- /dev/null +++ b/specs/corporate-backend/tasks.md @@ -0,0 +1,9 @@ +# Tasks + +- [x] RED contract tests +- [x] Prisma entities and additive migration +- [x] Validated guarded admin/hermes API, durable audit trail +- [x] Claim/fence/idempotency/QA gates +- [x] GREEN targeted tests, Prisma validate, backend build +- [x] Disposable DB verification if available; document gaps +- [x] Commit backend and scoped specs only; no push diff --git a/specs/corporate-backend/verification.md b/specs/corporate-backend/verification.md new file mode 100644 index 00000000..147ea210 --- /dev/null +++ b/specs/corporate-backend/verification.md @@ -0,0 +1,12 @@ +# Verification + +Local only, base 1f01b9dab94fbd62a5cf7a3b188c894005c9aab0. No push, deployment, cron changes or Hermes restart. + +- RED: corporate-policy.spec.ts failed because corporate-policy module absent before implementation. Integration tests added after implementation; not claimed as strict TDD. +- Prisma 5.22 schema validation PASS with explicit unused loopback URL; client generated privately (copied node_modules, not shared generated client). +- Additive migration generated with `prisma migrate diff` from exact base schema; applied successfully with `prisma db execute` to disposable PostgreSQL database corporate_test, loopback port 55439 and scratch socket. Existing scratch PostgreSQL binaries used; Docker daemon unavailable. No production credentials used. +- `npm run build` PASS (tsc -b). +- `CORPORATE_TEST_DATABASE_URL=postgresql://hermes@127.0.0.1:55439/corporate_test node_modules/.bin/jest --runInBand --runTestsByPath src/admin/hermes/corporate.integration.spec.ts src/admin/hermes/corporate-policy.spec.ts src/common/guards/roles.guard.spec.ts src/admin/api-keys.service.spec.ts`: PASS 4 suites / 24 tests. +- Five DB-backed HTTP scenarios verify actual Nest controller + service and existing guards: unauthenticated 401/admin scope 403; normalized list/search/meta; key replay and mismatch; actual concurrent duplicate create; exclusive concurrent claims; real held row lock skipped; lease expiration/reclaim and stale token rejection; independent reviewer; DONE receipt and logs; unavailable != zero; parent exclusion and QA rejection BLOCKED; research/source/roadmap/goal/report persistence. App listens on loopback TCP; DB fixture cleanup after suite. +- Test API-key validator is a local test double; unauthenticated JWT rejection uses local test Passport strategy. This does NOT prove live production JWT/user lookup or live API-key validity. Existing roles/API-key unit suites passed. AdminModule wiring compiled; whole production AdminModule boot is not exercised because unrelated Redis/settings providers are not started. +- No full backend regression suite, frontend/admin/storefront build, worker consumption, Stage runtime or production acceptance asserted. Spec baseline CLI 1.2.3 checked; scoped spec/plan/tasks authored explicitly without overwriting shared scaffolding.