feat(hermes): persist guarded corporate orchestration backend

This commit is contained in:
Canina Automation committed 2026-10-28 11:57:15 +00:00
1 parent 5550c80a75
commit cc365bcda2
13 files changed
+1734

No files matched your search

+24
View File
@@ -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.
+5
View File
@@ -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.
+7
View File
@@ -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.
+9
View File
@@ -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
+12
View File
@@ -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.