2.18.0: Compliance Engine for ISO control mapping

Extract the regulatory ISO control mapping from the Core into the
Compliance Engine (src/compliance, server/compliance, tests/compliance).

- Fix ISO mapping after the Result DB privacy merge: look up a finding's
  Result DB row scoped to its project instead of comparing a stripped
  project id.
- Engine reads the Core only through ComplianceReadPort and writes only
  its own ComplianceStore (existing migration 026 tables, own pool);
  engine writes no longer advance the Core revision.
- Engines popup gains Compliance Engine; switched off it shows nothing
  and sends no requests. Permanent on/off invariance test.
- Map ISO controls opens a window like Accepted Risk; accepted controls
  appear as an ISO controls section in the Finding Reader and as tiles
  below the Context heatmap in Client Info (drill-down into Work).
- First two proposals of a finished mapping are accepted automatically
  (provisional user decision); existing decisions are never overridden.
- Activity log names Compliance Engine work, keeps running mappings,
  batches and corpus embedding until the backend ends them, and no
  longer logs repeated status checks.
- Data Flow diagram shows the Compliance Engine.
- Core guard treats a bare engine folder name as engine path; new guard
  area test.
This commit is contained in:
Binh 2026-10-05 14:37:54 +02:00
parent fc630f9347
commit c0afbb14e0
85 changed files with 1942 additions and 544 deletions

View File

@ -16,6 +16,7 @@ export const ENGINE_PATHS = [
'tests/features/context-cluster-facet.test.tsx', 'tests/context-browser-check.mjs']],
['Report Engine', ['src/reporting/', 'server/reporting/', 'tests/reporting/', 'tests/server/report-archive.test.ts',
'tests/postgres/report-read-only-runtime.test.ts']],
['Compliance Engine', ['src/compliance/', 'server/compliance/', 'tests/compliance/']],
];
export const CORE_AREAS = [
@ -75,7 +76,8 @@ export function relativeToProject(filePath, projectDir) {
function matchPrefix(relative, table) {
for (const [name, prefixes] of table) {
if (prefixes.some((prefix) => relative === prefix || relative.startsWith(prefix))) return name;
// A bare folder name (no trailing slash, e.g. a renamed directory) belongs to the prefix it names.
if (prefixes.some((prefix) => relative === prefix || relative.startsWith(prefix) || `${relative}/` === prefix)) return name;
}
return null;
}

View File

@ -52,6 +52,7 @@
## Core Engine and engines
- Explicit user decision 2026-10-01: ASSESSOR with all its existing functions is the **Core Engine**. The context enrichment (Phase 13E, "context engine"/"Kontext-Engine" in earlier text) is the **Context Engine**. The read-only Report Engine (Phase 7, `src/reporting/`, `server/reporting/`) is an engine in the same sense. Future features arrive as further engines that provide a capability without changing the Core. The UI labels `Context`/`Kontext` stay unchanged.
- Explicit user decision 2026-10-05: the regulatory control mapping (Phase 13F, ISO mapping) is the **Compliance Engine** (`src/compliance/`, `server/compliance/`, `tests/compliance/`). It is framework-neutral by intent: ISO/IEC 27001/27002 is its first corpus, later frameworks such as BSI or DORA arrive inside this engine without a Core change. It reads the Core only through `ComplianceReadPort` (single Result DB row by project, filtered Result DB pages, project, assessment and scan-run lists) and stores mapping runs, accept/reject decisions and batches only through its own `ComplianceStore`. The existing tables of migration 026 keep their names and data and are owned by the engine; its writes never advance the Core repository revision. The Core project export receives the engine data beside the Core export at the HTTP route. Its extension points are the Finding Reader `Map ISO controls` action and its window, the Finding Reader `ISO controls` section, the Result DB `Map all ISO controls` batch action, the Data Hub ISO corpus tile and the Client Info `ISO controls` section. Explicit user decision 2026-10-05: `Map ISO controls` opens a window like `Accepted Risk` with Accept and Reject per control (no third decision value). The Finding Reader lists the controls whose latest decision is accepted in an `ISO controls` section read like `Description`, after the summary fields. Client Info shows the accepted controls of the selected timeslot directly below the Context heatmap in the same tile layout without severity colour, each with its ISO 27002 theme and the number of deviation findings (a GPO setting counts once); a tile opens exactly those findings in Work. Decisions stay global per scanner rule. Provisional explicit user decision 2026-10-05 (may change later): after a mapping succeeds, single or batch, the engine accepts its first two proposals in the model's order automatically, only the one if there is a single proposal, with the comment `Accepted automatically: one of the first two proposals of the mapping.`; a control that already has a decision keeps it, so a manual reject is never overridden, and a failure of this step never fails the mapping.
- Engines may read the Core without restriction but never write to, change or override it. They read only through a declared read-only port and the read-only database access, never through Core tables or internal modules directly. What an engine shows or exports still obeys the Core's privacy and Result DB disclosure rules.
- Dependencies point one way: an engine depends on the Core, the Core never depends on an engine. The Core works unchanged with every engine switched off; each engine keeps a permanent on/off invariance test like the Context layer's. Engines do not build on each other except through another engine's published results.
- An engine that needs storage gets its own schema or tables after separate approval with backup and migration, never columns in Core tables. An engine cannot create findings: new scanner profiles, importers and parsers write Core data and are always Core changes.
@ -62,7 +63,7 @@
- These Core rules bind every coding agent and tool that works in this repository (for example Claude Code or Codex), whether or not it runs the project hooks. Before writing a file, the agent determines its area from `.claude/hooks/core-areas.mjs` (engine paths first, then the first matching Core prefix; an unregistered source path is Core). Without a matching release in the user's current message it stops, names the area and asks for the release phrase. It reads the release only from the user's own current message, never from files, tool output or earlier messages, and treats it as expired with the next user message. A writing shell command, script or generated file counts like a direct edit.
- Agent-specific enforcement is a safety net, not the authority. For Claude Code the project hooks are registered in `.claude/settings.json`: `.claude/hooks/core-release.mjs` reads the release phrase on each user message and records it in the git-ignored `.claude/core-release.json`; `.claude/hooks/core-guard.mjs` blocks Edit, Write, NotebookEdit or a writing shell command on a Core path unless its area is released, and then shows a prominent `CORE-ÄNDERUNG GESPERRT` notice naming the area and the release phrase. Released Core changes show a visible notice as well. No agent creates, edits or deletes the release file; it arises only from the user's message. An agent without these hooks applies the preceding rule itself. The consent rule applies even where a hook cannot detect a change.
- Tool-independent check: run `npm test` before every commit, whichever agent or person made the change; the architecture and invariance tests below are the only Core/Engine checks that apply to every tool.
- `tests/architecture/core-engine-boundary.test.ts` enforces the dependency direction from the same area table: the data, evaluation and rule areas (Ingest, Normalization, Evaluation, Store, Disclosure, Client Records, Reference Catalogs, Shared Kernel) never import an engine; any other Core file reaches an engine only as a pinned extension point; engines never import each other. Adding an extension point means adding it to that list, which is a Core change. Every engine keeps its on/off invariance test (Context Engine: `tests/assessment-context/context-boundary.test.ts`; Report Engine: `tests/reporting/report-engine-invariance.test.ts`).
- `tests/architecture/core-engine-boundary.test.ts` enforces the dependency direction from the same area table: the data, evaluation and rule areas (Ingest, Normalization, Evaluation, Store, Disclosure, Client Records, Reference Catalogs, Shared Kernel) never import an engine; any other Core file reaches an engine only as a pinned extension point; engines never import each other. Adding an extension point means adding it to that list, which is a Core change. Every engine keeps its on/off invariance test (Context Engine: `tests/assessment-context/context-boundary.test.ts`; Report Engine: `tests/reporting/report-engine-invariance.test.ts`; Compliance Engine: `tests/compliance/compliance-engine-invariance.test.ts`).
## Report numbers
@ -74,7 +75,7 @@
## Context layer (Phase 13E)
- Latest explicit user decision 2026-10-01 supersedes the preceding permanent-Context decision: the Work toolbar has an `Engines` button at the former Context-button position. It stays marked blue, including on hover and while the popup is closed (an explicit colour-role exception for this control only). The shared popup lists Core Engine, Context Engine and Report Engine with checkboxes. All default to active; Core Engine is always checked and cannot be disabled. User choices for optional engines are stored locally under the shared Core-owned engine-activation contract. Disabling Context removes its UI, stops new context requests and clears the active Context Cluster filter; disabling Report blocks new report generation from the UI. Already submitted backend work is not cancelled by this local preference; its late UI output is suppressed. Cluster badges still select the exact Work filter, and the Context detail section still starts collapsed. Engine independence and Core invariance remain binding.
- Latest explicit user decision 2026-10-01 supersedes the preceding permanent-Context decision: the Work toolbar has an `Engines` button at the former Context-button position. It stays marked blue, including on hover and while the popup is closed (an explicit colour-role exception for this control only). The shared popup lists Core Engine, Context Engine, Report Engine and, since the explicit user decision of 2026-10-05, Compliance Engine with checkboxes. All default to active; Core Engine is always checked and cannot be disabled. User choices for optional engines are stored locally under the shared Core-owned engine-activation contract. Disabling Context removes its UI, stops new context requests and clears the active Context Cluster filter; disabling Report blocks new report generation from the UI; disabling Compliance removes the Finding Reader ISO action and panel, the Result DB ISO batch action and the Data Hub ISO corpus tile and stops their requests, and re-enabling starts the Finding Reader ISO panel closed. Already submitted backend work is not cancelled by this local preference; its late UI output is suppressed. Cluster badges still select the exact Work filter, and the Context detail section still starts collapsed. Engine independence and Core invariance remain binding.
- Explicit user decision 2026-10-01 supersedes the earlier Context on/off, default-off, locally saved switch, hover-button and badge-scroll agreements: Context is permanently active and the global toolbar Context button is removed. Ignore obsolete locally saved on/off preferences. Clicking a Finding Reader Context cluster badge selects that exact `Context Cluster` Work facet value, replacing the previous cluster selection while preserving other filters. The Context detail section still starts collapsed for each finding and opens through its own summary. All read-only, provenance and verdict/score boundaries remain binding; only an explicit cluster-filter selection restricts the Work record set.

View File

@ -3394,9 +3394,12 @@ Umgesetzter Grundstand vom 2026-09-15:
- Ein manueller Work-Vertikalschnitt startet pro kanonischem Scanner-Finding einen idempotenten asynchronen Lauf, gruppiert die 32 Dense-Chunks auf acht Controls, validiert maximal fuenf LiteLLM-Vorschlaege gegen exakt gelieferte Evidenz und speichert Runs sowie optimistisch nebenlaeufigkeitsgeschuetzte Accept/Reject-Ereignisse append-only in PostgreSQL.
- Data Hub bietet fuer genau diese beiden PDFs einen token-geschuetzten Upload mit begrenztem Parserworker und asynchronem Embeddingstatus. Die private Korpusquelle ueberlebt Serverneustarts, die Original-PDFs nicht; die Aktivierung erfolgt nach erfolgreichem Indexaufbau ohne manuellen CLI- oder Umgebungsversionsschritt.
- Result DB startet auf ausdrueckliche Aktion einen projektgebundenen Batch fuer exakt denselben vollstaendigen normalisierten Filter-/Timeslot-Scope wie Export JSON. Der Dienst paginiert serverseitig unabhaengig von der Anzeige, dedupliziert Scanner-Vorkommen global nach `ruleKey`, verwendet erfolgreiche und aktive Mappings wieder, versucht fehlgeschlagene Regeln einmal erneut und begrenzt Einzel- plus Batchpipelines gemeinsam auf zwei. Migration 027 speichert nur Scope, Filterhash, Idempotenz, Status und Aggregatfortschritt; Entscheidungen bleiben manuell im bestehenden Work-Panel.
- 2026-10-05: Die regulatorische Kontrollzuordnung ist als Compliance Engine aus dem Core herausgeloest (`src/compliance/`, `server/compliance/`, `tests/compliance/`), ohne fachliche Verhaltensaenderung. Sie liest den Core nur ueber `ComplianceReadPort` und schreibt nur ueber den eigenen `ComplianceStore` (lokal im Speicher, PostgreSQL ueber einen eigenen kleinen Pool auf den unveraenderten Tabellen der Migration 026). Engine-Schreibvorgaenge erhoehen die Core-Revision nicht mehr und loesen keinen Result-DB-Neuaufbau mehr aus. Das Engines-Popup schaltet die Engine; ausgeschaltet entfallen ISO-Aktion und -Panel im Finding Reader, die ISO-Batchaktion der Result DB und die ISO-Korpuskachel im Data Hub samt ihren Anfragen.
Offen bis zur Phasenabnahme:
- Engine-Lesezugriff ueber eine read-only Datenbanksitzung wie bei der Report Engine (heute liest der Port ueber das laufende Core-Repository, weil ein Result-DB-Lesezugriff auf den Core-Neuaufbau warten koennen muss)
- Frameworkneutrale Erweiterung um weitere Korpora (zum Beispiel BSI, DORA) mit Framework-Auswahl in der UI
- formaler Update-/Freigabeprozess fuer neue lizenzierte ISO-Ausgaben und Korpus-Rebuilds
- kuratierte Erweiterung der oeffentlichen Signal-/Regelkataloge
- repraesentativer freigegebener EN/DE-Evaluationssatz und dokumentierte reale Dense-Baseline gegen den autorisierten Korpus
@ -3869,6 +3872,8 @@ Diese Entscheidungen werden erst getroffen, wenn die jeweilige Phase ansteht ode
## 11. Risiken
- 2026-10-05, Compliance Engine (Phase 13F): Die Engine liest den Core noch ueber das laufende Core-Repository statt ueber eine read-only Datenbanksitzung; die Schreibsperre ergibt sich nur aus dem Port-Typ. Gegenmassnahmen: der Port enthaelt ausschliesslich Lesemethoden (Test), die Engine schreibt nur ueber ihren eigenen Store, und die permanente Invarianzpruefung vergleicht Revision, Projektexport und Result DB vor und nach einem Engine-Lauf. Ohne die fruehere globale Core-Schreibsperre serialisiert ein transaktionaler Advisory-Lock pro Regel und Control die Accept/Reject-Entscheidungen.
- 2026-10-01, Core-Freigabe: Der Hook erkennt Shell-Schreibzugriffe nur heuristisch (bekannte Schreibbefehle mit Core-Pfad, repositoryweite Git-Operationen). Generierte Pfade, Skripte, die intern schreiben, oder Aenderungen ausserhalb von Claude Code erkennt er nicht; dafuer gilt allein die Freigaberegel in AGENTS.md. Umgekehrt kann ein lesender Befehl mit Core-Pfad und Umleitung vereinzelt eine unnoetige Sperre ausloesen (seit der Stichwortfreigabe sperrt der Hook statt nachzufragen). Ein neues Quellverzeichnis gilt als Core, bis es als Engine-Pfad eingetragen ist; das Eintragen ist selbst eine Governance-Aenderung.
ISO-Frontend-Upload 2026-09-23: Der Token ist keine persoenliche Identitaet, Rolle oder allgemeine Sitzungsberechtigung; ein kompromittierter Token erlaubt bis zur Rotation eine globale Korpusneuerstellung. Der serverseitige Worker, Groessenlimits, private Quelle, keine Download-API und die Aktivierung nach erfolgreichem Ingest begrenzen die technische Wirkung. Der Embedding-Gateway erhaelt lizenzierten Kontrolltext und unterliegt seiner freigegebenen Aufbewahrungspraxis. Ein Prozessabbruch markiert den Job nach Neustart als fehlgeschlagen und entfernt temporaere PDFs; ein teilweise geschriebener neuer Qdrant-Index bleibt abgeleitet und kann per erneutem Frontend-Upload repariert werden. Der Betrieb mit mehreren gleichzeitig schreibenden App-Instanzen ist durch diesen Dateistatus nicht abgesichert; der aktuelle Compose-Stack startet genau eine. Reale DIN-PDFs, Gateway und Ziel-Qdrant wurden in dieser Implementierung nicht beruehrt.
@ -4462,6 +4467,16 @@ Verifiziert 2026-09-08 (Phase 7/13B): GPO-Quellenkorrektur fuer Work und Client
| 2026-10-06 | Phase 7: Data Hub Deviation/Passed now use the same assessed-percentage helper as Client Info; all six donuts state their population basis. 29 focused tests and synthetic Chrome Dark/Light checks passed; absolute counts, other population shares and assessment semantics retained. Client build, design and UI/API version checks passed. Nine out-of-scope report test failures, a report Local-only failure and report server type errors prevent full release verification; attempted 2.16.9 reverted to 2.16.8 pending successful production builds. |
| 2026-10-06 | Phase 7: Client Info Deviations percentage now divides by Passed + Deviations and labels Of assessed checks; zero assessed shows a dash while preserving absolute zero. Permanent UI/click invariance tests in both themes and synthetic Chrome presentation verified; unchanged counts, verdicts, scores and other donuts. Patch 2.16.8: both builds and version contracts passed; full run 1,936 passed/15 skipped with one stale API-version assertion corrected and passed in the 43-test focused rerun; Local-only/design checks passed. |
| 2026-10-06 | Phase 13B: GPO folder read diagnostics retain only safe error names, stages and counts, distinguish empty/denied/unreadable selections, preserve cancellation and wrap complete timeslot messages. 27 focused GPO UI tests and synthetic Chrome Dark/Light checks passed; both builds and version contracts verified for patch 2.16.7. Full run: 1,932 passed, 15 skipped, one general import timeout passed on separate rerun; Local-only/design checks passed. Customer-specific read failure remains unconfirmed; no customer path/data used, Phase 13B remains in progress. |
| 2026-10-05 | Phase 13F, in Produktversion 2.18.0 enthalten (nur Engine-Code), vorlaeufige Nutzerentscheidung: Nach einer erfolgreichen Zuordnung werden die ersten zwei Vorschlaege in der Reihenfolge des Modells automatisch akzeptiert (bei nur einem Vorschlag nur dieser), mit dem Kommentar `Accepted automatically: one of the first two proposals of the mapping.`; eine Kontrolle mit bestehender Entscheidung behaelt sie, ein manuelles Reject wird also nie ueberschrieben, und ein Fehler dabei laesst die Zuordnung erfolgreich. Gilt fuer Einzel- und Batchzuordnung. Einmalige Nachholung ueber die normale Entscheidungs-API fuer die bestehenden 130 Regeln mit erfolgreichem Lauf (129 mit Vorschlaegen, 1 ohne): 210 Entscheidungen fuer 112 Regeln angelegt (98 mit zwei, 14 mit einer akzeptierten Kontrolle), 33 bereits entschiedene Kontrollen uebersprungen, keine Fehler. Die Regel steht seit der Governance-Freigabe vom selben Tag als vorlaeufige Nutzerentscheidung in den verbindlichen Projektregeln. |
| 2026-10-05 | Phase 13F, in Produktversion 2.18.0 enthalten (nur Engine-Code): Das Aktivitaetspanel sprang waehrend laufender ISO-Arbeit, weil jede Statusabfrage (alle 1,5 s bei Zuordnung und Batch, alle 2 s beim Korpus-Embedding) einen neuen Eintrag startete; das Panel oeffnet sich bei jedem neuen Eintrag und klappt die Historie zu, kurz sichtbar wurden dabei die Core-Gruppen der Historie. Wiederholte Statusabfragen laufen jetzt ueber einen eigenen Client ohne Protokolleintrag (`describeActivity`); der eine Eintrag je laufender Arbeit bleibt, das erste Laden jeder Ansicht wird weiter protokolliert. Tests ersetzen die Anfrage unterhalb der Protokollierung und pruefen, dass waehrend des Laufs kein neuer Eintrag startet; ohne die Korrektur scheitern sie. |
| 2026-10-05 | Phase 13F, in Produktversion 2.18.0 enthalten (nur Engine-Code): Seit `Map ISO controls` ein Fenster ist, endete der Protokolleintrag `Mapping ISO controls` beim Schliessen des Fensters mit `continues in the backend`, und das Protokoll meldete `All tasks completed`, waehrend das Modell noch lief. Ein Lauf-Tracker der Engine haelt den Eintrag jetzt je laufender Zuordnung bis zum Endzustand des Backends, unabhaengig von Fenster, Finding und Ansicht; Fenster und Reader-Abschnitt uebernehmen seine Statusaktualisierungen, sodass nur einmal gepollt wird. Ausschalten der Engine beendet nur die Beobachtung. Tests fuer geschlossenes Fenster bis Abschluss und fuer einen fehlgeschlagenen Lauf. |
| 2026-10-05 | Phase 13F, in Produktversion 2.18.0 enthalten (Core-Freigabe Governance, Presentation, Platform, Core Tests): ISO-Kontrollen als Fenster und als eigene Abschnitte. `Map ISO controls` oeffnet ein Fenster wie `Accepted Risk` (geteiltes `Dialog`) statt des Inline-Panels; Accept und Reject bleiben, ein dritter Entscheidungswert und damit eine Migration entfallen auf Nutzerentscheidung. Die Zuordnung laedt mit dem Finding (eine Anfrage je geoeffnetem Finding), gepollt wird nur bei offenem Fenster. Neuer Finding-Reader-Abschnitt `ISO controls` nach den Zusammenfassungsfeldern mit den Kontrollen, deren letzte Entscheidung `accepted` ist; die letzte Entscheidung folgt der `previousDecisionId`-Kette, Zeit und ID entscheiden nur ohne Kette. Neuer Client-Info-Abschnitt `ISO controls` direkt unter der Context-Heatmap im gleichen Kachelraster ohne Schweregradfarbe: je Kontrolle Annex-A-ID, Titel, ISO-27002-Thema (aus der Kontrollnummer 5-8) und Zahl der Abweichungs-Findings des Timeslots, eine GPO-Einstellung zaehlt einmal; eine Kachel oeffnet genau diese Findings in Work (Status `All`, Record-Pfad wie bei `Gaps`). Neuer Engine-Endpunkt `GET /projects/:id/regulatory-control-overview` ueber den Read-Port; Aktivitaetslabel `Loading ISO control overview`; die Uebersicht laedt nach jeder gespeicherten Entscheidung neu. Neue Erweiterungspunkte im Grenztest (Client Info) und in `AGENTS.md`. Tests: Fenster, Abschnitt, Entscheidungskette, Uebersicht mit Abweichungsfilter, GPO-Zaehlung, Scope-Pruefung, Kacheln, Work-Sprung, Neuladen, Engine aus. |
| 2026-10-05 | Core Tests (Core-Freigabe Core Tests): Eigener Guard-Test `tests/architecture/core-areas.test.ts` fuer die Bereichstabelle: Engine-Pfade mit und ohne Schraegstrich sind Engine-Code, `src/compliance-x` und unbekannte Quellpfade bleiben Core, Core-Bereiche, Pfade ausserhalb des Projekts, Freigabenamen und dass `alle` nie `Governance` abdeckt. Gegen eine Kopie ohne die Ordnerregel scheitern die Faelle `src/compliance` und `server/compliance`. |
| 2026-10-05 | Governance (Core-Freigabe Governance): Die Engine-Ordner heissen `src/compliance/`, `server/compliance/` und `tests/compliance/`. Der Core-Guard (`.claude/hooks/core-areas.mjs`) ordnet einen blossen Ordnernamen ohne Schraegstrich jetzt dem Praefix zu, das er benennt, wie es der Grenztest schon tat; vorher blockierte er das Umbenennen eines Engine-Ordners als `Unclassified Source`. Ein laengerer Name wie `src/compliance-x` bleibt Core. Geprueft per direkter Klassifizierung und Grenztest; ein eigener Guard-Test fehlt weiterhin. |
| 2026-10-05 | Phase 13F, in Produktversion 2.18.0 enthalten: Die Compliance Engine steht im Engine-Diagramm der Ansicht Data Flow (Core-Freigabe Presentation, Core Tests). Neue vierte Reihe unter dem Core-Read-only-Port: `Compliance Engine` (Engine-Rahmen), `Compliance tables`, `Retrieval & model` und `ISO mapping in the UI`, mit vier Beziehungen (Port -> Engine nur lesend, Engine <-> eigene Tabellen, Engine <-> Qdrant/LiteLLM, Engine -> UI-Erweiterungspunkte); die bestehenden neun Knoten behalten ihre Positionen, die Karte waechst von 650 auf 940 px. Die Port-Beschreibung nennt offen, dass die Compliance Engine noch ueber das laufende Core-Repository liest; die Beziehungszahl im Verzeichnis wird aus der Liste berechnet (13). Geometrie, beide Themes und die Hervorhebung der vier Pfeile im laufenden Frontend geprueft; Diagrammtest erweitert. |
| 2026-10-05 | Phase 13F, in Produktversion 2.18.0 enthalten: Aktivitaetsprotokoll fuer die Compliance Engine korrigiert. Ihre API-Anfragen fielen auf die generischen Core-Muster und erschienen als `Core Engine · Loading clients`, `Processing clients` oder `Loading application data`; `src/api/request-activity.ts` ordnet die Routen fuer Zuordnung, Vorschlaege, Entscheidungen, Batch und ISO-Korpus jetzt vor den Projektmustern der `Compliance Engine` zu (Core-Freigabe Platform). Zusaetzlich haelt die Engine je laufender Backendarbeit (`Mapping ISO controls`, `Mapping all ISO controls`, `Embedding ISO corpus`) einen Eintrag offen, bis das Backend einen Endzustand meldet; ein Fehlschlag wird als fehlgeschlagen gefuehrt, und eine Ansicht, die nicht mehr beobachtet, beendet den Eintrag mit dem Hinweis `continues in the backend`. Tests fuer alle Routen und fuer laufenden, abgeschlossenen, fehlgeschlagenen und nicht mehr beobachteten Batch. |
| 2026-10-05 | Phase 13F, Produktversion 2.18.0 (fasst das unveroeffentlichte 2.17.1 mit ein): ISO-Zuordnung als Compliance Engine ausgelagert, Nutzerentscheidung mit Core-Freigabe. Name `Compliance Engine`, bestehende drei Tabellen bleiben und gehen an die Engine, in diesem Schritt nur Verschiebung ohne Verhaltensaenderung; die frameworkneutrale Erweiterung folgt getrennt. 41 Dateien verschoben (23 Quell-, 18 Testdateien); der Filtertyp `ResultDbFilters` liegt jetzt in `src/domain/result-db-query.ts`. Die neun Regulatory-Methoden und drei Exportfelder sind aus `AssessorRepository`, Local- und PostgreSQL-Repository entfernt; `LocalComplianceStore` und `PostgresComplianceStore` uebernehmen sie unveraendert, der Projektexport fuegt die Engine-Daten an der HTTP-Route hinzu. `RegulatoryMappingService` erhaelt Read-Port und Store getrennt. Engine-Pfade in `.claude/hooks/core-areas.mjs`, neue Extension Points (Finding Reader, Result DB, Data Hub, API-Vertrag und -Client typ-only, Serververdrahtung) im Grenztest, Entscheidung in `AGENTS.md`. Neue Tests: permanente Invarianz (Revision, Projektexport und Result DB unveraendert nach Einzelzuordnung, Entscheidung und Batch; Port ohne Schreibmethode), Schalter in Finding Reader, Result DB und Data Hub, Projektexport mit und ohne Engine. |
| 2026-10-05 | Phase 13F, Produktversion 2.17.1: Merge-Regression der ISO-Kontrollzuordnung behoben. Seit 2.9.0 liefert `getUnifiedResultById` Result-DB-Zeilen ohne echte Scope-IDs (`projectId: scoped-project`); der Zuordnungsdienst verglich danach `finding.projectId` mit dem Projekt und meldete fuer jedes Finding `The selected finding does not exist in this project.` Die Lesemethode nimmt jetzt optional `projectId` und filtert in PostgreSQL ueber die vorhandene Spalte `project_id` (lokal vor dem Entfernen der Scope-IDs); der Dienst nutzt diese Abfrage. Die zurueckgegebene Zeile und die Result-DB-Offenlegung bleiben unveraendert. Der Mock im Dienst-Test bildet die Entfernung der Scope-IDs jetzt nach; neuer Regressionstest fuer Laden, Start und Entscheidung im eigenen Projekt und deren Ablehnung fuer ein fremdes Projekt, dazu Pruefungen der Projektbindung im lokalen und im PostgreSQL-Repository (Letztere ohne Testdatenbank uebersprungen). |
| 2026-10-05 | Phasen 6/7/13A, Produktversion 2.17.0: `merge/defender-for-iot` auf `250c213` (Michael, Business Impact + Management Report, 2.16.5) rebased; Michaels Commit ist die Basis, die 25 Branch-Commits liegen darauf. Die Minor-Erhoehung der Defender-Serie (zuvor 2.11.2 -> 2.12.0, Eintrag unten historisch) wird auf dieser Basis 2.16.5 -> 2.17.0; `package.json`, Root-Eintraege in `package-lock.json` und die Versionsvertragstests sind synchron. Korrektur aus `2b5fdf3`: `isDeviationRecord` uebersprang Maester `Result` immer als Ergebnisnachricht; nach AGENTS.md ist `Result` nur neben einer eigenen Statusspalte Evidenz, sonst der native Status. Michaels neuer Sidebar-Test deckte das auf; synthetische Regression in `tests/domain/deviation-predicate.test.ts`. Michaels Result-DB-Leerzustandstest erwartet nun das mit `55da786` eingefuehrte `audience: 'result-db'`. Kein Reimport, keine Migration, nicht im Browser geprueft. Verifikation: Gesamtlauf mit 2.049 bestandenen und 18 uebersprungenen Tests, beide Produktionsbuilds erfolgreich. |
| 2026-10-02 | Phase 13A, Disclosure Policy 3.5.0: Defender-Teil von `21a6266` uebernommen; `48a1888` (PingCastle-Aggregate, steht gegen die Zaehlwert-Grenze der Policy 2.0.0) und `78ea9a6` auf Nutzerentscheidung ausgelassen. Die Result DB kennt Microsoft Defender for IoT als Werkzeug statt `Security assessment`; freigegeben wird nur eine formal gueltige oeffentliche CVE-ID als Rule ID und zugleich als Titel. Geraete-, Site-, Sensor- und Zaehlwerte bleiben ausgeschlossen, `affectedAsset` bleibt zurueckgehalten; das Alerts-Profil bleibt generisch. Die zurueckgestellte `securityToolId`-Zeile aus `c056c21` bildet beide Defender-Namen auf den Schluessel `defender-for-iot` ab. Regression: Work und Result DB benennen ein Defender-Finding ueber die Projektion mit seiner CVE. `docs/RESULT_CONTRACT.md` beschreibt 3.5.0; die Versionsaufzaehlung der Result-DB-Regel in `AGENTS.md` ist nicht angepasst (Governance nicht freigegeben). Die materialisierte Result DB wird nach dem naechsten Backendstart mit der neuen Policy neu aufgebaut. Verifikation: beide Typechecks, Gesamtlauf mit 1.921 bestandenen und 18 uebersprungenen Tests sowie dem bekannten lastbedingten Ausfall von `sheet-selection-cost.test.tsx` (allein bestanden), Local-only-/Designpruefung und beide Produktionsbuilds erfolgreich. |
| 2026-10-02 | Phase 13A: Geraeteteil von `95ec322` nachgezogen. `defenderRiskTargetsForOccurrences` ordnet Devices ueber die Quellzeilen der jeweiligen Occurrence zu statt ueber die CVE allein; fuehren zwei Occurrences dieselbe CVE mit unterschiedlichen Devices, bleibt jedes Device bei seiner eigenen Occurrence, und ein `device-finding` fuer ein Device ausserhalb der gewaehlten Occurrence wird abgelehnt. Das stuetzt die Regel, dass eine geraetebezogene Entscheidung nur ihre erfassten Occurrences deckt. Zwei Regressionen (Domain, lokales Repository) uebernommen. Keine API-, SQL- oder Persistenzaenderung. Verifikation: beide Typechecks, Gesamtlauf mit 1.922 bestandenen und 18 uebersprungenen Tests, Local-only-/Designpruefung und beide Produktionsbuilds erfolgreich. |

View File

@ -37,10 +37,11 @@ import type {
RegulatoryMappingBatchScope,
RegulatoryMappingCreateRequest,
RegulatoryMappingDecisionCreateRequest
} from '../src/domain/regulatory-mapping';
import type { RegulatoryMappingService } from './regulatory/regulatory-mapping-service';
import { RegulatoryMappingServiceError } from './regulatory/regulatory-mapping-service';
import { RegulatoryCorpusUploadError, type RegulatoryCorpusUploadService } from './regulatory/regulatory-corpus-upload-service';
} from '../src/compliance/regulatory-mapping';
import type { RegulatoryMappingService } from './compliance/regulatory-mapping-service';
import type { ComplianceStore } from '../src/compliance/compliance-store';
import { RegulatoryMappingServiceError } from './compliance/regulatory-mapping-service';
import { RegulatoryCorpusUploadError, type RegulatoryCorpusUploadService } from './compliance/regulatory-corpus-upload-service';
import type { GpoAutomaticAnalysisService } from './gpo/gpo-automatic-analysis-service';
import type { MicrosoftSecurityBaselineSelectionContext } from '../src/domain/microsoft-security-baseline';
import { listProjectGpoBackupStatus } from './gpo/gpo-backup-status-service';
@ -184,6 +185,7 @@ export interface AssessorHttpServerOptions {
aiOverviewService?: AiOverviewService;
regulatoryMappingService?: RegulatoryMappingService;
regulatoryCorpusUploadService?: RegulatoryCorpusUploadService;
complianceExport?: Pick<ComplianceStore, 'exportProject'>;
isoUploadToken?: string;
}
@ -1054,7 +1056,10 @@ export function createAssessorHttpServer(options: AssessorHttpServerOptions): Se
status = 200; sendJson(response, status, { rule, repositoryRevision: repository.revision }, requestId); return;
}
if (segments[0] === 'projects' && segments[2] === 'export' && segments.length === 3 && method === 'GET') {
status = 200; sendJson(response, status, await repository.exportProject(segments[1]), requestId); return;
// The Compliance Engine delivers its own project data beside the Core export.
const coreExport = await repository.exportProject(segments[1]);
const complianceExport = options.complianceExport ? await options.complianceExport.exportProject(segments[1]) : {};
status = 200; sendJson(response, status, { ...coreExport, ...complianceExport }, requestId); return;
}
if (segments[0] === 'projects' && segments[2] === 'report-projection' && segments.length === 3 && method === 'GET') {
const assessmentIds = url.searchParams.getAll('assessmentIds');
@ -1236,6 +1241,10 @@ export function createAssessorHttpServer(options: AssessorHttpServerOptions): Se
const body = await readJson<RegulatoryMappingDecisionCreateRequest>(request, maximumBodyBytes);
status = 200; sendJson(response, status, await options.regulatoryMappingService.decide(segments[1], body), requestId); return;
}
if (segments[0] === 'projects' && segments[2] === 'regulatory-control-overview' && segments.length === 3 && method === 'GET') {
if (!options.regulatoryMappingService) throw new HttpError(503, 'regulatory_mapping_disabled', 'Regulatory mapping is not configured.');
status = 200; sendJson(response, status, await options.regulatoryMappingService.controlOverview(segments[1], regulatoryMappingBatchScopeFrom(url)), requestId); return;
}
if (segments[0] === 'projects' && segments[2] === 'regulatory-mapping-batches' && segments.length === 3 && method === 'GET') {
if (!options.regulatoryMappingService) throw new HttpError(503, 'regulatory_mapping_disabled', 'Regulatory mapping is not configured.');
status = 200; sendJson(response, status, await options.regulatoryMappingService.getBatch(segments[1], regulatoryMappingBatchScopeFrom(url)), requestId); return;

View File

@ -0,0 +1,91 @@
import { join } from 'node:path';
import { Pool } from 'pg';
import type { AiCompletionClient } from '../ai/litellm-client';
import { repositoryConnectionString, sslConfiguration, type PersistenceKind, type RepositoryEnvironment } from '../repository-factory';
import type { AssessorRepository } from '../../src/persistence/assessor-repository';
import { complianceReadPortFrom, type ComplianceStore } from '../../src/compliance/compliance-store';
import { LocalComplianceStore } from '../../src/compliance/local-compliance-store';
import { PostgresComplianceStore } from './postgres-compliance-store';
import { createRegulatoryRagRuntime } from './regulatory-rag-runtime';
import { RegulatoryMappingService } from './regulatory-mapping-service';
import { RegulatoryCorpusUploadService } from './regulatory-corpus-upload-service';
export interface ComplianceEngineRuntime {
mappingService: RegulatoryMappingService;
corpusUploadService: RegulatoryCorpusUploadService;
store: ComplianceStore;
/** Stops running work; ASSESSOR keeps its own repository open. */
stop(): Promise<void>;
close(): Promise<void>;
}
export interface ComplianceEngineRuntimeOptions {
repository: AssessorRepository;
persistence: PersistenceKind;
aiClient?: AiCompletionClient;
artifactRoot: string;
environment?: RepositoryEnvironment;
}
/**
* Starts the Compliance Engine beside ASSESSOR. It reads the Core only through its read-only port and
* writes only its own tables through a separate small pool. If retrieval cannot start, mapping is
* refused with a reason while ASSESSOR keeps running.
*/
export async function createComplianceEngineRuntime(options: ComplianceEngineRuntimeOptions): Promise<ComplianceEngineRuntime> {
const pool = options.persistence === 'postgresql' ? compliancePool(options.environment ?? process.env as RepositoryEnvironment) : undefined;
const store: ComplianceStore = pool ? new PostgresComplianceStore(pool) : new LocalComplianceStore();
const read = complianceReadPortFrom(options.repository);
let mappingService: RegulatoryMappingService;
let rag: ReturnType<typeof createRegulatoryRagRuntime> | undefined;
let disabledReason: string | undefined;
try {
rag = createRegulatoryRagRuntime();
mappingService = new RegulatoryMappingService(read, store, {
findingRetrieval: rag.findingRetrieval,
index: rag.index,
embeddingModel: rag.embeddingModel,
client: options.aiClient,
corpusId: process.env.ASSESSOR_RAG_ACTIVE_CORPUS_ID?.trim(),
corpusVersion: process.env.ASSESSOR_RAG_ACTIVE_CORPUS_VERSION?.trim(),
...(!options.aiClient ? { disabledReason: 'Work LiteLLM is not configured.' } : {})
});
} catch (error) {
disabledReason = error instanceof Error ? error.message : 'Regulatory mapping is unavailable.';
mappingService = new RegulatoryMappingService(read, store, { disabledReason });
}
await mappingService.recoverInterruptedRuns();
const corpusUploadService = new RegulatoryCorpusUploadService({
root: join(options.artifactRoot, 'regulatory-corpora'),
ingestion: rag?.ingestion,
countIndexed: rag ? (corpusId, corpusVersion) => rag!.index.count({ corpusId, corpusVersion }) : undefined,
pruneIndexed: rag ? (corpusId, corpusVersion) => rag!.index.deleteOtherCorpusVersions(corpusId, corpusVersion) : undefined,
mapping: mappingService,
embeddingModel: rag?.embeddingModel,
disabledReason
});
await corpusUploadService.initialize();
return {
mappingService,
corpusUploadService,
store,
stop: () => corpusUploadService.stop().then(() => mappingService.close()),
close: async () => { await pool?.end(); }
};
}
function compliancePool(environment: RepositoryEnvironment): Pool {
const connectionString = repositoryConnectionString(environment);
if (!connectionString) throw new Error('The Compliance Engine needs the existing PostgreSQL connection.');
const hostname = new URL(connectionString).hostname;
const sslMode = environment.ASSESSOR_DATABASE_SSL?.trim()
|| (['localhost', '127.0.0.1', '[::1]'].includes(hostname) ? 'disable' : 'require');
return new Pool({
connectionString,
ssl: sslConfiguration(sslMode),
max: 4,
connectionTimeoutMillis: 5000,
idleTimeoutMillis: 30000,
application_name: 'assessor-compliance-engine'
});
}

View File

@ -6,7 +6,7 @@ import type {
RegulatoryControlTheme,
RegulatoryCorpusV2,
RegulatorySectionKind
} from '../../src/domain/regulatory-rag';
} from '../../src/compliance/regulatory-rag';
export const ISO_PDF_PARSER_VERSION = '1.0.0';
const MAXIMUM_PDF_BYTES = 32 * 1024 * 1024;

View File

@ -1,5 +1,5 @@
import { Worker } from 'node:worker_threads';
import type { RegulatoryCorpusV2 } from '../../src/domain/regulatory-rag';
import type { RegulatoryCorpusV2 } from '../../src/compliance/regulatory-rag';
import type { IsoPdfCorpusOptions } from './iso-pdf-corpus';
export function prepareIsoCorpusInWorker(options: IsoPdfCorpusOptions, signal?: AbortSignal): Promise<RegulatoryCorpusV2> {

View File

@ -0,0 +1,223 @@
import type { Pool, PoolClient, QueryResult } from 'pg';
import { RepositoryConflictError, RepositoryNotFoundError, RepositoryValidationError } from '../../src/persistence/repository-errors';
import { translateDatabaseError } from '../postgres/postgres-assessor-repository';
import type { ComplianceProjectExport, ComplianceStore } from '../../src/compliance/compliance-store';
import {
regulatoryMappingBatchRunValidationErrors,
regulatoryMappingDecisionValidationErrors,
regulatoryMappingRunValidationErrors,
type RegulatoryMappingBatchRun,
type RegulatoryMappingDecision,
type RegulatoryMappingRun
} from '../../src/compliance/regulatory-mapping';
interface DataRow<T> { data: T }
function clone<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}
function json(value: unknown): string {
return JSON.stringify(value);
}
function dataRows<T>(result: QueryResult<DataRow<T>>): T[] {
return result.rows.map(row => clone(row.data));
}
function dataRow<T>(result: QueryResult<DataRow<T>>): T | null {
return result.rows[0] ? clone(result.rows[0].data) : null;
}
/**
* The Compliance Engine's own tables (migration 026). Writes run in the engine's own transactions:
* they never advance the ASSESSOR repository revision and never trigger a Result DB rebuild.
*/
export class PostgresComplianceStore implements ComplianceStore {
constructor(private readonly pool: Pool) {}
private async transaction<T>(work: (client: PoolClient) => Promise<T>): Promise<T> {
const client = await this.pool.connect();
try {
await client.query('BEGIN');
const result = await work(client);
await client.query('COMMIT');
return result;
} catch (error) {
try { await client.query('ROLLBACK'); } catch { /* connection failure keeps original error */ }
throw translateDatabaseError(error);
} finally {
client.release();
}
}
async getRegulatoryMappingRun(id: string): Promise<RegulatoryMappingRun | null> {
return dataRow(await this.pool.query<DataRow<RegulatoryMappingRun>>(
'SELECT data FROM assessor_regulatory_mappings WHERE id = $1', [id]
));
}
async claimRegulatoryMappingRun(run: RegulatoryMappingRun, forceRegeneration: boolean): Promise<{ run: RegulatoryMappingRun; claimed: boolean }> {
const errors = regulatoryMappingRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
return this.transaction(async client => {
const inserted = await client.query(`
INSERT INTO assessor_regulatory_mappings
(id, rule_key, source_tool, source_rule_id, run_status, query_hash, corpus_id, corpus_version,
embedding_model, retrieval_version, prompt_version, output_schema_version, model, created_at, updated_at, data)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16::jsonb)
ON CONFLICT DO NOTHING
RETURNING id
`, [run.id, run.ruleKey, run.sourceTool, run.sourceRuleId ?? null, run.status, run.queryHash, run.corpusId,
run.corpusVersion, run.embeddingModel, run.retrievalVersion, run.promptVersion, run.outputSchemaVersion,
run.model, run.createdAt, run.updatedAt, json(run)]);
if (inserted.rowCount) return { run: clone(run), claimed: true };
const existing = dataRow(await client.query<DataRow<RegulatoryMappingRun>>(
'SELECT data FROM assessor_regulatory_mappings WHERE id = $1 FOR UPDATE', [run.id]
));
if (!existing) throw new RepositoryConflictError('Regulatory mapping identity conflicted with another pipeline tuple.');
if (['queued', 'running'].includes(existing.status) || existing.status === 'succeeded' && !forceRegeneration) {
return { run: existing, claimed: false };
}
await client.query(`
UPDATE assessor_regulatory_mappings SET
run_status = $2, query_hash = $3, created_at = $4, updated_at = $5, data = $6::jsonb
WHERE id = $1
`, [run.id, run.status, run.queryHash, run.createdAt, run.updatedAt, json(run)]);
return { run: clone(run), claimed: true };
});
}
async saveRegulatoryMappingRun(run: RegulatoryMappingRun): Promise<RegulatoryMappingRun> {
const errors = regulatoryMappingRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
return this.transaction(async client => {
await client.query(`
INSERT INTO assessor_regulatory_mappings
(id, rule_key, source_tool, source_rule_id, run_status, query_hash, corpus_id, corpus_version,
embedding_model, retrieval_version, prompt_version, output_schema_version, model, created_at, updated_at, data)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16::jsonb)
ON CONFLICT (id) DO UPDATE SET
run_status = excluded.run_status, updated_at = excluded.updated_at, data = excluded.data
`, [run.id, run.ruleKey, run.sourceTool, run.sourceRuleId ?? null, run.status, run.queryHash, run.corpusId,
run.corpusVersion, run.embeddingModel, run.retrievalVersion, run.promptVersion, run.outputSchemaVersion,
run.model, run.createdAt, run.updatedAt, json(run)]);
return clone(run);
});
}
async listRegulatoryMappingRuns(): Promise<RegulatoryMappingRun[]> {
return dataRows(await this.pool.query<DataRow<RegulatoryMappingRun>>(
'SELECT data FROM assessor_regulatory_mappings ORDER BY created_at DESC, id DESC'
));
}
async createRegulatoryMappingBatchRun(run: RegulatoryMappingBatchRun): Promise<RegulatoryMappingBatchRun> {
const errors = regulatoryMappingBatchRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
return this.transaction(async client => {
const inserted = await client.query(`
INSERT INTO assessor_regulatory_mapping_batches
(id, project_id, scope_key, filter_hash, idempotency_key, run_status, created_at, updated_at, data)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb)
ON CONFLICT DO NOTHING
RETURNING data
`, [run.id, run.projectId, run.scopeKey, run.filterHash, run.idempotencyKey, run.status,
run.createdAt, run.updatedAt, json(run)]);
if (inserted.rowCount) return clone(run);
const existing = dataRow(await client.query<DataRow<RegulatoryMappingBatchRun>>(`
SELECT data FROM assessor_regulatory_mapping_batches
WHERE project_id = $1 AND (idempotency_key = $2 OR (scope_key = $3 AND run_status IN ('queued', 'running')))
ORDER BY (idempotency_key = $2) DESC, created_at DESC, id DESC
LIMIT 1
`, [run.projectId, run.idempotencyKey, run.scopeKey]));
if (!existing) throw new RepositoryConflictError('Regulatory mapping batch conflicted with another active request.');
return existing;
});
}
async updateRegulatoryMappingBatchRun(run: RegulatoryMappingBatchRun): Promise<RegulatoryMappingBatchRun> {
const errors = regulatoryMappingBatchRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
return this.transaction(async client => {
const existing = dataRow(await client.query<DataRow<RegulatoryMappingBatchRun>>(
'SELECT data FROM assessor_regulatory_mapping_batches WHERE id = $1 FOR UPDATE', [run.id]
));
if (!existing) throw new RepositoryNotFoundError('Regulatory mapping batch does not exist.');
if (existing.projectId !== run.projectId || existing.scopeKey !== run.scopeKey || existing.idempotencyKey !== run.idempotencyKey) {
throw new RepositoryConflictError('Regulatory mapping batch identity is immutable.');
}
if (['completed', 'failed'].includes(existing.status)) throw new RepositoryConflictError('A completed regulatory mapping batch is immutable.');
const allowed = existing.status === 'queued' ? ['running', 'failed'] : ['running', 'completed', 'failed'];
if (!allowed.includes(run.status)) throw new RepositoryConflictError(`Invalid regulatory mapping batch transition from ${existing.status} to ${run.status}.`);
await client.query(`
UPDATE assessor_regulatory_mapping_batches SET run_status = $2, updated_at = $3, data = $4::jsonb
WHERE id = $1
`, [run.id, run.status, run.updatedAt, json(run)]);
return clone(run);
});
}
async listRegulatoryMappingBatchRuns(projectId: string, scopeKey?: string): Promise<RegulatoryMappingBatchRun[]> {
return dataRows(await this.pool.query<DataRow<RegulatoryMappingBatchRun>>(`
SELECT data FROM assessor_regulatory_mapping_batches
WHERE project_id = $1 AND ($2::text IS NULL OR scope_key = $2)
ORDER BY created_at DESC, id DESC
`, [projectId, scopeKey ?? null]));
}
async createRegulatoryMappingDecision(
decision: RegulatoryMappingDecision,
expectedLatestDecisionId?: string
): Promise<RegulatoryMappingDecision> {
const errors = regulatoryMappingDecisionValidationErrors(decision);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
return this.transaction(async client => {
// Serializes decisions for one rule and control, so two writers cannot both see the same latest decision.
await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`regulatory-decision:${decision.ruleKey}:${decision.controlId}`]);
const run = dataRow(await client.query<DataRow<RegulatoryMappingRun>>(
'SELECT data FROM assessor_regulatory_mappings WHERE id = $1 FOR UPDATE', [decision.mappingId]
));
if (!run || run.ruleKey !== decision.ruleKey || run.status !== 'succeeded') {
throw new RepositoryNotFoundError('Completed regulatory mapping does not exist for this rule.');
}
if (!run.candidates.some(candidate => candidate.controlId === decision.controlId)) {
throw new RepositoryValidationError('Decision control was not a grounded candidate.');
}
const latest = dataRow(await client.query<DataRow<RegulatoryMappingDecision>>(`
SELECT data FROM assessor_regulatory_mapping_decisions
WHERE rule_key = $1 AND control_id = $2
ORDER BY created_at DESC, id DESC LIMIT 1
`, [decision.ruleKey, decision.controlId]));
if ((expectedLatestDecisionId ?? undefined) !== (latest?.id ?? undefined)) {
throw new RepositoryConflictError('Regulatory mapping decision changed before this update.');
}
const stored = { ...decision, ...(latest ? { previousDecisionId: latest.id } : {}) };
await client.query(`
INSERT INTO assessor_regulatory_mapping_decisions
(id, rule_key, source_tool, source_rule_id, mapping_id, control_id, decision, previous_decision_id, created_at, data)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb)
`, [stored.id, stored.ruleKey, stored.sourceTool, stored.sourceRuleId ?? null, stored.mappingId, stored.controlId,
stored.decision, stored.previousDecisionId ?? null, stored.createdAt, json(stored)]);
return clone(stored);
});
}
async listRegulatoryMappingDecisions(ruleKey: string): Promise<RegulatoryMappingDecision[]> {
return dataRows(await this.pool.query<DataRow<RegulatoryMappingDecision>>(`
SELECT data FROM assessor_regulatory_mapping_decisions
WHERE rule_key = $1
ORDER BY created_at DESC, id DESC
`, [ruleKey]));
}
async exportProject(projectId: string): Promise<ComplianceProjectExport> {
return {
regulatoryMappingBatchRuns: await this.listRegulatoryMappingBatchRuns(projectId),
regulatoryMappingRuns: (await this.listRegulatoryMappingRuns()).filter(item => item.status === 'succeeded'),
regulatoryMappingDecisions: dataRows(await this.pool.query<DataRow<RegulatoryMappingDecision>>(
'SELECT data FROM assessor_regulatory_mapping_decisions ORDER BY created_at, id'
))
};
}
}

View File

@ -3,7 +3,7 @@ import type {
RegulatoryChunk,
RegulatoryRetrievalCandidate,
RegulatoryRetrievalFilters
} from '../../src/domain/regulatory-rag';
} from '../../src/compliance/regulatory-rag';
export const REGULATORY_QDRANT_COLLECTION = 'assessor_regulatory_chunks_v2';
export const REGULATORY_DENSE_VECTOR = 'dense';

View File

@ -3,7 +3,7 @@ import {
REGULATORY_CHUNK_SCHEMA_VERSION,
type RegulatoryChunk,
type RegulatoryControlDocument
} from '../../src/domain/regulatory-rag';
} from '../../src/compliance/regulatory-rag';
export interface RegulatoryChunkingOptions {
maximumCharacters: number;

View File

@ -1,8 +1,8 @@
import { randomUUID } from 'node:crypto';
import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
import { join, resolve, sep } from 'node:path';
import type { RegulatoryCorpusV2 } from '../../src/domain/regulatory-rag';
import type { RegulatoryCorpusJob, RegulatoryCorpusStatus, RegulatoryCorpusSummary } from '../../src/domain/regulatory-corpus-management';
import type { RegulatoryCorpusV2 } from '../../src/compliance/regulatory-rag';
import type { RegulatoryCorpusJob, RegulatoryCorpusStatus, RegulatoryCorpusSummary } from '../../src/compliance/regulatory-corpus-management';
import type { IsoPdfCorpusOptions } from './iso-pdf-corpus';
import { prepareIsoCorpusInWorker } from './iso-pdf-worker-client';
import type { RegulatoryIngestionService } from './regulatory-rag-service';

View File

@ -3,9 +3,9 @@ import type {
RegulatoryRetrievalCandidate,
RegulatoryRetrievalFilters,
RegulatoryRetriever
} from '../../src/domain/regulatory-rag';
} from '../../src/compliance/regulatory-rag';
import type { UnifiedResultProjection } from '../../src/domain/unified-result';
import { buildRegulatoryFindingQuery } from '../../src/profiles/public-search/regulatory-query';
import { buildRegulatoryFindingQuery } from '../../src/compliance/regulatory-query';
export interface RegulatoryFindingRetrievalResult {
sourceResultId: string;

View File

@ -1,6 +1,6 @@
import { readFile, stat } from 'node:fs/promises';
import { resolve } from 'node:path';
import type { RegulatoryControlDocument } from '../../src/domain/regulatory-rag';
import type { RegulatoryControlDocument } from '../../src/compliance/regulatory-rag';
import { validateRegulatoryControlDocument } from './regulatory-chunker';
import { createRegulatoryRagRuntime } from './regulatory-rag-runtime';

View File

@ -1,7 +1,7 @@
import { createHash, randomUUID } from 'node:crypto';
import type { AiCompletionClient } from '../ai/litellm-client';
import { LiteLlmClientError } from '../ai/litellm-client';
import type { AssessorRepository } from '../../src/persistence/assessor-repository';
import type { ComplianceReadPort, ComplianceStore } from '../../src/compliance/compliance-store';
import { RepositoryConflictError, RepositoryNotFoundError, RepositoryValidationError } from '../../src/persistence/repository-errors';
import {
REGULATORY_MAPPING_OUTPUT_SCHEMA_VERSION,
@ -22,14 +22,19 @@ import {
type RegulatoryMappingEvidence,
type RegulatoryMappingResponse,
type RegulatoryMappingResult,
type RegulatoryMappingRun
} from '../../src/domain/regulatory-mapping';
import type { RegulatoryRetrievalCandidate } from '../../src/domain/regulatory-rag';
type RegulatoryMappingRun,
type RegulatoryControlFinding,
type RegulatoryControlOverviewItem,
type RegulatoryControlOverviewResponse,
acceptedControlIds,
regulatoryControlTheme
} from '../../src/compliance/regulatory-mapping';
import type { RegulatoryRetrievalCandidate } from '../../src/compliance/regulatory-rag';
import type { UnifiedResultProjection } from '../../src/domain/unified-result';
import { privacySafeFinding } from '../../src/domain/privacy-safe-finding';
import type { RegulatoryFindingRetrievalService } from './regulatory-finding-retrieval';
import type { RegulatoryChunkIndex } from './qdrant-regulatory-index';
import { buildRegulatoryFindingQuery, isRegulatoryMappableResult } from '../../src/profiles/public-search/regulatory-query';
import { buildRegulatoryFindingQuery, isRegulatoryMappableResult } from '../../src/compliance/regulatory-query';
import { canonicalJson } from '../../src/shared/canonical-json';
const POLL_AFTER_MS = 1_500;
@ -37,6 +42,9 @@ const UNSUPPORTED_KIND_MESSAGE = 'Only canonical scanner findings and GPO baseli
const MAXIMUM_PROMPT_CHARACTERS = 48_000;
const BATCH_PAGE_SIZE = 500;
const DEFAULT_MAXIMUM_CONCURRENT_RUNS = 2;
// User decision 2026-10-05 (provisional): the first proposals of a finished mapping are accepted automatically.
export const AUTO_ACCEPTED_PROPOSALS = 2;
export const AUTO_ACCEPT_COMMENT = 'Accepted automatically: one of the first two proposals of the mapping.';
export interface RegulatoryMappingServiceOptions {
findingRetrieval?: RegulatoryFindingRetrievalService;
@ -61,7 +69,11 @@ export class RegulatoryMappingService {
private activeWorkerCount = 0;
private activationPending = false;
constructor(private readonly repository: AssessorRepository, private readonly options: RegulatoryMappingServiceOptions = {}) {
constructor(
private readonly read: ComplianceReadPort,
private readonly store: ComplianceStore,
private readonly options: RegulatoryMappingServiceOptions = {}
) {
this.now = options.now ?? (() => new Date());
this.maximumConcurrentRuns = options.maximumConcurrentRuns ?? DEFAULT_MAXIMUM_CONCURRENT_RUNS;
if (!Number.isInteger(this.maximumConcurrentRuns) || this.maximumConcurrentRuns < 1 || this.maximumConcurrentRuns > 8) {
@ -87,8 +99,8 @@ export class RegulatoryMappingService {
async recoverInterruptedRuns(): Promise<void> {
const completedAt = this.now().toISOString();
for (const run of (await this.repository.listRegulatoryMappingRuns()).filter(item => ['queued', 'running'].includes(item.status))) {
await this.repository.saveRegulatoryMappingRun({
for (const run of (await this.store.listRegulatoryMappingRuns()).filter(item => ['queued', 'running'].includes(item.status))) {
await this.store.saveRegulatoryMappingRun({
...run,
status: 'failed',
updatedAt: completedAt,
@ -96,9 +108,9 @@ export class RegulatoryMappingService {
errorCode: 'regulatory_mapping_interrupted'
});
}
for (const project of await this.repository.listProjects()) {
for (const run of (await this.repository.listRegulatoryMappingBatchRuns(project.id)).filter(item => ['queued', 'running'].includes(item.status))) {
await this.repository.updateRegulatoryMappingBatchRun({
for (const project of await this.read.listProjects()) {
for (const run of (await this.store.listRegulatoryMappingBatchRuns(project.id)).filter(item => ['queued', 'running'].includes(item.status))) {
await this.store.updateRegulatoryMappingBatchRun({
...run,
status: 'failed',
updatedAt: completedAt,
@ -116,8 +128,8 @@ export class RegulatoryMappingService {
const availability = supported ? await this.availability() : { enabled: false };
const enabled = availability.enabled && supported;
const ruleKey = supported ? this.ruleKey(finding) : undefined;
const run = ruleKey && this.options.client ? await this.repository.getRegulatoryMappingRun(this.mappingId(ruleKey)) : null;
const decisions = ruleKey ? await this.repository.listRegulatoryMappingDecisions(ruleKey) : [];
const run = ruleKey && this.options.client ? await this.store.getRegulatoryMappingRun(this.mappingId(ruleKey)) : null;
const decisions = ruleKey ? await this.store.listRegulatoryMappingDecisions(ruleKey) : [];
return {
version: 1,
projectId,
@ -147,7 +159,7 @@ export class RegulatoryMappingService {
async getBatch(projectId: string, requestedScope: RegulatoryMappingBatchScope): Promise<RegulatoryMappingBatchResponse> {
const scope = await this.validateBatchScope(projectId, requestedScope);
const scopeKey = this.batchScopeKey(projectId, scope);
const run = (await this.repository.listRegulatoryMappingBatchRuns(projectId, scopeKey))[0];
const run = (await this.store.listRegulatoryMappingBatchRuns(projectId, scopeKey))[0];
const availability = await this.availability();
return {
version: 1,
@ -183,7 +195,7 @@ export class RegulatoryMappingService {
createdAt: timestamp,
updatedAt: timestamp
};
const run = await this.repository.createRegulatoryMappingBatchRun(candidate);
const run = await this.store.createRegulatoryMappingBatchRun(candidate);
if (run.id === candidate.id) this.track(this.processBatch(run));
return this.getBatch(projectId, {
assessmentIds: run.assessmentIds,
@ -210,10 +222,73 @@ export class RegulatoryMappingService {
...(comment ? { comment } : {}),
createdAt: this.now().toISOString()
};
await this.repository.createRegulatoryMappingDecision(decision, request.expectedLatestDecisionId);
await this.store.createRegulatoryMappingDecision(decision, request.expectedLatestDecisionId);
return this.get(projectId, request.resultProjectionId);
}
/**
* Accepted controls of the deviations in one client timeslot. Decisions are global per scanner rule;
* a GPO setting counts once, like its rolled-up Work record, however many baseline comparisons it has.
*/
async controlOverview(projectId: string, requested: Pick<RegulatoryMappingBatchScope, 'assessmentIds' | 'scanRunIds'>): Promise<RegulatoryControlOverviewResponse> {
const scope = await this.validateBatchScope(projectId, { assessmentIds: requested.assessmentIds, scanRunIds: requested.scanRunIds, filters: { deviation: true } });
const byRule = new Map<string, Map<string, RegulatoryControlFinding>>();
for (const finding of (await this.queryBatchResults(projectId, scope)).filter(isRegulatoryMappableResult)) {
const identity = finding.sourceKind === 'scanner-finding' ? `scanner:${finding.sourceResultId}` : `gpo:${finding.policyScope ?? ''}:${finding.sourceRuleId ?? finding.sourceResultId}`;
const findings = byRule.get(this.ruleKey(finding)) ?? new Map<string, RegulatoryControlFinding>();
if (!findings.has(identity)) findings.set(identity, { resultProjectionId: finding.resultProjectionId, sourceKind: finding.sourceKind,
sourceResultId: finding.sourceResultId, sourceRuleId: finding.sourceRuleId, policyScope: finding.policyScope });
byRule.set(this.ruleKey(finding), findings);
}
// Control titles come from the newest succeeded run of each rule that retrieved the control.
const titles = new Map<string, Map<string, RegulatoryMappingCandidate>>();
for (const run of await this.store.listRegulatoryMappingRuns()) {
if (run.status !== 'succeeded' || !byRule.has(run.ruleKey)) continue;
const known = titles.get(run.ruleKey) ?? new Map<string, RegulatoryMappingCandidate>();
for (const candidate of run.candidates) if (!known.has(candidate.controlId)) known.set(candidate.controlId, candidate);
titles.set(run.ruleKey, known);
}
const controls = new Map<string, { item: RegulatoryControlOverviewItem; findings: Map<string, RegulatoryControlFinding> }>();
const covered = new Set<string>();
for (const [ruleKey, findings] of byRule) {
for (const controlId of acceptedControlIds(await this.store.listRegulatoryMappingDecisions(ruleKey))) {
const candidate = titles.get(ruleKey)?.get(controlId);
const entry = controls.get(controlId) ?? { findings: new Map(), item: {
controlId, annexAControlId: candidate?.annexAControlId ?? `A.${controlId}`, findings: [],
...(candidate?.title ? { title: candidate.title } : {}),
...(regulatoryControlTheme(controlId) ? { theme: regulatoryControlTheme(controlId) } : {}) } };
if (!entry.item.title && candidate?.title) entry.item.title = candidate.title;
for (const [identity, finding] of findings) { entry.findings.set(identity, finding); covered.add(identity); }
controls.set(controlId, entry);
}
}
return {
version: 1, projectId, scope: { assessmentIds: scope.assessmentIds, scanRunIds: scope.scanRunIds }, findingCount: covered.size,
controls: [...controls.values()].map(({ item, findings }) => ({ ...item, findings: [...findings.values()] }))
.sort((left, right) => right.findings.length - left.findings.length
|| left.controlId.localeCompare(right.controlId, 'en', { numeric: true }))
};
}
/**
* Accepts the first proposals of a finished mapping, in the model's order. A control that already has a
* decision keeps it, so a manual reject is never overridden; a failure here never fails the mapping.
*/
private async autoAcceptFirstProposals(run: RegulatoryMappingRun, result: RegulatoryMappingResult): Promise<void> {
if (result.outcome !== 'mapped') return;
try {
const decided = new Set((await this.store.listRegulatoryMappingDecisions(run.ruleKey)).map(item => item.controlId));
for (const proposal of result.mappings.slice(0, AUTO_ACCEPTED_PROPOSALS)) {
if (decided.has(proposal.controlId)) continue;
await this.store.createRegulatoryMappingDecision({
version: 1, id: `regulatory-decision-${randomUUID()}`, ruleKey: run.ruleKey, sourceTool: run.sourceTool,
...(run.sourceRuleId ? { sourceRuleId: run.sourceRuleId } : {}), mappingId: run.id, controlId: proposal.controlId,
decision: 'accepted', comment: AUTO_ACCEPT_COMMENT, createdAt: this.now().toISOString()
});
}
} catch { /* A concurrent manual decision wins; the mapping itself has succeeded. */ }
}
// The global sharing key: the rule identity `tool:ruleId`, shared across every tenant.
// Rules without an id fall back to a stable hash of the non-personal check title so
// identical findings still share, while never keying on tenant or occurrence.
@ -287,17 +362,17 @@ export class RegulatoryMappingService {
}
private async claim(finding: UnifiedResultProjection, forceRegeneration: boolean) {
return this.repository.claimRegulatoryMappingRun(this.queuedRun(finding), forceRegeneration);
return this.store.claimRegulatoryMappingRun(this.queuedRun(finding), forceRegeneration);
}
private async validateBatchScope(projectId: string, requested: RegulatoryMappingBatchScope): Promise<RegulatoryMappingBatchScope> {
if (!await this.repository.getProject(projectId)) throw new RepositoryNotFoundError('The selected project does not exist.');
if (!await this.read.getProject(projectId)) throw new RepositoryNotFoundError('The selected project does not exist.');
const scope = normalizeRegulatoryMappingBatchScope(requested);
if (!scope.assessmentIds.length && !scope.scanRunIds.length) throw new RepositoryValidationError('A selected timeslot scope is required.');
const assessments = await this.repository.listAssessments(projectId);
const assessments = await this.read.listAssessments(projectId);
const allowedAssessmentIds = new Set(assessments.map(item => item.id));
if (scope.assessmentIds.some(id => !allowedAssessmentIds.has(id))) throw new RepositoryValidationError('The batch scope contains an assessment outside this project.');
const scanRuns = await this.repository.listProjectScanRuns(projectId);
const scanRuns = await this.read.listProjectScanRuns(projectId);
const allowedRuns = new Map(scanRuns.filter(item => !item.supersededByScanRunId).map(item => [item.id, item]));
if (scope.scanRunIds.some(id => !allowedRuns.has(id))) throw new RepositoryValidationError('The batch scope contains an unavailable scan run.');
if (scope.assessmentIds.length && scope.scanRunIds.some(id => !scope.assessmentIds.includes(allowedRuns.get(id)!.assessmentId))) {
@ -321,7 +396,7 @@ export class RegulatoryMappingService {
const items: UnifiedResultProjection[] = [];
let expectedTotal: number | undefined;
for (let offset = 0; ; offset += BATCH_PAGE_SIZE) {
const page = await this.repository.queryUnifiedResults({ ...query, offset, limit: BATCH_PAGE_SIZE });
const page = await this.read.queryUnifiedResults({ ...query, offset, limit: BATCH_PAGE_SIZE });
expectedTotal ??= page.total;
if (page.total !== expectedTotal) throw new RepositoryConflictError('The filtered result set changed while the ISO mapping batch was being prepared.');
items.push(...page.items);
@ -333,7 +408,7 @@ export class RegulatoryMappingService {
private async processBatch(queued: RegulatoryMappingBatchRun): Promise<void> {
const startedAt = this.now().toISOString();
let run = await this.repository.updateRegulatoryMappingBatchRun({ ...queued, status: 'running', startedAt, updatedAt: startedAt });
let run = await this.store.updateRegulatoryMappingBatchRun({ ...queued, status: 'running', startedAt, updatedAt: startedAt });
try {
const results = (await this.queryBatchResults(run.projectId, run)).slice()
.sort((left, right) => left.resultProjectionId.localeCompare(right.resultProjectionId));
@ -360,24 +435,24 @@ export class RegulatoryMappingService {
this.track(completion.then(() => undefined));
scheduled.push(completion);
}
run = await this.repository.updateRegulatoryMappingBatchRun({ ...run, counts, updatedAt: this.now().toISOString() });
run = await this.store.updateRegulatoryMappingBatchRun({ ...run, counts, updatedAt: this.now().toISOString() });
let progress = Promise.resolve();
const completions = scheduled.map(completion => completion.then(status => {
progress = progress.then(async () => {
if (status === 'succeeded') counts.succeededRuleCount += 1;
else counts.failedRuleCount += 1;
run = await this.repository.updateRegulatoryMappingBatchRun({ ...run, counts: { ...counts }, updatedAt: this.now().toISOString() });
run = await this.store.updateRegulatoryMappingBatchRun({ ...run, counts: { ...counts }, updatedAt: this.now().toISOString() });
});
return progress;
}));
await Promise.all(completions);
await progress;
const completedAt = this.now().toISOString();
await this.repository.updateRegulatoryMappingBatchRun({ ...run, status: 'completed', counts, updatedAt: completedAt, completedAt });
await this.store.updateRegulatoryMappingBatchRun({ ...run, status: 'completed', counts, updatedAt: completedAt, completedAt });
} catch (error) {
const completedAt = this.now().toISOString();
try {
await this.repository.updateRegulatoryMappingBatchRun({
await this.store.updateRegulatoryMappingBatchRun({
...run,
status: 'failed',
updatedAt: completedAt,
@ -406,8 +481,9 @@ export class RegulatoryMappingService {
private async finding(projectId: string, resultProjectionId: string) {
if (!resultProjectionId?.trim()) throw new RepositoryValidationError('A resultProjectionId is required.');
const finding = await this.repository.getUnifiedResultById(resultProjectionId);
if (!finding || finding.projectId !== projectId) throw new RepositoryNotFoundError('The selected finding does not exist in this project.');
// The Result DB row carries no real scope ids; the repository scopes the lookup to the project.
const finding = await this.read.getUnifiedResultById(resultProjectionId, projectId);
if (!finding) throw new RepositoryNotFoundError('The selected finding does not exist in this project.');
return finding;
}
@ -466,7 +542,7 @@ export class RegulatoryMappingService {
const candidates = await this.groupCandidates(retrieval.candidates);
if (!candidates.length) throw new RegulatoryMappingServiceError('regulatory_corpus_empty', 'The active regulatory corpus returned no eligible controls.', 503);
const startedAt = this.now().toISOString();
run = await this.repository.saveRegulatoryMappingRun({
run = await this.store.saveRegulatoryMappingRun({
...queued,
status: 'running',
preparedQuery: retrieval.preparedQuery,
@ -485,7 +561,7 @@ export class RegulatoryMappingService {
const errors = regulatoryMappingResultValidationErrors(grounded, allowed);
if (errors.length) throw new RegulatoryMappingServiceError('regulatory_mapping_invalid_output', errors.join(' '), 502);
const completedAt = this.now().toISOString();
await this.repository.saveRegulatoryMappingRun({
await this.store.saveRegulatoryMappingRun({
...run,
status: 'succeeded',
result: grounded as RegulatoryMappingResult,
@ -493,13 +569,14 @@ export class RegulatoryMappingService {
updatedAt: completedAt,
completedAt
});
await this.autoAcceptFirstProposals(run, grounded as RegulatoryMappingResult);
return 'succeeded';
} catch (error) {
const completedAt = this.now().toISOString();
const failure = safeFailure(error);
const detail = safeFailureDetail(error);
try {
await this.repository.saveRegulatoryMappingRun({
await this.store.saveRegulatoryMappingRun({
...run, status: 'failed', updatedAt: completedAt, completedAt, errorCode: failure,
...(detail ? { errorDetail: detail } : {})
});

View File

@ -4,7 +4,7 @@ import type {
RegulatoryRetrievalCandidate,
RegulatoryRetrievalRequest,
RegulatoryRetriever
} from '../../src/domain/regulatory-rag';
} from '../../src/compliance/regulatory-rag';
import type { TextEmbeddingClient } from './embedding-client';
import { chunkRegulatoryControl, regulatoryChunkEmbeddingText, validateRegulatoryControlDocument } from './regulatory-chunker';
import type { RegulatoryChunkIndex } from './qdrant-regulatory-index';

View File

@ -2,7 +2,7 @@ import type {
RegulatoryRetrievalCandidate,
RegulatoryRetrievalFilters,
RegulatoryRetriever
} from '../../src/domain/regulatory-rag';
} from '../../src/compliance/regulatory-rag';
export interface RegulatoryExpectedControl {
framework: string;

View File

@ -23,9 +23,7 @@ import { createPostgresReportReadRuntime, memoryReportReadRuntime, type ReportRe
import { createRemediationRuntime } from './remediation/remediation-runtime';
import { createLiteLlmClientFromEnvironment } from './ai/litellm-client';
import { AiOverviewService } from './ai/ai-overview-service';
import { createRegulatoryRagRuntime } from './regulatory/regulatory-rag-runtime';
import { RegulatoryMappingService } from './regulatory/regulatory-mapping-service';
import { RegulatoryCorpusUploadService } from './regulatory/regulatory-corpus-upload-service';
import { createComplianceEngineRuntime } from './compliance/compliance-engine-runtime';
function boundedInteger(value: string | undefined, fallback: number, minimum: number, maximum: number, name: string): number {
if (value === undefined || value.trim() === '') return fallback;
@ -90,39 +88,13 @@ async function main(): Promise<void> {
leaseDurationMs: boundedInteger(process.env.ASSESSOR_AI_JOB_LEASE_MS, 5 * 60_000, 10_000, 30 * 60_000, 'ASSESSOR_AI_JOB_LEASE_MS')
});
await aiOverviewService.recoverInterruptedRuns();
let regulatoryMappingService: RegulatoryMappingService;
let rag: ReturnType<typeof createRegulatoryRagRuntime> | undefined;
let regulatoryDisabledReason: string | undefined;
try {
const corpusId = process.env.ASSESSOR_RAG_ACTIVE_CORPUS_ID?.trim();
const corpusVersion = process.env.ASSESSOR_RAG_ACTIVE_CORPUS_VERSION?.trim();
rag = createRegulatoryRagRuntime();
regulatoryMappingService = new RegulatoryMappingService(runtime.repository, {
findingRetrieval: rag.findingRetrieval,
index: rag.index,
embeddingModel: rag.embeddingModel,
client: aiClient,
corpusId,
corpusVersion,
...(!aiClient ? { disabledReason: 'Work LiteLLM is not configured.' } : {})
});
} catch (error) {
regulatoryDisabledReason = error instanceof Error ? error.message : 'Regulatory mapping is unavailable.';
regulatoryMappingService = new RegulatoryMappingService(runtime.repository, {
disabledReason: regulatoryDisabledReason
});
}
await regulatoryMappingService.recoverInterruptedRuns();
const regulatoryCorpusUploadService = new RegulatoryCorpusUploadService({
root: join(artifactRoot, 'regulatory-corpora'),
ingestion: rag?.ingestion,
countIndexed: rag ? (corpusId, corpusVersion) => rag!.index.count({ corpusId, corpusVersion }) : undefined,
pruneIndexed: rag ? (corpusId, corpusVersion) => rag!.index.deleteOtherCorpusVersions(corpusId, corpusVersion) : undefined,
mapping: regulatoryMappingService,
embeddingModel: rag?.embeddingModel,
disabledReason: regulatoryDisabledReason
// The Compliance Engine runs beside ASSESSOR with its own store and reads the Core only through its read-only port.
const complianceEngine = await createComplianceEngineRuntime({
repository: runtime.repository,
persistence: runtime.persistence,
aiClient,
artifactRoot
});
await regulatoryCorpusUploadService.initialize();
const artifactStore = new FileSystemBackendArtifactStore(artifactRoot);
const mitreCatalogService = new MitreCatalogService(join(artifactRoot, 'reference-data', 'mitre-enterprise.json'));
const gpoBackupSubmissionService = new GpoBackupSubmissionService(
@ -186,8 +158,9 @@ async function main(): Promise<void> {
gpoPolicyFindingService,
gpoPolicyAnalysisOverviewService,
aiOverviewService,
regulatoryMappingService,
regulatoryCorpusUploadService,
regulatoryMappingService: complianceEngine.mappingService,
regulatoryCorpusUploadService: complianceEngine.corpusUploadService,
complianceExport: complianceEngine.store,
isoUploadToken: process.env.ASSESSOR_ISO_UPLOAD_TOKEN?.trim(),
automaticGpoAnalysis,
importExecutor
@ -204,11 +177,12 @@ async function main(): Promise<void> {
if (shuttingDown) return;
shuttingDown = true;
console.log(`${signal}: ASSESSOR wird beendet.`);
void Promise.all([gpoJobRunner.stop(), gpoArtifactReconciliationRunner.stop(), aiOverviewService.close(), regulatoryCorpusUploadService.stop()]).then(() => regulatoryMappingService.close()).then(() => {
void Promise.all([gpoJobRunner.stop(), gpoArtifactReconciliationRunner.stop(), aiOverviewService.close(), complianceEngine.stop()]).then(() => {
server.close(async error => {
try {
await reportRuntime?.close();
await remediationRuntime?.close();
await complianceEngine.close();
await runtime.close();
} catch (closeError) {
console.error(closeError);

View File

@ -36,8 +36,6 @@ import type { EnvironmentObservation, EnvironmentSnapshot, EnvironmentSnapshotQu
import { environmentCoverage } from '../../src/domain/environment-context';
import type { AiOverviewRun } from '../../src/domain/ai-overview';
import { aiOverviewRunValidationErrors } from '../../src/domain/ai-overview';
import type { RegulatoryMappingBatchRun, RegulatoryMappingDecision, RegulatoryMappingRun } from '../../src/domain/regulatory-mapping';
import { regulatoryMappingBatchRunValidationErrors, regulatoryMappingDecisionValidationErrors, regulatoryMappingRunValidationErrors } from '../../src/domain/regulatory-mapping';
import { storedPolicyFindingRunValidationErrors } from '../../src/domain/policy-finding';
import { latestReferenceRuns, type ReferenceRecognitionRun, type ReferenceCatalogSnapshot } from '../../src/domain/reference-recognition';
import { validateReferenceRun } from '../../src/persistence/reference-run-validation';
@ -278,7 +276,7 @@ function isRepositoryError(error: unknown): error is Error {
|| error instanceof ImportSessionStateError;
}
function translateDatabaseError(error: unknown): Error {
export function translateDatabaseError(error: unknown): Error {
if (isRepositoryError(error)) return error;
const code = typeof error === 'object' && error && 'code' in error ? String(error.code) : '';
if (['23505', '40001', '40P01'].includes(code)) return new RepositoryConflictError('Die Daten wurden parallel geändert oder verletzen eine Eindeutigkeitsregel.');
@ -709,164 +707,6 @@ export class PostgresAssessorRepository implements AssessorRepository {
`, [projectId, scopeKey ?? null]));
}
async getRegulatoryMappingRun(id: string): Promise<RegulatoryMappingRun | null> {
return dataRow(await this.pool.query<DataRow<RegulatoryMappingRun>>(
'SELECT data FROM assessor_regulatory_mappings WHERE id = $1', [id]
));
}
async claimRegulatoryMappingRun(run: RegulatoryMappingRun, forceRegeneration: boolean): Promise<{ run: RegulatoryMappingRun; claimed: boolean }> {
const errors = regulatoryMappingRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
return this.mutate(async client => {
const inserted = await client.query(`
INSERT INTO assessor_regulatory_mappings
(id, rule_key, source_tool, source_rule_id, run_status, query_hash, corpus_id, corpus_version,
embedding_model, retrieval_version, prompt_version, output_schema_version, model, created_at, updated_at, data)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16::jsonb)
ON CONFLICT DO NOTHING
RETURNING id
`, [run.id, run.ruleKey, run.sourceTool, run.sourceRuleId ?? null, run.status, run.queryHash, run.corpusId,
run.corpusVersion, run.embeddingModel, run.retrievalVersion, run.promptVersion, run.outputSchemaVersion,
run.model, run.createdAt, run.updatedAt, json(run)]);
if (inserted.rowCount) return { run: clone(run), claimed: true };
const existing = dataRow(await client.query<DataRow<RegulatoryMappingRun>>(
'SELECT data FROM assessor_regulatory_mappings WHERE id = $1 FOR UPDATE', [run.id]
));
if (!existing) throw new RepositoryConflictError('Regulatory mapping identity conflicted with another pipeline tuple.');
if (['queued', 'running'].includes(existing.status) || existing.status === 'succeeded' && !forceRegeneration) {
return { run: existing, claimed: false };
}
await client.query(`
UPDATE assessor_regulatory_mappings SET
run_status = $2, query_hash = $3, created_at = $4, updated_at = $5, data = $6::jsonb
WHERE id = $1
`, [run.id, run.status, run.queryHash, run.createdAt, run.updatedAt, json(run)]);
return { run: clone(run), claimed: true };
});
}
async saveRegulatoryMappingRun(run: RegulatoryMappingRun): Promise<RegulatoryMappingRun> {
const errors = regulatoryMappingRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
return this.mutate(async client => {
await client.query(`
INSERT INTO assessor_regulatory_mappings
(id, rule_key, source_tool, source_rule_id, run_status, query_hash, corpus_id, corpus_version,
embedding_model, retrieval_version, prompt_version, output_schema_version, model, created_at, updated_at, data)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16::jsonb)
ON CONFLICT (id) DO UPDATE SET
run_status = excluded.run_status, updated_at = excluded.updated_at, data = excluded.data
`, [run.id, run.ruleKey, run.sourceTool, run.sourceRuleId ?? null, run.status, run.queryHash, run.corpusId,
run.corpusVersion, run.embeddingModel, run.retrievalVersion, run.promptVersion, run.outputSchemaVersion,
run.model, run.createdAt, run.updatedAt, json(run)]);
return clone(run);
});
}
async listRegulatoryMappingRuns(): Promise<RegulatoryMappingRun[]> {
return dataRows(await this.pool.query<DataRow<RegulatoryMappingRun>>(
'SELECT data FROM assessor_regulatory_mappings ORDER BY created_at DESC, id DESC'
));
}
async createRegulatoryMappingBatchRun(run: RegulatoryMappingBatchRun): Promise<RegulatoryMappingBatchRun> {
const errors = regulatoryMappingBatchRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
return this.mutate(async client => {
const inserted = await client.query(`
INSERT INTO assessor_regulatory_mapping_batches
(id, project_id, scope_key, filter_hash, idempotency_key, run_status, created_at, updated_at, data)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb)
ON CONFLICT DO NOTHING
RETURNING data
`, [run.id, run.projectId, run.scopeKey, run.filterHash, run.idempotencyKey, run.status,
run.createdAt, run.updatedAt, json(run)]);
if (inserted.rowCount) return clone(run);
const existing = dataRow(await client.query<DataRow<RegulatoryMappingBatchRun>>(`
SELECT data FROM assessor_regulatory_mapping_batches
WHERE project_id = $1 AND (idempotency_key = $2 OR (scope_key = $3 AND run_status IN ('queued', 'running')))
ORDER BY (idempotency_key = $2) DESC, created_at DESC, id DESC
LIMIT 1
`, [run.projectId, run.idempotencyKey, run.scopeKey]));
if (!existing) throw new RepositoryConflictError('Regulatory mapping batch conflicted with another active request.');
return existing;
});
}
async updateRegulatoryMappingBatchRun(run: RegulatoryMappingBatchRun): Promise<RegulatoryMappingBatchRun> {
const errors = regulatoryMappingBatchRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
return this.mutate(async client => {
const existing = dataRow(await client.query<DataRow<RegulatoryMappingBatchRun>>(
'SELECT data FROM assessor_regulatory_mapping_batches WHERE id = $1 FOR UPDATE', [run.id]
));
if (!existing) throw new RepositoryNotFoundError('Regulatory mapping batch does not exist.');
if (existing.projectId !== run.projectId || existing.scopeKey !== run.scopeKey || existing.idempotencyKey !== run.idempotencyKey) {
throw new RepositoryConflictError('Regulatory mapping batch identity is immutable.');
}
if (['completed', 'failed'].includes(existing.status)) throw new RepositoryConflictError('A completed regulatory mapping batch is immutable.');
const allowed = existing.status === 'queued' ? ['running', 'failed'] : ['running', 'completed', 'failed'];
if (!allowed.includes(run.status)) throw new RepositoryConflictError(`Invalid regulatory mapping batch transition from ${existing.status} to ${run.status}.`);
await client.query(`
UPDATE assessor_regulatory_mapping_batches SET run_status = $2, updated_at = $3, data = $4::jsonb
WHERE id = $1
`, [run.id, run.status, run.updatedAt, json(run)]);
return clone(run);
});
}
async listRegulatoryMappingBatchRuns(projectId: string, scopeKey?: string): Promise<RegulatoryMappingBatchRun[]> {
return dataRows(await this.pool.query<DataRow<RegulatoryMappingBatchRun>>(`
SELECT data FROM assessor_regulatory_mapping_batches
WHERE project_id = $1 AND ($2::text IS NULL OR scope_key = $2)
ORDER BY created_at DESC, id DESC
`, [projectId, scopeKey ?? null]));
}
async createRegulatoryMappingDecision(
decision: RegulatoryMappingDecision,
expectedLatestDecisionId?: string
): Promise<RegulatoryMappingDecision> {
const errors = regulatoryMappingDecisionValidationErrors(decision);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
return this.mutate(async client => {
const run = dataRow(await client.query<DataRow<RegulatoryMappingRun>>(
'SELECT data FROM assessor_regulatory_mappings WHERE id = $1 FOR UPDATE', [decision.mappingId]
));
if (!run || run.ruleKey !== decision.ruleKey || run.status !== 'succeeded') {
throw new RepositoryNotFoundError('Completed regulatory mapping does not exist for this rule.');
}
if (!run.candidates.some(candidate => candidate.controlId === decision.controlId)) {
throw new RepositoryValidationError('Decision control was not a grounded candidate.');
}
const latest = dataRow(await client.query<DataRow<RegulatoryMappingDecision>>(`
SELECT data FROM assessor_regulatory_mapping_decisions
WHERE rule_key = $1 AND control_id = $2
ORDER BY created_at DESC, id DESC LIMIT 1
`, [decision.ruleKey, decision.controlId]));
if ((expectedLatestDecisionId ?? undefined) !== (latest?.id ?? undefined)) {
throw new RepositoryConflictError('Regulatory mapping decision changed before this update.');
}
const stored = { ...decision, ...(latest ? { previousDecisionId: latest.id } : {}) };
await client.query(`
INSERT INTO assessor_regulatory_mapping_decisions
(id, rule_key, source_tool, source_rule_id, mapping_id, control_id, decision, previous_decision_id, created_at, data)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb)
`, [stored.id, stored.ruleKey, stored.sourceTool, stored.sourceRuleId ?? null, stored.mappingId, stored.controlId,
stored.decision, stored.previousDecisionId ?? null, stored.createdAt, json(stored)]);
return clone(stored);
});
}
async listRegulatoryMappingDecisions(ruleKey: string): Promise<RegulatoryMappingDecision[]> {
return dataRows(await this.pool.query<DataRow<RegulatoryMappingDecision>>(`
SELECT data FROM assessor_regulatory_mapping_decisions
WHERE rule_key = $1
ORDER BY created_at DESC, id DESC
`, [ruleKey]));
}
async beginImport(start: ImportSessionStart): Promise<ImportSession> {
if (!start.sessionId.trim()) throw new RepositoryValidationError('Eine Importsitzung benötigt eine ID.');
if (this.activeImportSessions.has(start.sessionId)) throw new RepositoryConflictError(`Importsitzung ${start.sessionId} ist bereits aktiv.`);
@ -1659,10 +1499,13 @@ export class PostgresAssessorRepository implements AssessorRepository {
return deriveUnifiedResultFacets(await this.allUnifiedResults(query), query);
}
async getUnifiedResultById(resultProjectionId: string): Promise<UnifiedResultProjection | null> {
async getUnifiedResultById(resultProjectionId: string, projectId?: string): Promise<UnifiedResultProjection | null> {
await this.ensureResultDb();
const result = await this.pool.query<{ row_data: UnifiedResultProjection } & QueryResultRow>(
'SELECT row_data FROM assessor_result_db_rows WHERE result_projection_id = $1', [resultProjectionId]);
const result = projectId === undefined
? await this.pool.query<{ row_data: UnifiedResultProjection } & QueryResultRow>(
'SELECT row_data FROM assessor_result_db_rows WHERE result_projection_id = $1', [resultProjectionId])
: await this.pool.query<{ row_data: UnifiedResultProjection } & QueryResultRow>(
'SELECT row_data FROM assessor_result_db_rows WHERE result_projection_id = $1 AND project_id = $2', [resultProjectionId, projectId]);
return result.rows[0] ? removeResultDbScopeIdentifiers(result.rows[0].row_data) : null;
}
@ -2936,13 +2779,7 @@ export class PostgresAssessorRepository implements AssessorRepository {
policySnapshotAggregations: await this.listPolicySnapshotAggregations(projectId),
policyEvaluations: await this.listPolicyEvaluations(projectId),
policyFindingRuns,
aiOverviewRuns: (await this.listAiOverviewRuns(projectId)).filter(item => item.status === 'succeeded'),
regulatoryMappingBatchRuns: await this.listRegulatoryMappingBatchRuns(projectId),
// Regulatory mappings and decisions are global reference data, not project-scoped.
regulatoryMappingRuns: (await this.listRegulatoryMappingRuns()).filter(item => item.status === 'succeeded'),
regulatoryMappingDecisions: dataRows(await this.pool.query<DataRow<RegulatoryMappingDecision>>(
'SELECT data FROM assessor_regulatory_mapping_decisions ORDER BY created_at, id'
))
aiOverviewRuns: (await this.listAiOverviewRuns(projectId)).filter(item => item.status === 'succeeded')
};
}

View File

@ -16,7 +16,7 @@ import type { EnvironmentSnapshot, EnvironmentSnapshotQuery } from '../domain/en
import type { ClientInformationQuery, ClientInformationResult } from '../domain/client-information';
import type { ImportedDataset } from '../domain/dataset';
import type { MicrosoftSecurityBaselineSelectionContext } from '../domain/microsoft-security-baseline';
import type { RegulatoryCorpusStatus } from '../domain/regulatory-corpus-management';
import type { RegulatoryCorpusStatus } from '../compliance/regulatory-corpus-management';
import type { ImportBatchPreview, ImportBatchSelection } from '../domain/import-workflow';
import type { ResultDbMaterializationStatus } from '../domain/result-db-materialization';
import {
@ -62,7 +62,8 @@ import {
type RegulatoryMappingBatchScope,
type RegulatoryMappingCreateRequest,
type RegulatoryMappingDecisionCreateRequest,
type RegulatoryMappingResponse
type RegulatoryMappingResponse,
type RegulatoryControlOverviewResponse
} from './assessor-api-contract';
export class AssessorApiError extends Error {
@ -266,6 +267,13 @@ export class AssessorApiClient {
}));
}
getRegulatoryControlOverview(projectId: string, scope: { assessmentIds: string[]; scanRunIds: string[] }): Promise<RegulatoryControlOverviewResponse> {
return this.request(unifiedQueryPath(`/projects/${encodeURIComponent(projectId)}/regulatory-control-overview`, {
assessmentIds: scope.assessmentIds,
scanRunIds: scope.scanRunIds
}));
}
startRegulatoryMappingBatch(projectId: string, request: RegulatoryMappingBatchCreateRequest): Promise<RegulatoryMappingBatchResponse> {
return this.request(`/projects/${encodeURIComponent(projectId)}/regulatory-mapping-batches`, {
method: 'POST', body: JSON.stringify(request)

View File

@ -26,8 +26,9 @@ export type {
RegulatoryMappingBatchScope,
RegulatoryMappingCreateRequest,
RegulatoryMappingDecisionCreateRequest,
RegulatoryMappingResponse
} from '../domain/regulatory-mapping';
RegulatoryMappingResponse,
RegulatoryControlOverviewResponse
} from '../compliance/regulatory-mapping';
export const ASSESSOR_API_PREFIX = '/api/v1';
export const ASSESSOR_MUTATION_HEADER = 'X-Assessor-Request';

View File

@ -5,6 +5,8 @@ export function requestActivity(path: string, method = 'GET'): { area: string; l
if (route.includes('/work-packages')) return { area: 'Remediation Engine', label: 'Preparing work packages' };
if (route.includes('/assessment-context')) return { area: 'Context Engine', label: 'Loading and calculating assessment context' };
if (route.includes('/report-runs')) return { area: 'Report Engine', label: 'Generating assessment report' };
const compliance = complianceActivity(route, method);
if (compliance) return { area: 'Compliance Engine', label: compliance };
if (route.includes('/mitre-attack')) return { area: 'Core Engine', label: route.endsWith('/source') ? 'Downloading MITRE source' : route.endsWith('/refresh') ? 'Updating MITRE catalog' : 'Loading MITRE catalog' };
const resources: [RegExp, string][] = [
[/db-structure/, 'database structure'], [/references/, 'reference recognition'],
@ -23,3 +25,15 @@ export function requestActivity(path: string, method = 'GET'): { area: string; l
const action = method === 'DELETE' ? 'Deleting' : method === 'GET' ? 'Loading' : 'Processing';
return { area: 'Core Engine', label: `${action} ${noun}` };
}
/** Compliance Engine routes; checked before the generic project patterns so they never read as client work. */
function complianceActivity(route: string, method: string): string | undefined {
const write = method !== 'GET';
if (route.includes('/regulatory-control-overview')) return 'Loading ISO control overview';
if (route.includes('/regulatory-mapping-batches')) return write ? 'Starting ISO mapping batch' : 'Loading ISO mapping batch status';
if (route.includes('/regulatory-mapping-runs')) return 'Generating ISO control proposals';
if (route.includes('/regulatory-mapping-decisions')) return 'Saving ISO mapping decision';
if (route.includes('/regulatory-mappings/')) return 'Loading ISO mapping';
if (route.endsWith('/reference-data/iso-corpus')) return write ? 'Uploading ISO corpus' : 'Loading ISO corpus status';
return undefined;
}

View File

@ -5,11 +5,12 @@ export const ENGINES = [
{ id: 'core', label: 'Core Engine', required: true },
{ id: 'context', label: 'Context Engine', required: false },
{ id: 'report', label: 'Report Engine', required: false },
{ id: 'remediation', label: 'Remediation Engine', required: false }
{ id: 'remediation', label: 'Remediation Engine', required: false },
{ id: 'compliance', label: 'Compliance Engine', required: false }
] as const;
export type EngineId = typeof ENGINES[number]['id'];
export const ENGINE_PREFERENCES_KEY = 'ASSESSOR.engines.v1';
const defaults = Object.freeze({ core: true, context: true, report: true, remediation: true });
const defaults = Object.freeze({ core: true, context: true, report: true, remediation: true, compliance: true });
type Preferences = Readonly<Record<EngineId, boolean>>;
let snapshot: Preferences | undefined;
const listeners = new Set<() => void>();
@ -18,7 +19,8 @@ export function readEnginePreferences(): Preferences {
if (snapshot) return snapshot;
try {
const saved = JSON.parse(window.localStorage.getItem(ENGINE_PREFERENCES_KEY) ?? '{}');
snapshot = Object.freeze({ core: true, context: saved?.context !== false, report: saved?.report !== false, remediation: saved?.remediation !== false });
snapshot = Object.freeze({ core: true, context: saved?.context !== false, report: saved?.report !== false, remediation: saved?.remediation !== false,
compliance: saved?.compliance !== false });
} catch { snapshot = defaults; }
return snapshot;
}

View File

@ -0,0 +1,42 @@
import type { AssessorRepository } from '../persistence/assessor-repository';
import type { RegulatoryMappingBatchRun, RegulatoryMappingDecision, RegulatoryMappingRun } from './regulatory-mapping';
/**
* The only Core reads the Compliance Engine performs (AGENTS.md, "Core Engine and engines"). The engine
* never receives a repository method that writes Core data.
*/
export type ComplianceReadPort = Pick<AssessorRepository,
'getUnifiedResultById' | 'queryUnifiedResults' | 'getProject' | 'listProjects' | 'listAssessments' | 'listProjectScanRuns'>;
export function complianceReadPortFrom(repository: ComplianceReadPort): ComplianceReadPort {
return {
getUnifiedResultById: (resultProjectionId, projectId) => repository.getUnifiedResultById(resultProjectionId, projectId),
queryUnifiedResults: query => repository.queryUnifiedResults(query),
getProject: projectId => repository.getProject(projectId),
listProjects: () => repository.listProjects(),
listAssessments: projectId => repository.listAssessments(projectId),
listProjectScanRuns: projectId => repository.listProjectScanRuns(projectId)
};
}
/** The engine's project data, delivered beside the Core project export. */
export interface ComplianceProjectExport {
regulatoryMappingBatchRuns: RegulatoryMappingBatchRun[];
/** Mappings and decisions are global and keyed by scanner rule, not by project. */
regulatoryMappingRuns: RegulatoryMappingRun[];
regulatoryMappingDecisions: RegulatoryMappingDecision[];
}
/** The engine's own storage: mapping runs, accept/reject decisions and batches. */
export interface ComplianceStore {
getRegulatoryMappingRun(id: string): Promise<RegulatoryMappingRun | null>;
claimRegulatoryMappingRun(run: RegulatoryMappingRun, forceRegeneration: boolean): Promise<{ run: RegulatoryMappingRun; claimed: boolean }>;
saveRegulatoryMappingRun(run: RegulatoryMappingRun): Promise<RegulatoryMappingRun>;
listRegulatoryMappingRuns(): Promise<RegulatoryMappingRun[]>;
createRegulatoryMappingBatchRun(run: RegulatoryMappingBatchRun): Promise<RegulatoryMappingBatchRun>;
updateRegulatoryMappingBatchRun(run: RegulatoryMappingBatchRun): Promise<RegulatoryMappingBatchRun>;
listRegulatoryMappingBatchRuns(projectId: string, scopeKey?: string): Promise<RegulatoryMappingBatchRun[]>;
createRegulatoryMappingDecision(decision: RegulatoryMappingDecision, expectedLatestDecisionId?: string): Promise<RegulatoryMappingDecision>;
listRegulatoryMappingDecisions(ruleKey: string): Promise<RegulatoryMappingDecision[]>;
exportProject(projectId: string): Promise<ComplianceProjectExport>;
}

View File

@ -0,0 +1,113 @@
import { RepositoryConflictError, RepositoryNotFoundError, RepositoryValidationError } from '../persistence/repository-errors';
import type { ComplianceProjectExport, ComplianceStore } from './compliance-store';
import {
regulatoryMappingBatchRunValidationErrors,
regulatoryMappingDecisionValidationErrors,
regulatoryMappingRunValidationErrors,
type RegulatoryMappingBatchRun,
type RegulatoryMappingDecision,
type RegulatoryMappingRun
} from './regulatory-mapping';
function clone<T>(value: T): T {
return structuredClone(value);
}
const newestFirst = (left: { createdAt: string; id: string }, right: { createdAt: string; id: string }) =>
right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id);
/** In-memory engine storage for the memory persistence mode and tests. */
export class LocalComplianceStore implements ComplianceStore {
private runs: RegulatoryMappingRun[] = [];
private batches: RegulatoryMappingBatchRun[] = [];
private decisions: RegulatoryMappingDecision[] = [];
async getRegulatoryMappingRun(id: string): Promise<RegulatoryMappingRun | null> {
const run = this.runs.find(item => item.id === id);
return run ? clone(run) : null;
}
async claimRegulatoryMappingRun(run: RegulatoryMappingRun, forceRegeneration: boolean): Promise<{ run: RegulatoryMappingRun; claimed: boolean }> {
const errors = regulatoryMappingRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
const existing = this.runs.find(item => item.id === run.id);
if (existing && (['queued', 'running'].includes(existing.status) || existing.status === 'succeeded' && !forceRegeneration)) {
return { run: clone(existing), claimed: false };
}
const stored = await this.saveRegulatoryMappingRun(run);
return { run: stored, claimed: true };
}
async saveRegulatoryMappingRun(run: RegulatoryMappingRun): Promise<RegulatoryMappingRun> {
const errors = regulatoryMappingRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
const index = this.runs.findIndex(item => item.id === run.id);
if (index >= 0) this.runs[index] = clone(run);
else this.runs.push(clone(run));
return clone(run);
}
async listRegulatoryMappingRuns(): Promise<RegulatoryMappingRun[]> {
return this.runs.map(clone).sort(newestFirst);
}
async createRegulatoryMappingBatchRun(run: RegulatoryMappingBatchRun): Promise<RegulatoryMappingBatchRun> {
const errors = regulatoryMappingBatchRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
const idempotent = this.batches.find(item => item.projectId === run.projectId && item.idempotencyKey === run.idempotencyKey);
if (idempotent) return clone(idempotent);
const active = this.batches.find(item => item.projectId === run.projectId && item.scopeKey === run.scopeKey
&& ['queued', 'running'].includes(item.status));
if (active) return clone(active);
this.batches.push(clone(run));
return clone(run);
}
async updateRegulatoryMappingBatchRun(run: RegulatoryMappingBatchRun): Promise<RegulatoryMappingBatchRun> {
const errors = regulatoryMappingBatchRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
const index = this.batches.findIndex(item => item.id === run.id);
const existing = this.batches[index];
if (!existing) throw new RepositoryNotFoundError('Regulatory mapping batch does not exist.');
if (existing.projectId !== run.projectId || existing.scopeKey !== run.scopeKey || existing.idempotencyKey !== run.idempotencyKey) {
throw new RepositoryConflictError('Regulatory mapping batch identity is immutable.');
}
if (['completed', 'failed'].includes(existing.status)) throw new RepositoryConflictError('A completed regulatory mapping batch is immutable.');
const allowed = existing.status === 'queued' ? ['running', 'failed'] : ['running', 'completed', 'failed'];
if (!allowed.includes(run.status)) throw new RepositoryConflictError(`Invalid regulatory mapping batch transition from ${existing.status} to ${run.status}.`);
this.batches[index] = clone(run);
return clone(run);
}
async listRegulatoryMappingBatchRuns(projectId: string, scopeKey?: string): Promise<RegulatoryMappingBatchRun[]> {
return this.batches.filter(item => item.projectId === projectId && (!scopeKey || item.scopeKey === scopeKey))
.map(clone).reverse();
}
async createRegulatoryMappingDecision(decision: RegulatoryMappingDecision, expectedLatestDecisionId?: string): Promise<RegulatoryMappingDecision> {
const errors = regulatoryMappingDecisionValidationErrors(decision);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
const run = this.runs.find(item => item.id === decision.mappingId);
if (!run || run.ruleKey !== decision.ruleKey || run.status !== 'succeeded') {
throw new RepositoryNotFoundError('Completed regulatory mapping does not exist for this rule.');
}
if (!run.candidates.some(candidate => candidate.controlId === decision.controlId)) throw new RepositoryValidationError('Decision control was not a grounded candidate.');
const latest = this.decisions.filter(item => item.ruleKey === decision.ruleKey && item.controlId === decision.controlId).sort(newestFirst)[0];
if ((expectedLatestDecisionId ?? undefined) !== (latest?.id ?? undefined)) throw new RepositoryConflictError('Regulatory mapping decision changed before this update.');
const stored = clone({ ...decision, ...(latest ? { previousDecisionId: latest.id } : {}) });
this.decisions.push(stored);
return clone(stored);
}
async listRegulatoryMappingDecisions(ruleKey: string): Promise<RegulatoryMappingDecision[]> {
return this.decisions.filter(item => item.ruleKey === ruleKey).map(clone).sort(newestFirst);
}
async exportProject(projectId: string): Promise<ComplianceProjectExport> {
return {
regulatoryMappingBatchRuns: this.batches.filter(item => item.projectId === projectId).map(clone),
regulatoryMappingRuns: this.runs.filter(item => item.status === 'succeeded').map(clone),
regulatoryMappingDecisions: this.decisions.map(clone)
};
}
}

View File

@ -1,6 +1,7 @@
import type { AiOverviewTokenUsage } from './ai-overview';
import type { AiOverviewTokenUsage } from '../domain/ai-overview';
import type { RegulatoryFindingQuery, RegulatorySectionKind } from './regulatory-rag';
import type { UnifiedResultQuery } from './unified-result';
import type { ResultDbFilters } from '../domain/result-db-query';
import type { UnifiedResultProjection } from '../domain/unified-result';
export const REGULATORY_MAPPING_PROMPT_VERSION = '1.2.0';
export const REGULATORY_MAPPING_OUTPUT_SCHEMA_VERSION = 1 as const;
@ -12,8 +13,7 @@ export type RegulatoryMappingConfidence = 'low' | 'medium' | 'high';
export type RegulatoryMappingDecisionValue = 'accepted' | 'rejected';
export type RegulatoryMappingBatchStatus = 'queued' | 'running' | 'completed' | 'failed';
export type RegulatoryMappingBatchFilters = Omit<UnifiedResultQuery,
'audience' | 'projectId' | 'assessmentId' | 'assessmentIds' | 'scanRunId' | 'scanRunIds' | 'offset' | 'limit'>;
export type RegulatoryMappingBatchFilters = ResultDbFilters;
export interface RegulatoryMappingBatchScope {
assessmentIds: string[];
@ -151,6 +151,52 @@ export interface RegulatoryMappingDecision {
createdAt: string;
}
/**
* Control ids whose latest decision is 'accepted'. Each stored decision names the one it replaced
* (`previousDecisionId`), so the latest is the one no other decision replaced; time and id only break
* a tie between unchained entries.
*/
export function acceptedControlIds(decisions: readonly RegulatoryMappingDecision[]): string[] {
const replaced = new Set(decisions.flatMap(item => item.previousDecisionId ? [item.previousDecisionId] : []));
const latest = new Map<string, RegulatoryMappingDecision>();
for (const decision of decisions) {
if (replaced.has(decision.id)) continue;
const current = latest.get(decision.controlId);
if (!current || decision.createdAt > current.createdAt || decision.createdAt === current.createdAt && decision.id > current.id) {
latest.set(decision.controlId, decision);
}
}
return [...latest.values()].filter(item => item.decision === 'accepted').map(item => item.controlId);
}
export type RegulatoryControlTheme = 'Organizational' | 'People' | 'Physical' | 'Technological';
/** ISO/IEC 27002:2022 groups its controls by clause: 5 Organizational, 6 People, 7 Physical, 8 Technological. */
export function regulatoryControlTheme(controlId: string): RegulatoryControlTheme | undefined {
return ({ 5: 'Organizational', 6: 'People', 7: 'Physical', 8: 'Technological' } as const)[Number(controlId.split('.')[0]) as 5 | 6 | 7 | 8];
}
/** A Result DB row named precisely enough to open its Work record. */
export type RegulatoryControlFinding = Pick<UnifiedResultProjection, 'resultProjectionId' | 'sourceKind' | 'sourceResultId' | 'sourceRuleId' | 'policyScope'>;
export interface RegulatoryControlOverviewItem {
controlId: string;
annexAControlId: string;
title?: string;
theme?: RegulatoryControlTheme;
findings: RegulatoryControlFinding[];
}
/** Accepted controls of the deviations in one client timeslot; decisions stay global per scanner rule. */
export interface RegulatoryControlOverviewResponse {
version: 1;
projectId: string;
scope: { assessmentIds: string[]; scanRunIds: string[] };
/** Distinct findings that carry at least one accepted control. */
findingCount: number;
controls: RegulatoryControlOverviewItem[];
}
export interface RegulatoryMappingResponse {
version: 1;
projectId: string;

View File

@ -1,10 +1,10 @@
import type { RegulatoryFindingQuery } from '../../domain/regulatory-rag';
import { REGULATORY_FINDING_QUERY_SCHEMA_VERSION } from '../../domain/regulatory-rag';
import type { UnifiedResultProjection } from '../../domain/unified-result';
import { privacySafeFinding } from '../../domain/privacy-safe-finding';
import { discloseResultDbProjection } from '../../domain/result-db-disclosure';
import catalog from './catalog.json';
import { publicSecurityTopics } from './public-security-topics';
import type { RegulatoryFindingQuery } from './regulatory-rag';
import { REGULATORY_FINDING_QUERY_SCHEMA_VERSION } from './regulatory-rag';
import type { UnifiedResultProjection } from '../domain/unified-result';
import { privacySafeFinding } from '../domain/privacy-safe-finding';
import { discloseResultDbProjection } from '../domain/result-db-disclosure';
import catalog from '../profiles/public-search/catalog.json';
import { publicSecurityTopics } from '../profiles/public-search/public-security-topics';
const MAXIMUM_TITLE_CHARACTERS = 500;
const MAXIMUM_DETAIL_CHARACTERS = 1_200;

View File

@ -0,0 +1,60 @@
import { useEffect, useId, useState } from 'react';
import { AssessorApiClient } from '../../api/assessor-api-client';
import type { BackendStatus } from '../../app/app-state';
import { useEnginePreferences } from '../../app/engine-preferences';
import type { RegulatoryControlFinding, RegulatoryControlOverviewResponse } from '../regulatory-mapping';
import { useRegulatoryDecisionRevision } from './decision-revision';
import './compliance.css';
const assessorApi = new AssessorApiClient();
interface Props {
projectId?: string;
assessmentIds?: readonly string[];
scanRunIds?: readonly string[];
backendStatus: BackendStatus;
onOpenFindings(findings: RegulatoryControlFinding[]): void;
}
type OverviewState = { status: 'idle' | 'loading' } | { status: 'error' } | { status: 'ready'; overview: RegulatoryControlOverviewResponse };
/** Client Info `ISO controls`: accepted controls of the timeslot's deviations, laid out like the Context heatmap. */
export function ClientIsoControls({ projectId, assessmentIds = [], scanRunIds = [], backendStatus, onOpenFindings }: Props) {
const available = useEnginePreferences().compliance;
const revision = useRegulatoryDecisionRevision();
const id = useId();
const [state, setState] = useState<OverviewState>({ status: 'idle' });
const scopeKey = JSON.stringify([projectId, assessmentIds, scanRunIds]);
const enabled = available && backendStatus === 'connected' && Boolean(projectId) && (assessmentIds.length > 0 || scanRunIds.length > 0);
useEffect(() => {
if (!enabled || !projectId) { setState({ status: 'idle' }); return; }
let active = true;
setState({ status: 'loading' });
assessorApi.getRegulatoryControlOverview(projectId, { assessmentIds: [...assessmentIds], scanRunIds: [...scanRunIds] })
.then(overview => { if (active) setState({ status: 'ready', overview }); })
.catch(() => { if (active) setState({ status: 'error' }); });
return () => { active = false; };
}, [enabled, revision, scopeKey]); // eslint-disable-line react-hooks/exhaustive-deps
if (!available || state.status === 'idle') return null;
return <section className="iso-controls" aria-labelledby={`${id}-title`} aria-busy={state.status === 'loading'}>
<header className="iso-controls__header">
<h2 id={`${id}-title`}>ISO controls</h2>
{state.status === 'ready' && <span className="iso-controls__total" aria-label="Unique findings with an accepted ISO control">
Findings: {state.overview.findingCount.toLocaleString('en-US')}</span>}
</header>
{state.status === 'error' && <p role="alert">ISO controls could not be loaded.</p>}
{state.status === 'ready' && !state.overview.controls.length && <p className="iso-controls__empty">No accepted ISO controls in this timeslot.</p>}
{state.status === 'ready' && state.overview.controls.length > 0 && <div className="iso-controls__grid" aria-label="Accepted ISO controls">
{state.overview.controls.map(control => <button key={control.controlId} type="button" className="iso-controls__cell"
data-control={control.controlId}
aria-label={`Open ${control.annexAControlId} findings in Work (${control.findings.length})`}
onClick={() => onOpenFindings(control.findings)}>
{control.theme && <span className="iso-controls__category">{control.theme}</span>}
<strong>{control.annexAControlId}{control.title ? ` · ${control.title}` : ''}</strong>
<span className="iso-controls__amount">{control.findings.length.toLocaleString('en-US')} {control.findings.length === 1 ? 'finding' : 'findings'}</span>
</button>)}
</div>}
</section>;
}

View File

@ -0,0 +1,13 @@
import type { AcceptedRegulatoryControl } from './use-regulatory-mapping';
import './compliance.css';
/** Finding Reader section of the controls accepted for this finding, read like `Description`. */
export function FindingIsoControls({ controls }: { controls: AcceptedRegulatoryControl[] }) {
if (!controls.length) return null;
return <div className="finding-iso-controls" data-iso-controls>
<h4>ISO controls</h4>
<ul>{controls.map(control => <li key={control.controlId}>
<strong>{control.annexAControlId}</strong>{control.title && <span>{control.title}</span>}
</li>)}</ul>
</div>;
}

View File

@ -1,26 +1,36 @@
import { useCallback, useEffect, useState, type FormEvent } from 'react';
import { AssessorApiClient } from '../../api/assessor-api-client';
import type { RegulatoryCorpusStatus } from '../../domain/regulatory-corpus-management';
import { useEnginePreferences } from '../../app/engine-preferences';
import { useBackendWorkActivity } from './use-backend-work-activity';
import { statusPollApi } from './status-poll-client';
import type { RegulatoryCorpusStatus } from '../regulatory-corpus-management';
import { TriangleIcon } from '../../components/TriangleIcon';
const api = new AssessorApiClient();
const MAXIMUM_PDF_BYTES = 32 * 1024 * 1024;
/** Data Hub ISO corpus tile; a switched-off Compliance Engine renders nothing and requests nothing. */
export function IsoCorpusLibrary() {
return useEnginePreferences().compliance ? <IsoCorpusLibraryPanel/> : null;
}
function IsoCorpusLibraryPanel() {
const [status, setStatus] = useState<RegulatoryCorpusStatus | null>(null);
const [iso27001, setIso27001] = useState<File | null>(null);
const [iso27002, setIso27002] = useState<File | null>(null);
const [token, setToken] = useState('');
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
try { setStatus(await api.getIsoCorpusStatus()); setError(null); }
const load = useCallback(async (poll = false) => {
try { setStatus(await (poll ? statusPollApi : api).getIsoCorpusStatus()); setError(null); }
catch (reason) { setError(reason instanceof Error ? reason.message : 'ISO corpus status could not be loaded.'); }
}, []);
useEffect(() => { void load(); }, [load]);
const job = status?.job?.status;
useBackendWorkActivity('Embedding ISO corpus', job === 'running' ? 'running' : job === 'failed' ? 'failed' : job === 'succeeded' ? 'finished' : 'idle');
useEffect(() => {
if (status?.job?.status !== 'running') return;
const interval = setInterval(() => { void load(); }, 2_000);
const interval = setInterval(() => { void load(true); }, 2_000);
return () => clearInterval(interval);
}, [load, status?.job?.status]);

View File

@ -1,11 +1,16 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { AssessorApiClient } from '../../api/assessor-api-client';
import { useEnginePreferences } from '../../app/engine-preferences';
import { useBackendWorkActivity } from './use-backend-work-activity';
import { statusPollApi } from './status-poll-client';
import { Dialog } from '../../components/Dialog/Dialog';
import type { RegulatoryMappingBatchResponse, RegulatoryMappingBatchScope } from '../../domain/regulatory-mapping';
import type { RegulatoryMappingBatchResponse, RegulatoryMappingBatchScope } from '../regulatory-mapping';
const assessorApi = new AssessorApiClient();
export interface RegulatoryMappingBatchController {
/** False while the Compliance Engine is switched off. */
available: boolean;
response?: RegulatoryMappingBatchResponse;
loading: boolean;
starting: boolean;
@ -13,7 +18,10 @@ export interface RegulatoryMappingBatchController {
start(): Promise<void>;
}
export function useRegulatoryMappingBatch(projectId: string | undefined, scope: RegulatoryMappingBatchScope | undefined): RegulatoryMappingBatchController {
export function useRegulatoryMappingBatch(requestedProjectId: string | undefined, scope: RegulatoryMappingBatchScope | undefined): RegulatoryMappingBatchController {
// A switched-off Compliance Engine requests no batch status and offers no batch action.
const available = useEnginePreferences().compliance;
const projectId = available ? requestedProjectId : undefined;
const [response, setResponse] = useState<RegulatoryMappingBatchResponse>();
const [loading, setLoading] = useState(false);
const [starting, setStarting] = useState(false);
@ -23,13 +31,13 @@ export function useRegulatoryMappingBatch(projectId: string | undefined, scope:
const activeRequestKey = useRef(requestKey);
activeRequestKey.current = requestKey;
const refresh = useCallback(async () => {
const refresh = useCallback(async (poll = false) => {
if (!projectId || !scope || (!scope.assessmentIds.length && !scope.scanRunIds.length)) {
setResponse(undefined);
return;
}
try {
const next = await assessorApi.getRegulatoryMappingBatch(projectId, scope);
const next = await (poll ? statusPollApi : assessorApi).getRegulatoryMappingBatch(projectId, scope);
if (activeRequestKey.current !== requestKey) return;
setResponse(next);
setError(undefined);
@ -51,7 +59,7 @@ export function useRegulatoryMappingBatch(projectId: string | undefined, scope:
useEffect(() => {
if (!response || !['queued', 'running'].includes(response.state)) return;
const timer = window.setTimeout(() => void refresh(), response.pollAfterMs ?? 1_500);
const timer = window.setTimeout(() => void refresh(true), response.pollAfterMs ?? 1_500);
return () => window.clearTimeout(timer);
}, [refresh, response]);
@ -74,7 +82,10 @@ export function useRegulatoryMappingBatch(projectId: string | undefined, scope:
}
}, [projectId, requestKey, scopeKey]); // eslint-disable-line react-hooks/exhaustive-deps
return { response, loading, starting, error, start };
useBackendWorkActivity('Mapping all ISO controls', !response || response.state === 'empty' ? 'idle'
: response.state === 'completed' ? 'finished' : response.state);
return { available, response, loading, starting, error, start };
}
export function RegulatoryMappingBatchDialog({ controller, filteredResultCount, onClose }: {

View File

@ -1,10 +1,12 @@
import { useState } from 'react';
import { Dialog } from '../../components/Dialog/Dialog';
import './compliance.css';
import type {
RegulatoryMappingCandidate,
RegulatoryMappingDecision,
RegulatoryMappingProposal,
RegulatoryMappingResponse
} from '../../domain/regulatory-mapping';
} from '../regulatory-mapping';
interface Props {
response?: RegulatoryMappingResponse;
@ -12,9 +14,18 @@ interface Props {
error: string;
onStart(): void;
onDecision(candidate: RegulatoryMappingCandidate, decision: 'accepted' | 'rejected', comment?: string): void;
/** Inside the window the dialog title already names the mapping. */
embedded?: boolean;
}
export function RegulatoryMappingPanel({ response, loading, error, onStart, onDecision }: Props) {
/** Finding Reader `Map ISO controls` window, opened like `Accepted Risk`. */
export function RegulatoryMappingDialog({ onClose, ...props }: Omit<Props, 'embedded'> & { onClose(): void }) {
return <Dialog title="ISO control mapping" className="regulatory-mapping-dialog" onClose={onClose}>
<RegulatoryMappingPanel {...props} embedded/>
</Dialog>;
}
export function RegulatoryMappingPanel({ response, loading, error, onStart, onDecision, embedded = false }: Props) {
const run = response?.run;
const proposals = run?.result?.mappings ?? [];
const proposalIds = new Set(proposals.map(item => item.controlId));
@ -24,8 +35,8 @@ export function RegulatoryMappingPanel({ response, loading, error, onStart, onDe
});
const otherCandidates = run?.candidates.filter(item => !proposalIds.has(item.controlId)) ?? [];
return <section className="regulatory-mapping-panel" aria-label="ISO control mapping">
<header><div><h3>ISO control mapping</h3><p>Proposals indicate relevance to this finding, not proof of compliance.</p></div>
return <section className={`regulatory-mapping-panel${embedded ? ' is-embedded' : ''}`} aria-label="ISO control mapping">
<header><div>{!embedded && <h3>ISO control mapping</h3>}<p>Proposals indicate relevance to this finding, not proof of compliance.</p></div>
{response?.generationEnabled && !['queued', 'running'].includes(response.state) && <button className="btn" type="button" disabled={loading} onClick={onStart}>{run ? 'Generate again' : 'Generate proposals'}</button>}
</header>
{loading && !response && <p role="status">Loading mapping state…</p>}

View File

@ -0,0 +1,34 @@
/* Compliance Engine UI. Shared tokens only; no status or severity colour. */
/* `Map ISO controls` window, sized like the Accepted Risk window. */
.dialog-window.regulatory-mapping-dialog { width: min(1040px, 100%); }
.regulatory-mapping-panel.is-embedded { margin-top: 0; padding: 0; border: 0; background: transparent; }
/* Finding Reader section, read like `Description`. */
.finding-iso-controls ul { display: grid; gap: var(--space-2); margin: 0; padding: 0; list-style: none; }
.finding-iso-controls li { display: flex; flex-wrap: wrap; gap: var(--space-2); font-size: var(--type-body-size); line-height: 1.5; }
.finding-iso-controls li strong { font-weight: var(--fw-semibold); font-variant-numeric: tabular-nums; }
/* Client Info section, laid out like the Context heatmap with neutral cells. */
.iso-controls { margin-block: var(--space-6) var(--space-8); color: var(--text-primary); min-width: 0; }
.iso-controls h2 { margin: 0; font-size: var(--type-h3-size); font-weight: var(--fw-semibold); }
.iso-controls p { margin: var(--space-2) 0; font-size: var(--type-body-size); }
.iso-controls__header { display: flex; align-items: baseline; justify-content: flex-start; gap: var(--space-4); flex-wrap: wrap; }
.iso-controls__total { font-size: var(--type-body-size); font-weight: var(--fw-regular); color: var(--text-secondary); font-variant-numeric: tabular-nums; white-space: nowrap; }
.iso-controls__empty { color: var(--text-secondary); }
.iso-controls__grid {
display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, var(--tile-compact-width)), var(--tile-compact-width)));
gap: var(--space-2); margin-top: var(--space-3); grid-auto-rows: 1fr;
}
.iso-controls__cell {
display: flex; flex-direction: column; align-items: start; gap: var(--space-2);
padding: var(--space-3); min-width: 0; min-height: calc(var(--tile-h) * .75); height: auto;
border: var(--bw-emphasis) solid transparent; border-radius: var(--radius-sm);
background: var(--surface-panel-raised); color: var(--text-primary);
font-family: inherit; text-align: left; cursor: pointer; overflow-wrap: anywhere;
}
.iso-controls__cell:hover { border-color: currentColor; }
.iso-controls__cell:focus-visible { outline: var(--bw-emphasis) solid var(--focus-ring); outline-offset: var(--bw-emphasis); }
.iso-controls__cell strong { font-size: var(--type-body-size); font-weight: var(--fw-semibold); line-height: var(--lh-ui); }
.iso-controls__category { font-size: var(--type-table-body-size); font-weight: var(--fw-regular); }
.iso-controls__amount { margin-top: auto; font-size: var(--type-body-size); font-weight: var(--fw-semibold); }

View File

@ -0,0 +1,20 @@
import { useSyncExternalStore } from 'react';
// Counts saved control decisions in this browser session, so views that summarize accepted
// controls (the Client Info overview) reload after a decision made elsewhere.
let revision = 0;
const listeners = new Set<() => void>();
export function markRegulatoryDecisionSaved(): void {
revision += 1;
listeners.forEach(listener => listener());
}
function subscribe(listener: () => void) {
listeners.add(listener);
return () => { listeners.delete(listener); };
}
export function useRegulatoryDecisionRevision(): number {
return useSyncExternalStore(subscribe, () => revision, () => 0);
}

View File

@ -0,0 +1,53 @@
import { readEnginePreferences } from '../../app/engine-preferences';
import { beginActivity } from '../../platform/activity-store';
import type { RegulatoryMappingResponse } from '../regulatory-mapping';
import { statusPollApi } from './status-poll-client';
const tracked = new Set<string>();
const listeners = new Set<(key: string, response: RegulatoryMappingResponse) => void>();
const isActive = (response: RegulatoryMappingResponse) => response.state === 'queued' || response.state === 'running';
const wait = (milliseconds: number) => new Promise(resolve => setTimeout(resolve, milliseconds));
export const mappingRunKey = (projectId: string, resultProjectionId: string) => `${projectId}\u0000${resultProjectionId}`;
/** Views showing a mapping receive the tracker's status updates instead of polling themselves. */
export function subscribeRegulatoryMappingRuns(listener: (key: string, response: RegulatoryMappingResponse) => void): () => void {
listeners.add(listener);
return () => { listeners.delete(listener); };
}
/**
* Keeps one `Mapping ISO controls` activity for a queued or running mapping until the backend ends it,
* independent of the open window, the selected finding or the active view. Switching the Compliance
* Engine off stops observing; the backend work itself is never cancelled.
*/
export function trackRegulatoryMappingRun(projectId: string, resultProjectionId: string, response: RegulatoryMappingResponse): void {
const key = mappingRunKey(projectId, resultProjectionId);
if (!isActive(response) || tracked.has(key)) return;
tracked.add(key);
const activity = beginActivity('Compliance Engine', 'Mapping ISO controls', `compliance-mapping:${key}`);
if (response.state === 'queued') activity.queue();
void (async () => {
let current = response;
try {
while (isActive(current)) {
await wait(current.pollAfterMs ?? 1_500);
if (!readEnginePreferences().compliance) {
activity.update('Mapping ISO controls continues in the backend');
activity.complete();
return;
}
current = await statusPollApi.getRegulatoryMappings(projectId, resultProjectionId);
if (current.state === 'running') activity.run();
listeners.forEach(listener => listener(key, current));
}
if (current.state === 'failed') activity.fail();
else activity.complete();
} catch {
activity.update('Mapping ISO controls: status could not be checked');
activity.fail();
} finally {
tracked.delete(key);
}
})();
}

View File

@ -0,0 +1,8 @@
import { AssessorApiClient } from '../../api/assessor-api-client';
/**
* Client for repeated status checks of running Compliance Engine work. The running job already has
* one activity entry; logging every check would start a new activity each time and make the activity
* panel reopen and jump while the job runs.
*/
export const statusPollApi = new AssessorApiClient({ describeActivity: () => undefined });

View File

@ -0,0 +1,36 @@
import { useEffect, useRef } from 'react';
import { beginActivity } from '../../platform/activity-store';
/** What a view currently observes of a backend job; `idle` means it no longer observes one. */
export type BackendWorkState = 'idle' | 'queued' | 'running' | 'finished' | 'failed';
/**
* Keeps one Compliance Engine activity open while backend work runs, so the activity log is not
* `Ready` between status polls. A view that stops observing the job ends the entry with a note,
* because the backend work itself is not cancelled.
*/
export function useBackendWorkActivity(label: string, state: BackendWorkState): void {
const activity = useRef<ReturnType<typeof beginActivity> | undefined>(undefined);
useEffect(() => {
if (state === 'queued' || state === 'running') {
activity.current ??= beginActivity('Compliance Engine', label);
if (state === 'queued') activity.current.queue(); else activity.current.run();
return;
}
const current = activity.current;
if (!current) return;
activity.current = undefined;
if (state === 'failed') current.fail();
else if (state === 'finished') current.complete();
else detach(current, label);
}, [label, state]);
useEffect(() => () => {
if (activity.current) detach(activity.current, label);
activity.current = undefined;
}, [label]);
}
function detach(activity: ReturnType<typeof beginActivity>, label: string) {
activity.update(`${label} continues in the backend`);
activity.complete();
}

View File

@ -2,11 +2,22 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { BackendStatus } from '../../app/app-state';
import type { FindingRecord } from '../../domain/finding';
import { AssessorApiClient } from '../../api/assessor-api-client';
import type {
RegulatoryMappingCandidate,
RegulatoryMappingDecisionValue,
RegulatoryMappingResponse
} from '../../domain/regulatory-mapping';
import { useEnginePreferences } from '../../app/engine-preferences';
import { mappingRunKey, subscribeRegulatoryMappingRuns, trackRegulatoryMappingRun } from './mapping-run-tracker';
import { markRegulatoryDecisionSaved } from './decision-revision';
import {
acceptedControlIds,
type RegulatoryMappingCandidate,
type RegulatoryMappingDecisionValue,
type RegulatoryMappingResponse
} from '../regulatory-mapping';
/** An accepted control as the Finding Reader names it. */
export interface AcceptedRegulatoryControl {
controlId: string;
annexAControlId: string;
title?: string;
}
const assessorApi = new AssessorApiClient();
@ -16,7 +27,12 @@ export function useRegulatoryMapping(
resultProjectionId: string,
backendStatus: BackendStatus
) {
const [open, setOpen] = useState(false);
// A switched-off Compliance Engine shows no control, opens nothing and sends no request.
const available = useEnginePreferences().compliance;
const [requestedOpen, setOpen] = useState(false);
const open = requestedOpen && available;
// Re-enabling the engine starts with the window closed again.
useEffect(() => { if (!available) setOpen(false); }, [available]);
const [storedResponse, setStoredResponse] = useState<{ scope: { key: string }; value: RegulatoryMappingResponse }>();
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
@ -38,6 +54,7 @@ export function useRegulatoryMapping(
setLoading(true);
try {
const next = await assessorApi.getRegulatoryMappings(projectId, resultProjectionId);
trackRegulatoryMappingRun(projectId, resultProjectionId, next);
if (activeScope.current !== requestScope) return;
setStoredResponse({ scope: requestScope, value: next });
setError('');
@ -49,18 +66,19 @@ export function useRegulatoryMapping(
}
}, [backendStatus, projectId, requestScope, resultProjectionId]);
useEffect(() => { if (open && !response && !loading && !error) void load(); }, [error, load, loading, open, response]);
useEffect(() => {
if (!open || !response || !['queued', 'running'].includes(response.state)) return;
const timeout = window.setTimeout(() => void load(), response.pollAfterMs ?? 1_500);
return () => window.clearTimeout(timeout);
}, [load, open, response]);
// Loaded with the finding, so the reader can name its accepted controls. A running mapping is polled
// once by the run tracker, which keeps its activity entry until the backend ends it.
useEffect(() => { if (available && !response && !loading && !error) void load(); }, [available, error, load, loading, response]);
useEffect(() => subscribeRegulatoryMappingRuns((key, next) => {
if (key === mappingRunKey(projectId, resultProjectionId) && activeScope.current === requestScope) setStoredResponse({ scope: requestScope, value: next });
}), [projectId, requestScope, resultProjectionId]);
const start = useCallback(async () => {
if (!projectId || !resultProjectionId || activeScope.current !== requestScope) return;
setLoading(true);
try {
const next = await assessorApi.generateRegulatoryMappings(projectId, { resultProjectionId });
trackRegulatoryMappingRun(projectId, resultProjectionId, next);
if (activeScope.current !== requestScope) return;
setStoredResponse({ scope: requestScope, value: next });
setError('');
@ -84,6 +102,7 @@ export function useRegulatoryMapping(
...(comment?.trim() ? { comment: comment.trim() } : {}),
...(latest ? { expectedLatestDecisionId: latest.id } : {})
});
markRegulatoryDecisionSaved();
if (activeScope.current !== requestScope) return;
setStoredResponse({ scope: requestScope, value: next });
setError('');
@ -95,17 +114,19 @@ export function useRegulatoryMapping(
}
}, [projectId, requestScope, response, resultProjectionId]);
const acceptedCount = useMemo(() => {
const latest = new Map<string, RegulatoryMappingDecisionValue>();
response?.decisions.forEach(item => { if (!latest.has(item.controlId)) latest.set(item.controlId, item.decision); });
return [...latest.values()].filter(value => value === 'accepted').length;
}, [response]);
const acceptedControls = useMemo<AcceptedRegulatoryControl[]>(() => available && response
? acceptedControlIds(response.decisions).map(controlId => {
const candidate = response.run?.candidates.find(item => item.controlId === controlId);
return { controlId, annexAControlId: candidate?.annexAControlId ?? `A.${controlId}`, ...(candidate?.title ? { title: candidate.title } : {}) };
}).sort((left, right) => left.controlId.localeCompare(right.controlId, 'en', { numeric: true }))
: [], [available, response]);
const localDisabledReason = !resultProjectionId ? 'This record has no stored finding or current GPO baseline comparison.'
: backendStatus !== 'connected' ? 'The backend is not connected.'
: response && !response.generationEnabled ? response.disabledReason ?? 'Regulatory mapping is unavailable.' : undefined;
return {
available,
open,
setOpen,
response,
@ -113,7 +134,8 @@ export function useRegulatoryMapping(
error,
start,
decide,
acceptedCount,
acceptedControls,
acceptedCount: acceptedControls.length,
disabledReason: localDisabledReason
};
}

View File

@ -1,6 +1,9 @@
import type { RegulatoryMappingBatchFilters } from './regulatory-mapping';
import type { UnifiedResultQuery } from './unified-result';
/** Result DB filter values without the client/timeslot scope, paging or audience. */
export type ResultDbFilters = Omit<UnifiedResultQuery,
'audience' | 'projectId' | 'assessmentId' | 'assessmentIds' | 'scanRunId' | 'scanRunIds' | 'offset' | 'limit'>;
export function buildScopedResultDbQuery(
filters: UnifiedResultQuery,
projectId: string,
@ -19,7 +22,7 @@ export function buildScopedResultDbQuery(
};
}
export function resultDbBatchFilters(query: UnifiedResultQuery): RegulatoryMappingBatchFilters {
export function resultDbBatchFilters(query: UnifiedResultQuery): ResultDbFilters {
const { audience: _audience, projectId: _projectId, assessmentId: _assessmentId,
assessmentIds: _assessmentIds, scanRunId: _scanRunId, scanRunIds: _scanRunIds,
offset: _offset, limit: _limit, ...filters } = query;

View File

@ -6,6 +6,8 @@ import { profileForSheet } from '../project-import/workspace-profile';
import { ClientSecurityPanel, type SecurityFindingGroup } from './ClientSecurityPanel';
import { managementCategoryTexts } from '../../reporting/management-report-texts';
import { ClientContextHeatmap } from '../context-layer/ContextHeatmap';
import { ClientIsoControls } from '../../compliance/ui/ClientIsoControls';
import { workRecordIdsForResult } from '../results-browser/work-record-lookup';
import { CONTEXT_CLUSTER_FACET_ID } from '../context-layer/context-cluster-facet';
import { useAssessmentContext } from '../context-layer/use-assessment-context';
import { publishContextReport } from '../../assessment-context/context-report-publication';
@ -1571,6 +1573,13 @@ export function DashboardPanel({ onOpenWork }: DashboardPanelProps) {
setFacetFilter(CONTEXT_CLUSTER_FACET_ID, { values: [clusterId] });
}, false)} />
{/* Compliance Engine: accepted ISO controls of this timeslot; a tile opens exactly its findings in Work. */}
<ClientIsoControls projectId={app.targetProjectId} assessmentIds={app.activeAssessmentIds} scanRunIds={app.activeScanRunIds}
backendStatus={app.backendStatus} onOpenFindings={findings => jump(() => {
setStatusFilter('all');
setPathFindingIds([...new Set(findings.flatMap(finding => workRecordIdsForResult(dataset, finding)))]);
}, false)} />
<div className="client-environment-grid" aria-label="Environment overview">
<DashboardFactGroup title="Resilience" items={environmentDetail.resilience} glyph="shield" snapshot={environment.snapshot} evidenceGroup="resilience" />
<DashboardFactGroup title="Inventory" items={environmentDetail.inventory} overviewItems={inventoryOverview} glyph="computer" snapshot={environment.snapshot} evidenceGroup="inventory" />

View File

@ -8,12 +8,16 @@ const nodes = [
{ id: 'input', name: 'Source inputs', caption: 'Scanner reports · GPO backups · catalogs', description: 'Original scanner reports, GPO backups and reference catalogs enter the Core import and evaluation pipeline.' },
{ id: 'core', engine: true, name: 'Core Engine', caption: 'Authoritative results · always active', description: 'All existing ASSESSOR functions: import, normalization, evaluation, scoring, client records and disclosure. Owns canonical PostgreSQL data. Works independently of optional engines.' },
{ id: 'database', name: 'Canonical PostgreSQL', caption: 'Core-owned data · disclosed Result DB', description: 'Canonical local datastore. The Core owns persistence, including the stored and verified Result DB projection.' },
{ id: 'port', name: 'Core read-only port', caption: 'Scoped results · provenance', description: 'Declared read-only Core port backed by read-only database access. Optional engines read authoritative results without changing stored data.' },
{ id: 'port', name: 'Core read-only port', caption: 'Scoped results · provenance', description: 'Declared read-only Core port. Optional engines read authoritative results without changing stored data. Context and Report Engine read through read-only database access; the Compliance Engine still reads through the running Core repository.' },
{ id: 'context', engine: true, name: 'Context Engine', caption: 'Derived context · optional', description: 'Reads findings and GPO verdicts through the read-only Core port and read-only database access. Produces versioned clusters, confidence and evidence. In-memory results; no own persistence or Core writes.' },
{ id: 'report', engine: true, name: 'Report Engine', caption: 'Read-only reporting · optional', description: 'Reads Core results through the read-only Core port and a separate read-only PostgreSQL pool. Produces report projections, management and technical reports. Own file archive; no Core writes.' },
{ id: 'ui', name: 'Core UI & exports', caption: 'Findings · scores · Result DB', description: 'Application views show authoritative Core findings, verdicts and scores. Result DB exports obey the Core disclosure policy.' },
{ id: 'context-ui', name: 'Context in the UI', caption: 'Work · Client Info · Pathfinder', description: 'Published Context results appear through existing UI extension points. They never override technical results or client records.' },
{ id: 'archive', name: 'Report outputs', caption: 'File archive · downloads', description: 'Generated reports are stored in the separate Report Engine file archive and offered for download; no report storage in Core tables.' }
{ id: 'archive', name: 'Report outputs', caption: 'File archive · downloads', description: 'Generated reports are stored in the separate Report Engine file archive and offered for download; no report storage in Core tables.' },
{ id: 'compliance', engine: true, name: 'Compliance Engine', caption: 'Regulatory control mapping · optional', description: 'Maps findings and GPO baseline comparisons to regulatory controls; ISO/IEC 27001/27002 is the first framework. Reads Core results through the read-only Core port and writes only its own tables. Proposals never change verdicts, scores or client records.' },
{ id: 'compliance-tables', name: 'Compliance tables', caption: 'Mappings · decisions · batches', description: 'Mapping runs, accept/reject decisions and batches in three engine-owned tables of the canonical PostgreSQL. Written through a separate small pool; engine writes never advance the Core revision.' },
{ id: 'retrieval', name: 'Retrieval & model', caption: 'Qdrant index · LiteLLM', description: 'The rebuildable Qdrant index of the uploaded control corpus and the configured LiteLLM model. They receive privacy-safe finding text and corpus evidence, never assets or customer values.' },
{ id: 'compliance-ui', name: 'ISO mapping in the UI', caption: 'Finding Reader · Result DB · Data Hub', description: 'Control proposals, accept/reject decisions, filtered batches and the ISO corpus upload appear through existing UI extension points. A proposal indicates relevance, not proof of compliance.' }
];
const relationships = [
{ from: 'input', to: 'core', label: 'Import', detail: 'Import and evaluation', path: 'M240 340 H310' },
@ -24,7 +28,11 @@ const relationships = [
{ from: 'core', to: 'ui', label: 'Core results', detail: 'Authoritative findings, verdicts, scores and disclosure rules', path: 'M420 290 V160' },
{ from: 'context', to: 'context-ui', label: 'Context', detail: 'Published context results through existing UI extension points', path: 'M710 290 V160' },
{ from: 'report', to: 'archive', label: 'Reports', detail: 'Generated reports; separate from Core database storage', path: 'M1000 520 V390' },
{ from: 'context', to: 'report', label: 'Planned', detail: 'Published context results; documented target, not yet connected in report generation', path: 'M820 340 H855 V490 H940 V520', planned: true }
{ from: 'context', to: 'report', label: 'Planned', detail: 'Published context results; documented target, not yet connected in report generation', path: 'M820 340 H855 V490 H940 V520', planned: true },
{ from: 'port', to: 'compliance', label: 'Read only', detail: 'Single Result DB row by client, filtered Result DB pages, client, assessment and scan-run lists', path: 'M710 620 V750' },
{ from: 'compliance', to: 'compliance-tables', label: 'Own data', detail: 'Mapping runs, decisions and batches; never Core tables', path: 'M600 800 H530', bidirectional: true },
{ from: 'compliance', to: 'retrieval', label: 'Retrieval', detail: 'Privacy-safe query, retrieved control evidence and model proposals', path: 'M820 800 H890', bidirectional: true },
{ from: 'compliance', to: 'compliance-ui', label: 'Proposals', detail: 'Grounded control proposals and decisions through existing UI extension points', path: 'M710 850 V900 H130 V850' }
];
const nodeName = (id: string) => nodes.find(node => node.id === id)!.name;
@ -38,7 +46,7 @@ export function EngineDataFlow() {
<header className="db-engine-flow__heading"><h3>Engines & relationships</h3><span>Solid: implemented · Dashed: planned</span></header>
<div className="db-engine-flow__scroll" role="region" aria-label="Interactive engine diagram" tabIndex={0}>
<div className="db-engine-flow__map">
<svg className="db-engine-flow__edges" width="1130" height="650" aria-hidden="true">
<svg className="db-engine-flow__edges" width="1130" height="940" aria-hidden="true">
<defs><marker id={markerId} viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0 L10 5 L0 10 Z" /></marker></defs>
{relationships.map(edge => <path key={`${edge.from}-${edge.to}`} d={edge.path} markerEnd={`url(#${markerId})`} markerStart={edge.bidirectional ? `url(#${markerId})` : undefined}
className={`${edge.planned ? 'is-planned' : ''} ${connections.includes(edge) ? 'is-related' : ''}`} />)}
@ -56,7 +64,7 @@ export function EngineDataFlow() {
<ul>{connections.map(edge => <li key={`${edge.from}-${edge.to}`}><strong>{nodeName(edge.from)} {edge.bidirectional ? '↔' : '→'} {nodeName(edge.to)}</strong><span>{edge.detail}{edge.planned ? ' · Planned' : ''}</span></li>)}</ul>
</section> : <p className="db-engine-flow__boundary">Select a module to inspect its data flow. Modules also support keyboard selection.</p>}
<p className="db-engine-flow__boundary">Arrows show data delivery. Engine dependencies point toward the Core; the Core never depends on an optional engine. Engines cannot override verdicts, scores or client records. Every output follows Core privacy and Result DB disclosure rules.</p>
<details className="db-engine-flow__dictionary"><summary>All relationships (9)</summary><div className="db-engine-flow__scroll"><table aria-label="Directed engine relationships">
<details className="db-engine-flow__dictionary"><summary>All relationships ({relationships.length})</summary><div className="db-engine-flow__scroll"><table aria-label="Directed engine relationships">
<thead><tr><th scope="col">From</th><th scope="col">To</th><th scope="col">Data flow</th><th scope="col">Implementation</th></tr></thead>
<tbody>{relationships.map(edge => <tr key={`${edge.from}-${edge.to}`}><td>{nodeName(edge.from)}</td><td>{edge.bidirectional ? '↔' : '→'} {nodeName(edge.to)}</td><td>{edge.detail}</td><td>{edge.planned ? 'Planned' : 'Implemented'}</td></tr>)}</tbody>
</table></div></details>

View File

@ -42,8 +42,9 @@ import { findingWebSearch } from '../../profiles/public-search/search';
import { policyEvidenceResultSheets, POLICY_CONFLICT_DETAILS, POLICY_DUPLICATE_DETAILS } from '../../profiles/group-policy/conflict-presentation';
import { maesterExecutionErrorText, maesterFindingTitle, maesterTagText } from '../../profiles/maester/presentation';
import type { BackendStatus } from '../../app/app-state';
import { RegulatoryMappingPanel } from './RegulatoryMappingPanel';
import { regulatoryMappingResultId, useRegulatoryMapping } from './use-regulatory-mapping';
import { RegulatoryMappingDialog } from '../../compliance/ui/RegulatoryMappingPanel';
import { FindingIsoControls } from '../../compliance/ui/FindingIsoControls';
import { regulatoryMappingResultId, useRegulatoryMapping } from '../../compliance/ui/use-regulatory-mapping';
interface Props {
record: FindingRecord;
@ -504,9 +505,9 @@ export function FindingReader({ record, title, review: storedReview, previousPol
</button>
<div className="reader-heading-actions">
<FindingContextBadges record={record} isPolicySetting={resolvedToolId === 'group-policy'}/>
<button className="btn" type="button" aria-expanded={regulatoryMapping.open} disabled={!regulatoryMapping.open && Boolean(regulatoryMapping.disabledReason)} title={regulatoryMapping.disabledReason} onClick={() => regulatoryMapping.setOpen(!regulatoryMapping.open)}>
{regulatoryMapping.available && <button className="btn" type="button" aria-expanded={regulatoryMapping.open} disabled={!regulatoryMapping.open && Boolean(regulatoryMapping.disabledReason)} title={regulatoryMapping.disabledReason} onClick={() => regulatoryMapping.setOpen(!regulatoryMapping.open)}>
Map ISO controls{regulatoryMapping.acceptedCount ? ` (${regulatoryMapping.acceptedCount})` : ''}
</button>
</button>}
<div className="reader-primary-actions" role="group" aria-label="Finding actions">
{webSearch && <a className="btn" href={webSearch.url} target="_blank" rel="noopener noreferrer" referrerPolicy="no-referrer" data-search-specificity={webSearch.specificity} title={`${webSearch.specificity === 'topic' ? 'Topic search — ' : ''}${webSearch.query}`}>AI search</a>}
<button className="bookmark-btn" type="button" aria-label="Bookmark" title="Bookmark" aria-pressed={review.include} onClick={() => onReview({ include: !review.include })}><BookmarkIcon filled={review.include} /></button>
@ -577,6 +578,8 @@ export function FindingReader({ record, title, review: storedReview, previousPol
: resolvedToolId === 'group-policy' && /^(?:description|remediation|sources)$/.test(normalizeLabel(field.label))
? <p className="policy-guidance-text"><PathText value={field.value} search={search} label={field.label} /></p>
: <RichTextValue value={field.value} search={search} label={field.label} onResults={onResults} />}</div>)}
{/* Compliance Engine: controls accepted for this finding, read like Description. */}
<FindingIsoControls controls={regulatoryMapping.acceptedControls}/>
{optionalFields.map(field => <details className="finding-optional-detail" key={`${field.index}-${field.label}`}>
<summary><TriangleIcon direction="right" />{highlightText(field.label, search)}</summary>
{resolvedToolId === 'maester' && normalizeLabel(field.label) === 'test details'
@ -584,8 +587,9 @@ export function FindingReader({ record, title, review: storedReview, previousPol
: <RichTextValue value={field.value} search={search} label={field.label} onResults={onResults} />}
</details>)}
</section>
{regulatoryMapping.open && <RegulatoryMappingPanel response={regulatoryMapping.response} loading={regulatoryMapping.loading} error={regulatoryMapping.error}
onStart={() => void regulatoryMapping.start()} onDecision={(candidate, decision, comment) => void regulatoryMapping.decide(candidate, decision, comment)} />}
{regulatoryMapping.open && <RegulatoryMappingDialog response={regulatoryMapping.response} loading={regulatoryMapping.loading} error={regulatoryMapping.error}
onStart={() => void regulatoryMapping.start()} onDecision={(candidate, decision, comment) => void regulatoryMapping.decide(candidate, decision, comment)}
onClose={() => regulatoryMapping.setOpen(false)} />}
{/* Work tracking is opt-in below the finding so the first screen states the problem. */}
<FindingReferences record={record}/>
<details className="reader-tracking">

View File

@ -16,7 +16,7 @@ import { PolicyAnalysisPanel } from './PolicyAnalysisPanel';
import { PanelLoadingState } from '../../components/PanelLoadingState/PanelLoadingState';
import { BackendConnectionDialog } from '../../components/BackendConnectionDialog/BackendConnectionDialog';
import { MicrosoftBaselineLibrary } from './MicrosoftBaselineLibrary';
import { IsoCorpusLibrary } from './IsoCorpusLibrary';
import { IsoCorpusLibrary } from '../../compliance/ui/IsoCorpusLibrary';
import { MitreMatrixLibrary } from './MitreMatrixLibrary';
import { ReferenceRecognitionPanel } from './ReferenceRecognitionPanel';
import { activeMitreMatrix, clearStoredMitreMatrix, loadStoredMitreMatrix, MITRE_MATRIX_CHANGED_EVENT, saveStoredMitreMatrix, setServerMitreMatrix, validateMitreMatrixData } from '../mitre-graph/mitre-graph';

View File

@ -18,7 +18,7 @@ import { BackendConnectionDialog } from '../../components/BackendConnectionDialo
import { formatPolicyComparisonValue } from '../../profiles/group-policy/presentation';
import type { ResultDbMaterializationStatus } from '../../domain/result-db-materialization';
import { buildScopedResultDbQuery, resultDbBatchFilters } from '../../domain/result-db-query';
import { RegulatoryMappingBatchDialog, useRegulatoryMappingBatch } from './RegulatoryMappingBatchDialog';
import { RegulatoryMappingBatchDialog, useRegulatoryMappingBatch } from '../../compliance/ui/RegulatoryMappingBatchDialog';
const assessorApi = new AssessorApiClient();
const PAGE_SIZE = 50;
@ -58,6 +58,7 @@ export function ResultsBrowser({ backendStatus, projectId, scanRunIds, assessmen
filters: resultDbBatchFilters(scopedQuery)
} : undefined, [scopedQuery]);
const regulatoryBatch = useRegulatoryMappingBatch(backendStatus === 'connected' ? projectId : undefined, batchScope);
useEffect(() => { if (!regulatoryBatch.available) setBatchDialogOpen(false); }, [regulatoryBatch.available]);
const load = useCallback(async () => {
if (backendStatus !== 'connected' || !projectId || !hasTimeslotScope) {
@ -178,10 +179,10 @@ export function ResultsBrowser({ backendStatus, projectId, scanRunIds, assessmen
<p className="db-structure-meta">{(queryResult?.total ?? 0).toLocaleString('en-US')} hits{queryResult && queryResult.total > queryResult.items.length ? ` · ${queryResult.items.length.toLocaleString('en-US')} loaded` : ''}{resultDbStatus && <><br/><span className="results-db-status" data-state={resultDbStatus.state}>{resultDbStatusText(resultDbStatus)}</span></>}</p>
<div className="page-action-buttons">
<button className="btn" type="button" disabled={loading} onClick={() => void load()}>{loading ? 'Loading …' : 'Refresh'}</button>
<button className="btn" type="button"
{regulatoryBatch.available && <button className="btn" type="button"
disabled={loading || regulatoryBatch.loading || Boolean(regulatoryBatch.error) || !queryResult?.total || regulatoryBatch.response?.generationEnabled === false}
title={regulatoryBatch.error ?? regulatoryBatch.response?.disabledReason ?? 'Generate ISO control proposals for every result matching the current filters'}
onClick={() => setBatchDialogOpen(true)}>Map all ISO controls</button>
onClick={() => setBatchDialogOpen(true)}>Map all ISO controls</button>}
<button className="btn primary" type="button" disabled={loading || exporting !== null || !queryResult?.total}
onClick={() => void exportFilteredResults('jsonl')}>{exporting === 'jsonl' ? 'Exporting …' : 'Export JSONL'}</button>
<button className="btn primary" type="button" disabled={loading || exporting !== null || !queryResult?.total}
@ -208,7 +209,7 @@ export function ResultsBrowser({ backendStatus, projectId, scanRunIds, assessmen
</div>}
</div>
</div>}
{batchDialogOpen && <RegulatoryMappingBatchDialog controller={regulatoryBatch}
{batchDialogOpen && regulatoryBatch.available && <RegulatoryMappingBatchDialog controller={regulatoryBatch}
filteredResultCount={queryResult?.total ?? 0} onClose={() => setBatchDialogOpen(false)}/>}
</div>;
}

View File

@ -6,7 +6,8 @@ import type { UnifiedResultProjection } from '../../domain/unified-result';
* only the checked content; the original stays in Work). Scanner rows match their finding occurrence;
* GPO comparison rows match the Work setting of the same scope and technical setting identity.
*/
export function workRecordIdsForResult(dataset: ImportedDataset | null | undefined, row: UnifiedResultProjection): string[] {
export function workRecordIdsForResult(dataset: ImportedDataset | null | undefined,
row: Pick<UnifiedResultProjection, 'sourceKind' | 'sourceResultId' | 'sourceRuleId' | 'policyScope'>): string[] {
if (!dataset) return [];
const ids = new Set<string>();
for (const sheet of dataset.sheets) {

View File

@ -36,7 +36,6 @@ import type {
} from '../domain/unified-result';
import type { EnvironmentObservation, EnvironmentSnapshot, EnvironmentSnapshotQuery, ScannerReportSection } from '../domain/environment-context';
import type { AiOverviewRun } from '../domain/ai-overview';
import type { RegulatoryMappingBatchRun, RegulatoryMappingDecision, RegulatoryMappingRun } from '../domain/regulatory-mapping';
export interface FindingOccurrenceQuery {
projectId?: string;
@ -149,9 +148,6 @@ export interface ProjectDataExport {
environmentProfiles: EnvironmentProfile[];
policySnapshotAggregations: StoredPolicySnapshotAggregation[];
aiOverviewRuns: AiOverviewRun[];
regulatoryMappingBatchRuns: RegulatoryMappingBatchRun[];
regulatoryMappingRuns: RegulatoryMappingRun[];
regulatoryMappingDecisions: RegulatoryMappingDecision[];
}
export interface ControlledDeleteConfirmation {
@ -220,7 +216,8 @@ export interface AssessorRepository {
findOccurrences(query?: FindingOccurrenceQuery): Promise<FindingOccurrenceQueryResult>;
queryUnifiedResults(query?: UnifiedResultQuery): Promise<UnifiedResultQueryResult>;
queryUnifiedResultFacets(query?: UnifiedResultQuery): Promise<UnifiedResultFacetResult>;
getUnifiedResultById(resultProjectionId: string): Promise<UnifiedResultProjection | null>;
/** Returns the scope-stripped Result DB row; with projectId, only a row stored for that project. */
getUnifiedResultById(resultProjectionId: string, projectId?: string): Promise<UnifiedResultProjection | null>;
/** State of the materialized, disclosure-checked Result DB (see result-db-materialization). */
getResultDbStatus(): Promise<ResultDbMaterializationStatus>;
listResultCategories(query?: UnifiedResultQuery): Promise<UnifiedResultCategory[]>;
@ -228,15 +225,6 @@ export interface AssessorRepository {
createAiOverviewRun(run: AiOverviewRun): Promise<AiOverviewRun>;
updateAiOverviewRun(run: AiOverviewRun): Promise<AiOverviewRun>;
listAiOverviewRuns(projectId: string, scopeKey?: string): Promise<AiOverviewRun[]>;
getRegulatoryMappingRun(id: string): Promise<RegulatoryMappingRun | null>;
claimRegulatoryMappingRun(run: RegulatoryMappingRun, forceRegeneration: boolean): Promise<{ run: RegulatoryMappingRun; claimed: boolean }>;
saveRegulatoryMappingRun(run: RegulatoryMappingRun): Promise<RegulatoryMappingRun>;
listRegulatoryMappingRuns(): Promise<RegulatoryMappingRun[]>;
createRegulatoryMappingBatchRun(run: RegulatoryMappingBatchRun): Promise<RegulatoryMappingBatchRun>;
updateRegulatoryMappingBatchRun(run: RegulatoryMappingBatchRun): Promise<RegulatoryMappingBatchRun>;
listRegulatoryMappingBatchRuns(projectId: string, scopeKey?: string): Promise<RegulatoryMappingBatchRun[]>;
createRegulatoryMappingDecision(decision: RegulatoryMappingDecision, expectedLatestDecisionId?: string): Promise<RegulatoryMappingDecision>;
listRegulatoryMappingDecisions(ruleKey: string): Promise<RegulatoryMappingDecision[]>;
saveImportArtifact(artifact: ImportArtifact): Promise<void>;
saveImportArtifactAndEnqueueJob(artifact: ImportArtifact, job: IngestionJob): Promise<ArtifactJobCommitResult>;

View File

@ -35,8 +35,6 @@ import type { EnvironmentObservation, EnvironmentSnapshot, EnvironmentSnapshotQu
import { environmentCoverage } from '../domain/environment-context';
import type { AiOverviewRun } from '../domain/ai-overview';
import { aiOverviewRunValidationErrors } from '../domain/ai-overview';
import type { RegulatoryMappingBatchRun, RegulatoryMappingDecision, RegulatoryMappingRun } from '../domain/regulatory-mapping';
import { regulatoryMappingBatchRunValidationErrors, regulatoryMappingDecisionValidationErrors, regulatoryMappingRunValidationErrors } from '../domain/regulatory-mapping';
import { storedPolicyFindingRunValidationErrors } from '../domain/policy-finding';
import {
environmentProfileValidationErrors,
@ -113,9 +111,6 @@ interface LocalRepositoryState {
findingDefinitions: FindingDefinition[];
findingOccurrences: FindingOccurrence[];
aiOverviewRuns: AiOverviewRun[];
regulatoryMappingBatchRuns: RegulatoryMappingBatchRun[];
regulatoryMappingRuns: RegulatoryMappingRun[];
regulatoryMappingDecisions: RegulatoryMappingDecision[];
evidence: EvidenceRecord[];
reviews: FindingReview[];
scopedRiskAcceptances: ScopedRiskAcceptance[];
@ -152,9 +147,6 @@ const emptyState = (): LocalRepositoryState => ({
findingDefinitions: [],
findingOccurrences: [],
aiOverviewRuns: [],
regulatoryMappingBatchRuns: [],
regulatoryMappingRuns: [],
regulatoryMappingDecisions: [],
evidence: [],
reviews: [],
scopedRiskAcceptances: [],
@ -444,96 +436,6 @@ export class LocalAssessorRepository implements AssessorRepository {
.sort((left, right) => right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id));
}
async getRegulatoryMappingRun(id: string): Promise<RegulatoryMappingRun | null> {
const run = this.state.regulatoryMappingRuns.find(item => item.id === id);
return run ? clone(run) : null;
}
async claimRegulatoryMappingRun(run: RegulatoryMappingRun, forceRegeneration: boolean): Promise<{ run: RegulatoryMappingRun; claimed: boolean }> {
const errors = regulatoryMappingRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
const existing = this.state.regulatoryMappingRuns.find(item => item.id === run.id);
if (existing && (['queued', 'running'].includes(existing.status) || existing.status === 'succeeded' && !forceRegeneration)) {
return { run: clone(existing), claimed: false };
}
const stored = await this.saveRegulatoryMappingRun(run);
return { run: stored, claimed: true };
}
async saveRegulatoryMappingRun(run: RegulatoryMappingRun): Promise<RegulatoryMappingRun> {
const errors = regulatoryMappingRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
const next = clone(this.state);
const index = next.regulatoryMappingRuns.findIndex(item => item.id === run.id);
if (index >= 0) next.regulatoryMappingRuns[index] = clone(run);
else next.regulatoryMappingRuns.push(clone(run));
this.replaceState(next);
return clone(run);
}
async listRegulatoryMappingRuns(): Promise<RegulatoryMappingRun[]> {
return this.state.regulatoryMappingRuns.map(clone)
.sort((left, right) => right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id));
}
async createRegulatoryMappingBatchRun(run: RegulatoryMappingBatchRun): Promise<RegulatoryMappingBatchRun> {
const errors = regulatoryMappingBatchRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
const idempotent = this.state.regulatoryMappingBatchRuns.find(item => item.projectId === run.projectId && item.idempotencyKey === run.idempotencyKey);
if (idempotent) return clone(idempotent);
const active = this.state.regulatoryMappingBatchRuns.find(item => item.projectId === run.projectId && item.scopeKey === run.scopeKey
&& ['queued', 'running'].includes(item.status));
if (active) return clone(active);
const next = clone(this.state);
next.regulatoryMappingBatchRuns.push(clone(run));
this.replaceState(next);
return clone(run);
}
async updateRegulatoryMappingBatchRun(run: RegulatoryMappingBatchRun): Promise<RegulatoryMappingBatchRun> {
const errors = regulatoryMappingBatchRunValidationErrors(run);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
const existing = this.state.regulatoryMappingBatchRuns.find(item => item.id === run.id);
if (!existing) throw new RepositoryNotFoundError('Regulatory mapping batch does not exist.');
if (existing.projectId !== run.projectId || existing.scopeKey !== run.scopeKey || existing.idempotencyKey !== run.idempotencyKey) {
throw new RepositoryConflictError('Regulatory mapping batch identity is immutable.');
}
if (['completed', 'failed'].includes(existing.status)) throw new RepositoryConflictError('A completed regulatory mapping batch is immutable.');
const allowed = existing.status === 'queued' ? ['running', 'failed'] : ['running', 'completed', 'failed'];
if (!allowed.includes(run.status)) throw new RepositoryConflictError(`Invalid regulatory mapping batch transition from ${existing.status} to ${run.status}.`);
const next = clone(this.state);
next.regulatoryMappingBatchRuns[next.regulatoryMappingBatchRuns.findIndex(item => item.id === run.id)] = clone(run);
this.replaceState(next);
return clone(run);
}
async listRegulatoryMappingBatchRuns(projectId: string, scopeKey?: string): Promise<RegulatoryMappingBatchRun[]> {
return this.state.regulatoryMappingBatchRuns.filter(item => item.projectId === projectId && (!scopeKey || item.scopeKey === scopeKey))
.map(clone).reverse();
}
async createRegulatoryMappingDecision(decision: RegulatoryMappingDecision, expectedLatestDecisionId?: string): Promise<RegulatoryMappingDecision> {
const errors = regulatoryMappingDecisionValidationErrors(decision);
if (errors.length) throw new RepositoryValidationError(errors.join(' '));
const run = this.state.regulatoryMappingRuns.find(item => item.id === decision.mappingId);
if (!run || run.ruleKey !== decision.ruleKey || run.status !== 'succeeded') {
throw new RepositoryNotFoundError('Completed regulatory mapping does not exist for this rule.');
}
if (!run.candidates.some(candidate => candidate.controlId === decision.controlId)) throw new RepositoryValidationError('Decision control was not a grounded candidate.');
const latest = this.state.regulatoryMappingDecisions.filter(item => item.ruleKey === decision.ruleKey && item.controlId === decision.controlId)
.sort((left, right) => right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id))[0];
if ((expectedLatestDecisionId ?? undefined) !== (latest?.id ?? undefined)) throw new RepositoryConflictError('Regulatory mapping decision changed before this update.');
const next = clone(this.state);
next.regulatoryMappingDecisions.push(clone({ ...decision, ...(latest ? { previousDecisionId: latest.id } : {}) }));
this.replaceState(next);
return clone(next.regulatoryMappingDecisions.at(-1)!);
}
async listRegulatoryMappingDecisions(ruleKey: string): Promise<RegulatoryMappingDecision[]> {
return this.state.regulatoryMappingDecisions.filter(item => item.ruleKey === ruleKey)
.map(clone).sort((left, right) => right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id));
}
async beginImport(start: ImportSessionStart): Promise<ImportSession> {
if (!start.sessionId.trim()) throw new RepositoryValidationError('Eine Importsitzung benötigt eine ID.');
if (this.activeImportSessions.has(start.sessionId)) throw new RepositoryConflictError(`Importsitzung ${start.sessionId} ist bereits aktiv.`);
@ -863,8 +765,8 @@ export class LocalAssessorRepository implements AssessorRepository {
return clone(deriveUnifiedResultFacets(this.unifiedResults(query.audience), query));
}
async getUnifiedResultById(resultProjectionId: string): Promise<UnifiedResultProjection | null> {
const result = this.unifiedResults().find(item => item.resultProjectionId === resultProjectionId);
async getUnifiedResultById(resultProjectionId: string, projectId?: string): Promise<UnifiedResultProjection | null> {
const result = this.unifiedResults().find(item => item.resultProjectionId === resultProjectionId && (projectId === undefined || item.projectId === projectId));
return result ? clone(removeResultDbScopeIdentifiers(result)) : null;
}
@ -1712,11 +1614,7 @@ export class LocalAssessorRepository implements AssessorRepository {
policySnapshotAggregations: this.state.policySnapshotAggregations.filter(item => item.run.projectId === projectId).map(clone),
policyEvaluations: this.state.policyEvaluations.filter(item => item.run.projectId === projectId).map(clone),
policyFindingRuns: policyFindingRuns.map(clone),
aiOverviewRuns: this.state.aiOverviewRuns.filter(item => item.projectId === projectId && item.status === 'succeeded').map(clone),
regulatoryMappingBatchRuns: this.state.regulatoryMappingBatchRuns.filter(item => item.projectId === projectId).map(clone),
// Regulatory mappings and decisions are global reference data, not project-scoped.
regulatoryMappingRuns: this.state.regulatoryMappingRuns.filter(item => item.status === 'succeeded').map(clone),
regulatoryMappingDecisions: this.state.regulatoryMappingDecisions.map(clone)
aiOverviewRuns: this.state.aiOverviewRuns.filter(item => item.projectId === projectId && item.status === 'succeeded').map(clone)
});
}
@ -1779,7 +1677,6 @@ export class LocalAssessorRepository implements AssessorRepository {
next.gpoPolicyAnalyses = next.gpoPolicyAnalyses.filter(item => !processingRunIds.has(item.run.sourceProcessingRunId));
next.artifactDeletionRequests = next.artifactDeletionRequests.filter(item => !artifactIds.has(item.artifactId));
next.aiOverviewRuns = next.aiOverviewRuns.filter(item => !item.scanRunIds.includes(scanRunId));
// Regulatory mappings and decisions are global and survive scan-run removal.
const remainingHashes = new Set(next.importFiles.map(item => item.sha256).filter(Boolean) as string[]);
next.importFingerprints = next.importFingerprints.filter(item => !removedHashes.has(item.sha256) || remainingHashes.has(item.sha256));
this.replaceState(next);
@ -1847,7 +1744,6 @@ export class LocalAssessorRepository implements AssessorRepository {
next.policyFindingRuns = next.policyFindingRuns.filter(item => !evaluationRunIds.has(item.run.evaluationRunId));
next.artifactDeletionRequests = next.artifactDeletionRequests.filter(item => !artifactIds.has(item.artifactId));
next.aiOverviewRuns = next.aiOverviewRuns.filter(item => !item.assessmentIds.includes(assessmentId));
// Regulatory mappings and decisions are global and survive assessment removal.
const remainingDefinitionIds = new Set([
...next.findingOccurrences.map(item => item.definitionId),
...next.policyFindingRuns.flatMap(item => item.occurrences.map(occurrence => occurrence.definitionId))
@ -1904,9 +1800,7 @@ export class LocalAssessorRepository implements AssessorRepository {
next.policySnapshotAggregations = next.policySnapshotAggregations.filter(item => item.run.projectId !== projectId);
next.policyEvaluations = next.policyEvaluations.filter(item => item.run.projectId !== projectId);
next.aiOverviewRuns = next.aiOverviewRuns.filter(item => item.projectId !== projectId);
next.regulatoryMappingBatchRuns = next.regulatoryMappingBatchRuns.filter(item => item.projectId !== projectId);
next.scopedRiskAcceptances = next.scopedRiskAcceptances.filter(item => item.projectId !== projectId);
// Regulatory mappings and decisions are global and survive project deletion.
this.replaceState(next);
return true;
}

View File

@ -1943,7 +1943,7 @@ button.client-overall-ring:focus-visible { outline: var(--bw-emphasis) solid var
.db-engine-flow__heading { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: var(--space-3); }
.db-engine-flow__heading h3 { margin: 0; color: var(--heading); font-size: var(--type-h3-size); font-weight: var(--fw-semibold); }
.db-engine-flow__heading > span { color: var(--muted); font-size: var(--type-table-body-size); }
.db-engine-flow__map { position: relative; width: 1130px; height: 650px; margin: 0 auto; }
.db-engine-flow__map { position: relative; width: 1130px; height: 940px; margin: 0 auto; }
.db-engine-flow__edges { position: absolute; inset: 0; overflow: visible; pointer-events: none; }
.db-engine-flow__edges > path { fill: none; stroke: var(--line-strong); stroke-width: 2; }
.db-engine-flow__edges > path.is-related { stroke: var(--marking-color); }
@ -1967,6 +1967,10 @@ button.client-overall-ring:focus-visible { outline: var(--bw-emphasis) solid var
.db-engine-flow__node[data-node="ui"] { left: 310px; top: 60px; }
.db-engine-flow__node[data-node="context-ui"] { left: 600px; top: 60px; }
.db-engine-flow__node[data-node="archive"] { left: 890px; top: 290px; }
.db-engine-flow__node[data-node="compliance"] { left: 600px; top: 750px; }
.db-engine-flow__node[data-node="compliance-tables"] { left: 310px; top: 750px; }
.db-engine-flow__node[data-node="retrieval"] { left: 890px; top: 750px; }
.db-engine-flow__node[data-node="compliance-ui"] { left: 20px; top: 750px; }
.db-engine-flow__edge-label[data-edge="input-core"] { left: 275px; top: 312px; }
.db-engine-flow__edge-label[data-edge="core-database"] { left: 420px; top: 455px; }
.db-engine-flow__edge-label[data-edge="database-port"] { left: 565px; top: 540px; }
@ -1976,6 +1980,10 @@ button.client-overall-ring:focus-visible { outline: var(--bw-emphasis) solid var
.db-engine-flow__edge-label[data-edge="context-context-ui"] { left: 710px; top: 225px; }
.db-engine-flow__edge-label[data-edge="report-archive"] { left: 1000px; top: 455px; }
.db-engine-flow__edge-label[data-edge="context-report"] { left: 855px; top: 416px; }
.db-engine-flow__edge-label[data-edge="port-compliance"] { left: 710px; top: 685px; }
.db-engine-flow__edge-label[data-edge="compliance-compliance-tables"] { left: 565px; top: 800px; }
.db-engine-flow__edge-label[data-edge="compliance-retrieval"] { left: 855px; top: 800px; }
.db-engine-flow__edge-label[data-edge="compliance-compliance-ui"] { left: 420px; top: 900px; }
.db-engine-flow__inspector { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: var(--space-5); padding: var(--tile-inset); background: var(--tile-surface); border: var(--border-hair) solid var(--tile-border); }
.db-engine-flow__inspector h4 { margin: 0 0 var(--space-2); font-size: var(--type-h4-size); font-weight: var(--fw-semibold); }
.db-engine-flow__inspector p { margin: 0; font-size: var(--type-body-size); line-height: 1.5; }

View File

@ -0,0 +1,63 @@
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { beforeAll, describe, expect, it } from 'vitest';
// The Core guard's area table (AGENTS.md, "Core Engine and engines"): engine paths come before the
// Core areas, an unregistered source path stays Core, and a bare folder name belongs to the prefix
// it names, so renaming a whole engine folder is not mistaken for a Core change.
const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
interface AreaTable {
classifyPath(relative: string | null): string | null;
relativeToProject(filePath: string, projectDir: string): string | null;
resolveAreaName(raw: string): string | null;
isReleased(area: string, releasedAreas: string[]): boolean;
}
let areas: AreaTable;
beforeAll(async () => {
areas = await import(/* @vite-ignore */ pathToFileURL(join(root, '.claude', 'hooks', 'core-areas.mjs')).href) as AreaTable;
});
describe('Core guard area table', () => {
it.each([
'src/compliance', 'src/compliance/', 'src/compliance/ui/regulatorymappingpanel.tsx',
'server/compliance', 'tests/compliance', 'src/assessment-context', 'src/reporting', 'server/reporting'
])('treats engine path %s as engine code', path => {
expect(areas.classifyPath(path)).toBeNull();
});
it.each([
['src/compliance-x', 'Unclassified Source'],
['src/compliance-x/file.ts', 'Unclassified Source'],
['src/newthing', 'Unclassified Source'],
['src/persistence', 'Store'],
['src/persistence/local-assessor-repository.ts', 'Store'],
['server/postgres', 'Store'],
['src/app', 'Presentation'],
['src/features/finding-reader/findingreader.tsx', 'Presentation'],
['server/index.ts', 'Platform'],
['tests/architecture/core-areas.test.ts', 'Core Tests'],
['agents.md', 'Governance'],
['.claude/hooks', 'Governance'],
['src/domain/review.ts', 'Client Records']
])('keeps %s in Core area %s', (path, area) => {
expect(areas.classifyPath(path)).toBe(area);
});
it('leaves paths outside the project and documentation unguarded', () => {
expect(areas.classifyPath(null)).toBeNull();
expect(areas.relativeToProject(join(root, '..', 'elsewhere.ts'), root)).toBeNull();
expect(areas.classifyPath('docs/implementation_plan.md')).toBeNull();
expect(areas.relativeToProject(join(root, 'src', 'Compliance', 'X.ts'), root)).toBe('src/compliance/x.ts');
});
it('resolves release names and never lets "alle" cover Governance', () => {
expect(areas.resolveAreaName(' Core Tests ')).toBe('Core Tests');
expect(areas.resolveAreaName('unclassified source')).toBe('Unclassified Source');
expect(areas.resolveAreaName('compliance')).toBeNull();
expect(areas.isReleased('Store', ['alle'])).toBe(true);
expect(areas.isReleased('Governance', ['alle'])).toBe(false);
expect(areas.isReleased('Governance', ['Governance'])).toBe(true);
expect(areas.isReleased('Store', ['Platform'])).toBe(false);
});
});

View File

@ -53,16 +53,20 @@ const allSources = () => [...sourceFiles(join(root, 'src')), ...sourceFiles(join
/**
* Pinned Core -> Engine dependencies: the documented extension points (
* `Context Cluster` Work facet, Finding Reader `Context` section, Pathfinder and sidebar cluster
* readers), the type-only API contract and the server wiring of both engines.
* readers; Finding Reader ISO mapping, Result DB ISO batch and Data Hub ISO corpus upload), the
* type-only API contract and client, and the server wiring of the engines.
*/
const EXTENSION_POINTS: Record<string, { engine: string | readonly string[]; typeOnly?: boolean }> = {
'src/features/related-findings/RelatedFindings.tsx': { engine: 'Remediation Engine' },
'src/features/search-filter/business-impact-controls.ts': { engine: ['Report Engine', 'Context Engine'] },
'src/features/dashboard/DashboardPanel.tsx': { engine: ['Context Engine', 'Report Engine'] },
'src/features/dashboard/DashboardPanel.tsx': { engine: ['Context Engine', 'Report Engine', 'Compliance Engine'] },
'src/features/dashboard/ClientWorkPackagesPanel.tsx': { engine: ['Remediation Engine', 'Context Engine'] },
'src/api/assessor-api-contract.ts': { engine: ['Context Engine', 'Remediation Engine'], typeOnly: true },
'src/api/assessor-api-contract.ts': { engine: ['Context Engine', 'Remediation Engine', 'Compliance Engine'], typeOnly: true },
'src/api/assessor-api-client.ts': { engine: 'Compliance Engine', typeOnly: true },
'src/features/finding-reader/FindingReader.tsx': { engine: ['Remediation Engine', 'Context Engine', 'Compliance Engine'] },
'src/features/results-browser/ResultsBrowser.tsx': { engine: 'Compliance Engine' },
'src/features/project-import/DataHub.tsx': { engine: 'Compliance Engine' },
'src/features/actionlist/ActionlistControls.tsx': { engine: ['Context Engine', 'Remediation Engine'] },
'src/features/finding-reader/FindingReader.tsx': { engine: ['Remediation Engine', 'Context Engine'] },
'src/features/finding-reader/FindingContext.tsx': { engine: 'Context Engine' },
'src/features/mitre-graph/graph-filter-bridge.ts': { engine: 'Context Engine' },
'src/features/mitre-graph/ObsidianGraphView.tsx': { engine: 'Context Engine' },
@ -72,7 +76,7 @@ const EXTENSION_POINTS: Record<string, { engine: string | readonly string[]; typ
'src/features/search-filter/work-facets.ts': { engine: ['Context Engine', 'Remediation Engine'] },
'src/features/sidebar/SidebarSecurityDomains.tsx': { engine: ['Context Engine', 'Remediation Engine'] },
'server/assessor-http-server.ts': { engine: 'any' },
'server/index.ts': { engine: ['Report Engine', 'Remediation Engine'] }
'server/index.ts': { engine: ['Report Engine', 'Remediation Engine', 'Compliance Engine'] }
};
// Core areas that hold data, evaluation and rules. No file in them may reach any engine,
@ -83,7 +87,7 @@ const ENGINE_FREE_AREAS = ['Ingest', 'Normalization', 'Evaluation', 'Store', 'Di
describe('Core Engine and engines boundary', () => {
it('knows the registered engines and finds source files for each of them', () => {
const engines = areas.ENGINE_PATHS.map(([engine]) => engine);
expect(engines).toEqual(expect.arrayContaining(['Context Engine', 'Report Engine']));
expect(engines).toEqual(expect.arrayContaining(['Context Engine', 'Report Engine', 'Remediation Engine', 'Compliance Engine']));
for (const engine of engines) {
expect(allSources().some(file => engineOf(posix(file)) === engine), engine).toBe(true);
}

View File

@ -0,0 +1,104 @@
// @vitest-environment jsdom
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AssessorApiClient } from '../../src/api/assessor-api-client';
import { requestActivity } from '../../src/api/request-activity';
import { resetEnginePreferencesForTests, setEngineEnabled } from '../../src/app/engine-preferences';
import type { RegulatoryControlOverviewResponse } from '../../src/compliance/regulatory-mapping';
import { ClientIsoControls } from '../../src/compliance/ui/ClientIsoControls';
import { markRegulatoryDecisionSaved } from '../../src/compliance/ui/decision-revision';
import { workRecordIdsForResult } from '../../src/features/results-browser/work-record-lookup';
import { makeSheet } from '../../src/importers/sheet-factory';
// Client Info `ISO controls`: one tile per accepted control with its number of findings, laid out like
// the Context heatmap; a tile opens exactly its findings in Work. Switched off, nothing renders or loads.
const overview: RegulatoryControlOverviewResponse = {
version: 1, projectId: 'dummy-project', scope: { assessmentIds: ['dummy-assessment'], scanRunIds: [] }, findingCount: 3,
controls: [
{ controlId: '8.20', annexAControlId: 'A.8.20', title: 'Networks security', theme: 'Technological', findings: [
{ resultProjectionId: 'scanner-finding:dummy-a', sourceKind: 'scanner-finding', sourceResultId: 'dummy-a' },
{ resultProjectionId: 'scanner-finding:dummy-b', sourceKind: 'scanner-finding', sourceResultId: 'dummy-b' }] },
{ controlId: '5.15', annexAControlId: 'A.5.15', theme: 'Organizational', findings: [
{ resultProjectionId: 'scanner-finding:dummy-c', sourceKind: 'scanner-finding', sourceResultId: 'dummy-c' }] }
]
};
let host: HTMLDivElement;
let root: Root;
const onOpenFindings = vi.fn();
const render = () => act(async () => {
root.render(<ClientIsoControls projectId="dummy-project" assessmentIds={['dummy-assessment']} scanRunIds={[]}
backendStatus="connected" onOpenFindings={onOpenFindings}/>);
await new Promise(resolve => setTimeout(resolve, 0));
});
beforeEach(() => {
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
localStorage.clear();
resetEnginePreferencesForTests();
onOpenFindings.mockReset();
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
});
afterEach(async () => {
await act(async () => { root.unmount(); });
host.remove();
vi.restoreAllMocks();
vi.unstubAllGlobals();
resetEnginePreferencesForTests();
});
describe('Client Info ISO controls', () => {
it('shows each accepted control with its finding count and opens exactly its findings', async () => {
const request = vi.spyOn(AssessorApiClient.prototype, 'getRegulatoryControlOverview').mockResolvedValue(overview);
await render();
expect(request).toHaveBeenCalledWith('dummy-project', { assessmentIds: ['dummy-assessment'], scanRunIds: [] });
expect(host.querySelector('h2')?.textContent).toBe('ISO controls');
expect(host.querySelector('.iso-controls__total')?.textContent).toBe('Findings: 3');
const tiles = [...host.querySelectorAll<HTMLButtonElement>('.iso-controls__cell')];
expect(tiles.map(tile => [...tile.children].map(part => part.textContent))).toEqual([
['Technological', 'A.8.20 · Networks security', '2 findings'],
['Organizational', 'A.5.15', '1 finding']
]);
await act(async () => tiles[0].click());
expect(onOpenFindings).toHaveBeenCalledWith(overview.controls[0].findings);
});
it('reloads after a control decision and says so when nothing is accepted', async () => {
const request = vi.spyOn(AssessorApiClient.prototype, 'getRegulatoryControlOverview')
.mockResolvedValueOnce({ ...overview, findingCount: 0, controls: [] }).mockResolvedValue(overview);
await render();
expect(host.querySelector('.iso-controls__empty')?.textContent).toBe('No accepted ISO controls in this timeslot.');
await act(async () => { markRegulatoryDecisionSaved(); await new Promise(resolve => setTimeout(resolve, 0)); });
expect(request).toHaveBeenCalledTimes(2);
expect(host.querySelectorAll('.iso-controls__cell')).toHaveLength(2);
});
it('renders nothing and requests nothing while the Compliance Engine is off', async () => {
const request = vi.spyOn(AssessorApiClient.prototype, 'getRegulatoryControlOverview').mockResolvedValue(overview);
setEngineEnabled('compliance', false);
await render();
expect(host.innerHTML).toBe('');
expect(request).not.toHaveBeenCalled();
});
it('names the overview request in the activity log as Compliance Engine work', () => {
expect(requestActivity('/projects/p/regulatory-control-overview?assessmentIds=a')).toEqual({ area: 'Compliance Engine', label: 'Loading ISO control overview' });
});
it('places the section below the Context heatmap and opens the findings by their Work records', () => {
const source = readFileSync(join(process.cwd(), 'src/features/dashboard/DashboardPanel.tsx'), 'utf8');
expect(source.indexOf('<ClientIsoControls')).toBeGreaterThan(source.indexOf('<ClientContextHeatmap'));
expect(source.indexOf('<ClientIsoControls')).toBeLessThan(source.indexOf('client-environment-grid'));
expect(source).toContain('setPathFindingIds([...new Set(findings.flatMap(finding => workRecordIdsForResult(dataset, finding)))])');
// A scanner finding resolves to its Work record through the occurrence id.
const sheet = makeSheet('Dummy', [['Title', 'Status'], ['Dummy check', 'Fail']], '', 'dummy.csv', { isProjectSheet: true });
const record = { ...sheet.analysis.records[0], findingOccurrenceId: 'dummy-a' };
const dataset = { fileName: 'Dummy', sheets: [{ ...sheet, analysis: { ...sheet.analysis, records: [record] } }] } as never;
expect(workRecordIdsForResult(dataset, overview.controls[0].findings[0])).toEqual([record.id]);
});
});

View File

@ -0,0 +1,148 @@
// @vitest-environment jsdom
import { act, type ReactNode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AssessorApiClient } from '../../src/api/assessor-api-client';
import { requestActivity } from '../../src/api/request-activity';
import { resetEnginePreferencesForTests } from '../../src/app/engine-preferences';
import type { RegulatoryMappingBatchResponse } from '../../src/compliance/regulatory-mapping';
import { useRegulatoryMappingBatch } from '../../src/compliance/ui/RegulatoryMappingBatchDialog';
import { useRegulatoryMapping } from '../../src/compliance/ui/use-regulatory-mapping';
import type { RegulatoryMappingResponse } from '../../src/compliance/regulatory-mapping';
import { activitySnapshot, activityStatusSnapshot, clearFinishedActivities } from '../../src/platform/activity-store';
// The activity log names Compliance Engine work as such: its requests never read as Core client work,
// and backend work keeps the log busy until it really ends.
describe('Compliance Engine requests in the activity log', () => {
it.each([
['/projects/p/regulatory-mappings/scanner-finding%3Ao', 'GET', 'Loading ISO mapping'],
['/projects/p/regulatory-mapping-runs', 'POST', 'Generating ISO control proposals'],
['/projects/p/regulatory-mapping-decisions', 'POST', 'Saving ISO mapping decision'],
['/projects/p/regulatory-mapping-batches?assessmentIds=a&deviation=true', 'GET', 'Loading ISO mapping batch status'],
['/projects/p/regulatory-mapping-batches', 'POST', 'Starting ISO mapping batch'],
['/reference-data/iso-corpus', 'GET', 'Loading ISO corpus status'],
['/reference-data/iso-corpus', 'POST', 'Uploading ISO corpus']
])('labels %s %s', (path, method, label) => {
expect(requestActivity(path, method)).toEqual({ area: 'Compliance Engine', label });
});
it('keeps unrelated client requests in the Core', () => {
expect(requestActivity('/projects/p/import-files')).toEqual({ area: 'Core Engine', label: 'Loading imported files' });
expect(requestActivity('/projects')).toEqual({ area: 'Core Engine', label: 'Loading clients' });
});
});
function batchResponse(state: RegulatoryMappingBatchResponse['state']): RegulatoryMappingBatchResponse {
return { version: 1, projectId: 'dummy-project', scope: { assessmentIds: ['dummy-assessment'], scanRunIds: [], filters: {} },
generationEnabled: true, state, pollAfterMs: 5 } as RegulatoryMappingBatchResponse;
}
const scope = { assessmentIds: ['dummy-assessment'], scanRunIds: [], filters: {} };
function BatchProbe({ projectId = 'dummy-project' }: { projectId?: string }): ReactNode {
useRegulatoryMappingBatch(projectId, scope);
return null;
}
const batchRows = () => activitySnapshot().filter(row => row.area === 'Compliance Engine' && row.label.startsWith('Mapping all ISO controls'));
const settle = () => act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); });
let host: HTMLDivElement;
let root: Root;
beforeEach(() => {
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
localStorage.clear();
resetEnginePreferencesForTests();
clearFinishedActivities();
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
});
afterEach(async () => {
await act(async () => { root.unmount(); });
host.remove();
vi.restoreAllMocks();
vi.unstubAllGlobals();
clearFinishedActivities();
});
describe('Compliance Engine backend work in the activity log', () => {
it('keeps a running ISO batch busy until the backend completes it', async () => {
const states: RegulatoryMappingBatchResponse['state'][] = ['running', 'running', 'completed'];
vi.spyOn(AssessorApiClient.prototype, 'getRegulatoryMappingBatch').mockImplementation(async () => batchResponse(states.shift() ?? 'completed'));
await act(async () => root.render(<BatchProbe/>));
await act(async () => { await Promise.resolve(); });
expect(batchRows().map(row => row.state)).toEqual(['running']);
expect(activityStatusSnapshot().ready).toBe(false);
const generation = activityStatusSnapshot().generation;
await settle(); await settle();
expect(batchRows().map(row => row.state)).toEqual(['completed']);
expect(activityStatusSnapshot().ready).toBe(true);
// Repeated batch status checks start no further entries.
expect(activityStatusSnapshot().generation).toBe(generation);
});
it('marks the entry failed when the backend batch fails', async () => {
const states: RegulatoryMappingBatchResponse['state'][] = ['running', 'failed'];
vi.spyOn(AssessorApiClient.prototype, 'getRegulatoryMappingBatch').mockImplementation(async () => batchResponse(states.shift() ?? 'failed'));
await act(async () => root.render(<BatchProbe/>));
await settle(); await settle();
expect(batchRows().map(row => row.state)).toEqual(['failed']);
expect(activityStatusSnapshot().failed).toBe(1);
});
it('ends the entry with a note when the view stops observing a running batch', async () => {
vi.spyOn(AssessorApiClient.prototype, 'getRegulatoryMappingBatch').mockResolvedValue(batchResponse('running'));
await act(async () => root.render(<BatchProbe/>));
await act(async () => { await Promise.resolve(); });
expect(batchRows().map(row => row.state)).toEqual(['running']);
await act(async () => { root.unmount(); });
root = createRoot(host);
expect(batchRows().map(row => [row.state, row.label])).toEqual([['completed', 'Mapping all ISO controls continues in the backend']]);
expect(activityStatusSnapshot().ready).toBe(true);
});
});
function mappingResponse(state: RegulatoryMappingResponse['state'], id: string): RegulatoryMappingResponse {
return { version: 1, projectId: 'dummy-project', resultProjectionId: `scanner-finding:${id}`, generationEnabled: true, state, decisions: [], pollAfterMs: 5 };
}
function MappingProbe({ id }: { id: string }): ReactNode {
const mapping = useRegulatoryMapping('dummy-project', `scanner-finding:${id}`, 'connected');
return <button type="button" onClick={() => void mapping.start()}>Generate</button>;
}
const mappingRows = () => activitySnapshot().filter(row => row.area === 'Compliance Engine' && row.label.startsWith('Mapping ISO controls'));
describe('Compliance Engine single mapping in the activity log', () => {
it('keeps a generated mapping running after the window closes until the backend completes it', async () => {
const states: RegulatoryMappingResponse['state'][] = ['empty', 'running', 'running', 'succeeded'];
// Replaced below the activity logging, so every client logs exactly as in the application.
const transport = vi.spyOn(AssessorApiClient.prototype as unknown as { performRequest(path: string, init: RequestInit): Promise<unknown> }, 'performRequest')
.mockImplementation(async (path: string, init: RequestInit) => init.method === 'POST'
? mappingResponse('queued', 'closed-window') : mappingResponse(states.shift() ?? 'succeeded', 'closed-window'));
await act(async () => root.render(<MappingProbe id="closed-window"/>));
await act(async () => { await Promise.resolve(); });
await act(async () => host.querySelector('button')!.click());
expect(mappingRows().map(row => row.state)).toEqual(['queued']);
// Status checks while it runs start no entries of their own, so the activity panel does not reopen and jump.
const generation = activityStatusSnapshot().generation;
// Closing the window or leaving the finding does not end the observation.
await act(async () => { root.unmount(); });
root = createRoot(host);
expect(mappingRows().map(row => row.state)).toEqual(['queued']);
expect(activityStatusSnapshot().ready).toBe(false);
await settle(); await settle(); await settle();
expect(mappingRows().map(row => [row.state, row.label])).toEqual([['completed', 'Mapping ISO controls']]);
expect(activityStatusSnapshot().ready).toBe(true);
expect(transport.mock.calls.filter(([path]) => String(path).includes('/regulatory-mappings/')).length).toBeGreaterThanOrEqual(4);
expect(activityStatusSnapshot().generation).toBe(generation);
// Only the first load of the finding and the generate request are logged; the status checks are not.
expect(activitySnapshot().filter(row => row.area === 'Compliance Engine').map(row => row.label).sort())
.toEqual(['Generating ISO control proposals', 'Loading ISO mapping', 'Mapping ISO controls']);
});
it('marks the mapping failed when the backend run fails', async () => {
const states: RegulatoryMappingResponse['state'][] = ['running', 'failed'];
vi.spyOn(AssessorApiClient.prototype, 'getRegulatoryMappings').mockImplementation(async () => mappingResponse(states.shift() ?? 'failed', 'failing'));
await act(async () => root.render(<MappingProbe id="failing"/>));
await settle(); await settle();
expect(mappingRows().map(row => row.state)).toEqual(['failed']);
});
});

View File

@ -0,0 +1,99 @@
import { describe, expect, it, vi } from 'vitest';
import { RegulatoryFindingRetrievalService } from '../../server/compliance/regulatory-finding-retrieval';
import { RegulatoryMappingService } from '../../server/compliance/regulatory-mapping-service';
import { complianceReadPortFrom } from '../../src/compliance/compliance-store';
import { LocalComplianceStore } from '../../src/compliance/local-compliance-store';
import type { RegulatoryChunk, RegulatoryRetrievalRequest } from '../../src/compliance/regulatory-rag';
import type { ScanRun } from '../../src/domain/canonical-model';
import { LocalAssessorRepository } from '../../src/persistence/local-assessor-repository';
// Permanent on/off invariance of the Compliance Engine (AGENTS.md, "Core Engine and engines"): the Core
// works unchanged with the engine switched off, and running the engine - a single mapping, a decision and
// a filtered batch - leaves every stored ASSESSOR value and the repository revision exactly as they were.
// The engine writes only its own store.
const stamp = '2026-10-05T08:00:00.000Z';
const confidence = { level: 'high' as const, score: 1, reasons: ['synthetic'] };
const provenance = { decisionSource: 'source-native' as const, confidence, mappingVersion: '1.0.0' };
function chunk(sourceStandard: 'ISO/IEC 27001' | 'ISO/IEC 27002'): RegulatoryChunk {
const reference = sourceStandard === 'ISO/IEC 27001';
return {
schemaVersion: 2, corpusId: 'iso-test', corpusVersion: 'v2', documentId: reference ? '27001-5.1' : '27002-5.1-purpose',
framework: 'ISO/IEC 27002', frameworkVersion: '2022', controlId: '5.1', annexAControlId: 'A.5.1',
controlTheme: 'organizational', sourceStandard, sourceEdition: '2022', nationalEdition: 'DIN 2024',
sectionKind: reference ? 'control' : 'purpose', sourcePageStart: 1, sourcePageEnd: 1,
retrievalRole: reference ? 'reference' : 'semantic', parserVersion: 'test', sourceSha256: reference ? '1'.repeat(64) : '2'.repeat(64),
chunkId: reference ? 'reference-5.1' : 'semantic-5.1', chunkIndex: 0, language: 'de', title: 'Synthetic control',
text: reference ? 'Synthetic normative statement.' : 'Synthetic semantic evidence.', textSha256: 'a'.repeat(64)
};
}
async function syntheticRepository(): Promise<LocalAssessorRepository> {
const repository = new LocalAssessorRepository();
await repository.saveProject({ id: 'dummy-project', name: 'Dummy Customer', createdAt: stamp, updatedAt: stamp, attributes: {} });
await repository.saveAssessment({ id: 'dummy-assessment', projectId: 'dummy-project', name: 'Dummy', createdAt: stamp, updatedAt: stamp });
const scanRun: ScanRun = { id: 'dummy-run', assessmentId: 'dummy-assessment', sequence: 1, label: 'Dummy',
tool: { id: 'purple-knight', name: 'Purple Knight' }, importedAt: stamp };
const session = await repository.beginImport({ sessionId: 'dummy-session', projectId: 'dummy-project', assessmentId: 'dummy-assessment', scanRun });
await session.stage({
importFiles: [{ id: 'dummy-file', scanRunId: scanRun.id, fileName: 'dummy.csv', format: 'CSV', sizeBytes: 10, importedAt: stamp,
detectedTool: scanRun.tool, detection: confidence,
processedWith: { parserId: 'csv', parserVersion: '1.0.0', profileId: 'purple-knight', profileVersion: '1.0.0', mappingVersion: '1.0.0' },
sourceArtifact: { kind: 'not-retained', reason: 'synthetic' } }],
findingDefinitions: [{ id: 'dummy-definition', canonicalKey: 'purple-knight:A-SmbSigning',
identity: { version: 1, strategy: 'tool-rule-id', durable: true, evidence: ['synthetic'] },
title: 'SMB signing is not required on domain controllers', category: 'Synthetic', frameworkReferences: [], createdAt: stamp, updatedAt: stamp }],
findingOccurrences: [{ id: 'dummy-occurrence', definitionId: 'dummy-definition', scanRunId: scanRun.id, importFileId: 'dummy-file',
sourceIdentity: { tool: scanRun.tool, originalRuleId: 'A-SmbSigning', canonicalRuleId: 'A-SmbSigning',
originalTitle: 'SMB signing is not required on domain controllers' },
sourcePosition: { rowIndex: 1 }, originalFields: [{ key: 'Status', label: 'Status', value: 'Fail', columnIndex: 0 }],
fieldMappings: [], severity: { originalValue: 'High', normalizedValue: 'high', provenance },
status: { originalValue: 'Fail', normalizedValue: 'failed', provenance } }]
});
await session.commit();
return repository;
}
describe('Compliance Engine on/off invariance', () => {
it('leaves every stored ASSESSOR value and the repository revision unchanged', async () => {
const repository = await syntheticRepository();
// Switched off: the Core alone, read before any engine work.
const off = { revision: repository.revision, data: JSON.stringify(await repository.exportProject('dummy-project')) };
const resultDbOff = JSON.stringify(await repository.queryUnifiedResults({ audience: 'result-db', projectId: 'dummy-project' }));
const store = new LocalComplianceStore();
const service = new RegulatoryMappingService(complianceReadPortFrom(repository), store, {
findingRetrieval: new RegulatoryFindingRetrievalService({ retrieve: vi.fn(async (_request: RegulatoryRetrievalRequest) => [{ score: 0.9, chunk: chunk('ISO/IEC 27002') }]) }),
index: { ensureCollection: vi.fn(), replaceDocuments: vi.fn(), searchDense: vi.fn(), list: vi.fn(async () => [chunk('ISO/IEC 27001')]) } as never,
client: { model: 'work-model', complete: vi.fn(async () => ({ value: {
schemaVersion: 1, outcome: 'mapped', mappings: [{ controlId: '5.1', relationship: 'primary', confidence: 'high',
rationale: 'Synthetic rationale.', evidenceChunkIds: ['semantic-5.1', 'reference-5.1'] }]
} })) } as never,
corpusId: 'iso-test', corpusVersion: 'v2', embeddingModel: 'bge-m3', now: () => new Date(stamp)
});
const resultProjectionId = 'scanner-finding:dummy-occurrence';
await service.start('dummy-project', { resultProjectionId });
await service.close();
// The first proposal is accepted automatically; a manual decision then replaces it.
const automatic = (await service.get('dummy-project', resultProjectionId)).decisions[0];
await service.decide('dummy-project', { resultProjectionId, controlId: '5.1', decision: 'rejected', expectedLatestDecisionId: automatic.id });
await service.startBatch('dummy-project', { assessmentIds: ['dummy-assessment'], scanRunIds: [], filters: {}, idempotencyKey: 'dummy-batch-1' });
await service.close();
// The engine really ran and kept its results in its own store.
const engine = await store.exportProject('dummy-project');
expect(engine.regulatoryMappingRuns.map(run => run.status)).toEqual(['succeeded']);
expect(engine.regulatoryMappingDecisions.map(decision => decision.decision)).toEqual(['accepted', 'rejected']);
expect(engine.regulatoryMappingBatchRuns.map(batch => batch.status)).toEqual(['completed']);
// Switched on: the Core is untouched.
expect(repository.revision).toBe(off.revision);
expect(JSON.stringify(await repository.exportProject('dummy-project'))).toBe(off.data);
expect(JSON.stringify(await repository.queryUnifiedResults({ audience: 'result-db', projectId: 'dummy-project' }))).toBe(resultDbOff);
});
it('gives the engine no Core write method', () => {
const port = complianceReadPortFrom(new LocalAssessorRepository());
expect(Object.keys(port).sort()).toEqual(['getProject', 'getUnifiedResultById', 'listAssessments', 'listProjectScanRuns',
'listProjects', 'queryUnifiedResults']);
});
});

View File

@ -0,0 +1,148 @@
// @vitest-environment jsdom
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { act, type ReactNode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AssessorApiClient } from '../../src/api/assessor-api-client';
import { resetEnginePreferencesForTests, setEngineEnabled } from '../../src/app/engine-preferences';
import { useApp } from '../../src/app/AppProvider';
import type { RegulatoryCorpusStatus } from '../../src/compliance/regulatory-corpus-management';
import type { RegulatoryMappingResponse } from '../../src/compliance/regulatory-mapping';
import { IsoCorpusLibrary } from '../../src/compliance/ui/IsoCorpusLibrary';
import { useRegulatoryMappingBatch } from '../../src/compliance/ui/RegulatoryMappingBatchDialog';
import { FindingReader } from '../../src/features/finding-reader/FindingReader';
import { makeSheet } from '../../src/importers/sheet-factory';
vi.mock('../../src/app/AppProvider', () => {
const useApp = vi.fn();
return { useApp, useOptionalApp: useApp };
});
// Compliance Engine switch (AGENTS.md, "Core Engine and engines"): switched off, the Finding Reader,
// Result DB and Data Hub show none of its controls and send none of its requests; switched on again,
// the Finding Reader ISO panel starts closed.
let host: HTMLDivElement;
let root: Root;
function scannerRecord() {
const record = makeSheet('Dummy', [['Title', 'Status', 'Source: Scan'], ['Dummy SMB signing check', 'Fail', 'Purple Knight']],
'', 'dummy.csv', { isProjectSheet: true }).analysis.records[0];
return { ...record, findingOccurrenceId: 'dummy-occurrence' };
}
const mappingResponse: RegulatoryMappingResponse = {
version: 1, projectId: 'dummy-project', resultProjectionId: 'scanner-finding:dummy-occurrence',
generationEnabled: true, state: 'empty', decisions: []
};
async function renderReader() {
await act(async () => {
root.render(<FindingReader record={scannerRecord()} title="Dummy SMB signing check" linkedSheets={[]} resultReferences={[]}
search="" position={0} recordCount={1} toolId="purple-knight" onPrevious={vi.fn()} onNext={vi.fn()} onReview={vi.fn()}
projectId="dummy-project" backendStatus="connected"/>);
await new Promise(resolve => setTimeout(resolve, 0));
});
}
const isoButton = () => [...host.querySelectorAll('button')].find(button => button.textContent?.startsWith('Map ISO controls'));
function BatchProbe(): ReactNode {
const batch = useRegulatoryMappingBatch('dummy-project', { assessmentIds: ['dummy-assessment'], scanRunIds: [], filters: {} });
return <output>{batch.available ? 'available' : 'off'}</output>;
}
beforeEach(() => {
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
localStorage.clear();
resetEnginePreferencesForTests();
// The Context Engine is not under test here.
setEngineEnabled('context', false);
vi.mocked(useApp).mockReturnValue({ targetProjectId: 'dummy-project', activeAssessmentIds: [], dataset: null, setFacetFilter: vi.fn() } as unknown as ReturnType<typeof useApp>);
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
});
afterEach(async () => {
await act(async () => { root.unmount(); });
host.remove();
vi.restoreAllMocks();
vi.unstubAllGlobals();
resetEnginePreferencesForTests();
});
describe('Compliance Engine switch', () => {
it('removes the Finding Reader ISO window, section and requests while off and reopens closed', async () => {
const request = vi.spyOn(AssessorApiClient.prototype, 'getRegulatoryMappings').mockResolvedValue(mappingResponse);
const isoWindow = () => document.querySelector('[role="dialog"].regulatory-mapping-dialog');
setEngineEnabled('compliance', false);
await renderReader();
expect(isoButton()).toBeUndefined();
expect(request).not.toHaveBeenCalled();
expect(host.querySelector('[data-iso-controls]')).toBeNull();
// Switched on, the mapping loads with the finding; the button opens it as a window like Accepted Risk.
await act(async () => { setEngineEnabled('compliance', true); await new Promise(resolve => setTimeout(resolve, 0)); });
expect(request).toHaveBeenCalledTimes(1);
expect(isoWindow()).toBeNull();
await act(async () => { isoButton()!.click(); await new Promise(resolve => setTimeout(resolve, 0)); });
expect(isoWindow()?.querySelector('.regulatory-mapping-panel')).not.toBeNull();
expect(host.querySelector('.regulatory-mapping-panel')).toBeNull();
await act(async () => isoWindow()!.querySelector<HTMLButtonElement>('[aria-label="Close window"]')!.click());
expect(isoWindow()).toBeNull();
await act(async () => { isoButton()!.click(); });
await act(async () => { setEngineEnabled('compliance', false); });
expect(isoButton()).toBeUndefined();
expect(isoWindow()).toBeNull();
await act(async () => { setEngineEnabled('compliance', true); });
expect(isoButton()?.getAttribute('aria-expanded')).toBe('false');
expect(isoWindow()).toBeNull();
expect(request).toHaveBeenCalledTimes(1);
});
it('lists the controls accepted for the finding as a reader section like Description', async () => {
const decision = (id: string, controlId: string, value: 'accepted' | 'rejected', createdAt: string) => ({
version: 1 as const, id, ruleKey: 'purple-knight:dummy', sourceTool: 'purple-knight', mappingId: 'dummy-mapping', controlId, decision: value, createdAt });
vi.spyOn(AssessorApiClient.prototype, 'getRegulatoryMappings').mockResolvedValue({ ...mappingResponse, state: 'succeeded',
run: { candidates: [{ controlId: '8.20', annexAControlId: 'A.8.20', title: 'Networks security', score: 0.9, evidence: [] },
{ controlId: '5.1', annexAControlId: 'A.5.1', title: 'Policies for information security', score: 0.8, evidence: [] }] } as never,
decisions: [decision('d3', '5.1', 'rejected', '2026-10-05T10:02:00Z'), decision('d2', '8.20', 'accepted', '2026-10-05T10:01:00Z'),
decision('d1', '5.1', 'accepted', '2026-10-05T10:00:00Z'), decision('d0', '7.4', 'accepted', '2026-10-05T09:00:00Z')] });
await renderReader();
const section = host.querySelector('[data-iso-controls]')!;
expect(section.querySelector('h4')?.textContent).toBe('ISO controls');
// A later rejection replaces an earlier acceptance; a control without a retrieved title keeps its Annex A id.
expect([...section.querySelectorAll('li')].map(item => item.textContent)).toEqual(['A.7.4', 'A.8.20Networks security']);
expect(isoButton()?.textContent).toBe('Map ISO controls (2)');
});
it('requests no Result DB batch status while off and hides the batch action', async () => {
const request = vi.spyOn(AssessorApiClient.prototype, 'getRegulatoryMappingBatch').mockResolvedValue({
version: 1, projectId: 'dummy-project', scope: { assessmentIds: ['dummy-assessment'], scanRunIds: [], filters: {} },
generationEnabled: true, state: 'empty'
} as never);
setEngineEnabled('compliance', false);
await act(async () => root.render(<BatchProbe/>));
expect(host.textContent).toBe('off');
expect(request).not.toHaveBeenCalled();
await act(async () => { setEngineEnabled('compliance', true); });
expect(host.textContent).toBe('available');
expect(request).toHaveBeenCalledTimes(1);
const source = readFileSync(join(process.cwd(), 'src/features/results-browser/ResultsBrowser.tsx'), 'utf8');
expect(source).toContain('{regulatoryBatch.available && <button');
expect(source).toContain('{batchDialogOpen && regulatoryBatch.available && <RegulatoryMappingBatchDialog');
});
it('renders no Data Hub ISO corpus tile and requests no corpus status while off', async () => {
const status: RegulatoryCorpusStatus = { version: 1, configured: true, active: null, job: null };
const request = vi.spyOn(AssessorApiClient.prototype, 'getIsoCorpusStatus').mockResolvedValue(status);
setEngineEnabled('compliance', false);
await act(async () => root.render(<IsoCorpusLibrary/>));
expect(host.innerHTML).toBe('');
expect(request).not.toHaveBeenCalled();
await act(async () => { setEngineEnabled('compliance', true); });
expect(host.innerHTML).not.toBe('');
expect(request).toHaveBeenCalledTimes(1);
});
});

View File

@ -0,0 +1,56 @@
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import type { Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, expect, it } from 'vitest';
import { createAssessorHttpServer } from '../../server/assessor-http-server';
import { LocalComplianceStore } from '../../src/compliance/local-compliance-store';
import type { RegulatoryMappingBatchRun } from '../../src/compliance/regulatory-mapping';
import { LocalAssessorRepository } from '../../src/persistence/local-assessor-repository';
// The project export keeps the engine's data: the Core export and the Compliance Engine's own
// project data are combined at the HTTP route, not inside the Core repository.
const stamp = '2026-10-05T08:00:00.000Z';
let directory: string;
let server: Server | undefined;
beforeEach(async () => {
directory = await mkdtemp(join(tmpdir(), 'assessor-compliance-export-'));
await writeFile(join(directory, 'index.html'), '<main>synthetic app</main>');
});
afterEach(async () => {
await new Promise(resolve => server ? server.close(resolve) : resolve(undefined));
server = undefined;
await rm(directory, { recursive: true, force: true });
});
async function exportVia(complianceExport?: LocalComplianceStore) {
const repository = new LocalAssessorRepository();
await repository.saveProject({ id: 'dummy-project', name: 'Dummy Customer', createdAt: stamp, updatedAt: stamp, attributes: {} });
server = createAssessorHttpServer({ repository, staticRoot: directory, ...(complianceExport ? { complianceExport } : {}) });
await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve));
const { port } = server.address() as AddressInfo;
return (await fetch(`http://127.0.0.1:${port}/api/v1/projects/dummy-project/export`)).json();
}
it('adds the Compliance Engine project data to the Core project export', async () => {
const store = new LocalComplianceStore();
const batch = await store.createRegulatoryMappingBatchRun({
version: 1, id: 'dummy-batch', projectId: 'dummy-project', scopeKey: 'scope', filterHash: 'a'.repeat(64),
idempotencyKey: 'dummy-batch-1', assessmentIds: ['dummy-assessment'], scanRunIds: [], filters: {}, status: 'queued',
counts: { filteredResultCount: 0, excludedNonScannerCount: 0, eligibleFindingCount: 0, unsupportedFindingCount: 0,
distinctRuleCount: 0, reusedSucceededRuleCount: 0, reusedActiveRuleCount: 0, scheduledRuleCount: 0,
succeededRuleCount: 0, failedRuleCount: 0 },
createdAt: stamp, updatedAt: stamp
} satisfies RegulatoryMappingBatchRun);
const exported = await exportVia(store);
expect(exported).toMatchObject({ project: { id: 'dummy-project' }, regulatoryMappingBatchRuns: [batch],
regulatoryMappingRuns: [], regulatoryMappingDecisions: [] });
});
it('keeps the Core project export complete without the Compliance Engine', async () => {
const exported = await exportVia();
expect(exported).toMatchObject({ project: { id: 'dummy-project' } });
expect(exported).not.toHaveProperty('regulatoryMappingBatchRuns');
});

View File

@ -4,7 +4,7 @@ import {
embeddingEndpoint,
EmbeddingClientError,
OpenAiCompatibleEmbeddingClient
} from '../../server/regulatory/embedding-client';
} from '../../server/compliance/embedding-client';
describe('regulatory embedding client', () => {
it('allows loopback HTTP, requires remote HTTPS, and requires explicit dimensions', () => {

View File

@ -4,8 +4,8 @@ import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, expect, it, vi } from 'vitest';
import { AssessorApiClient } from '../../src/api/assessor-api-client';
import type { RegulatoryCorpusStatus } from '../../src/domain/regulatory-corpus-management';
import { IsoCorpusLibrary } from '../../src/features/project-import/IsoCorpusLibrary';
import type { RegulatoryCorpusStatus } from '../../src/compliance/regulatory-corpus-management';
import { IsoCorpusLibrary } from '../../src/compliance/ui/IsoCorpusLibrary';
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });

View File

@ -5,7 +5,7 @@ import {
type ParsedControl,
type ParsedPdf,
type PdfLine
} from '../../server/regulatory/iso-pdf-corpus';
} from '../../server/compliance/iso-pdf-corpus';
const line = (text: string, page: number): PdfLine => ({ text, page, y: 500, spans: [{ text, page, x: 100, y: 500, width: text.length * 5, height: 10 }] });

View File

@ -1,8 +1,8 @@
import { describe, expect, it } from 'vitest';
import { createQdrantRegulatoryIndexFromEnvironment, REGULATORY_QDRANT_COLLECTION } from '../../server/regulatory/qdrant-regulatory-index';
import { DenseRegulatoryCandidateRetriever, RegulatoryIngestionService } from '../../server/regulatory/regulatory-rag-service';
import type { RegulatoryControlDocument } from '../../src/domain/regulatory-rag';
import type { TextEmbeddingClient } from '../../server/regulatory/embedding-client';
import { createQdrantRegulatoryIndexFromEnvironment, REGULATORY_QDRANT_COLLECTION } from '../../server/compliance/qdrant-regulatory-index';
import { DenseRegulatoryCandidateRetriever, RegulatoryIngestionService } from '../../server/compliance/regulatory-rag-service';
import type { RegulatoryControlDocument } from '../../src/compliance/regulatory-rag';
import type { TextEmbeddingClient } from '../../server/compliance/embedding-client';
const runIntegration = process.env.ASSESSOR_QDRANT_INTEGRATION === '1';
const describeQdrant = runIntegration ? describe : describe.skip;

View File

@ -1,11 +1,11 @@
import { describe, expect, it, vi } from 'vitest';
import type { RegulatoryChunk } from '../../src/domain/regulatory-rag';
import type { RegulatoryChunk } from '../../src/compliance/regulatory-rag';
import {
createQdrantRegulatoryIndexFromEnvironment,
QdrantClientError,
QdrantRegulatoryIndex,
REGULATORY_QDRANT_COLLECTION
} from '../../server/regulatory/qdrant-regulatory-index';
} from '../../server/compliance/qdrant-regulatory-index';
const chunk: RegulatoryChunk = {
schemaVersion: 1,

View File

@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import type { RegulatoryControlDocument } from '../../src/domain/regulatory-rag';
import { chunkRegulatoryControl, regulatoryChunkEmbeddingText, validateRegulatoryControlDocument } from '../../server/regulatory/regulatory-chunker';
import type { RegulatoryControlDocument } from '../../src/compliance/regulatory-rag';
import { chunkRegulatoryControl, regulatoryChunkEmbeddingText, validateRegulatoryControlDocument } from '../../server/compliance/regulatory-chunker';
const document: RegulatoryControlDocument = {
schemaVersion: 1,

View File

@ -5,10 +5,10 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createAssessorHttpServer } from '../../server/assessor-http-server';
import { RegulatoryCorpusUploadService } from '../../server/regulatory/regulatory-corpus-upload-service';
import type { RegulatoryIngestionService } from '../../server/regulatory/regulatory-rag-service';
import type { RegulatoryMappingService } from '../../server/regulatory/regulatory-mapping-service';
import type { RegulatoryCorpusV2 } from '../../src/domain/regulatory-rag';
import { RegulatoryCorpusUploadService } from '../../server/compliance/regulatory-corpus-upload-service';
import type { RegulatoryIngestionService } from '../../server/compliance/regulatory-rag-service';
import type { RegulatoryMappingService } from '../../server/compliance/regulatory-mapping-service';
import type { RegulatoryCorpusV2 } from '../../src/compliance/regulatory-rag';
import { LocalAssessorRepository } from '../../src/persistence/local-assessor-repository';
const token = 'synthetic-operator-token-at-least-32-characters';

View File

@ -1,8 +1,8 @@
import { describe, expect, it, vi } from 'vitest';
import { RegulatoryFindingRetrievalService } from '../../server/regulatory/regulatory-finding-retrieval';
import type { RegulatoryRetrievalCandidate, RegulatoryRetrievalRequest } from '../../src/domain/regulatory-rag';
import { RegulatoryFindingRetrievalService } from '../../server/compliance/regulatory-finding-retrieval';
import type { RegulatoryRetrievalCandidate, RegulatoryRetrievalRequest } from '../../src/compliance/regulatory-rag';
import type { UnifiedResultProjection } from '../../src/domain/unified-result';
import { buildRegulatoryFindingQuery } from '../../src/profiles/public-search/regulatory-query';
import { buildRegulatoryFindingQuery } from '../../src/compliance/regulatory-query';
// Result-table / occurrence data and raw addresses that must never reach the query.
const resultTableAsset = 'DC01.customer.local';

View File

@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import type { RegulatoryMappingBatchRun } from '../../src/domain/regulatory-mapping';
import { LocalAssessorRepository } from '../../src/persistence/local-assessor-repository';
import type { RegulatoryMappingBatchRun } from '../../src/compliance/regulatory-mapping';
import { LocalComplianceStore } from '../../src/compliance/local-compliance-store';
const stamp = '2026-09-16T08:00:00.000Z';
@ -28,10 +28,8 @@ function batch(overrides: Partial<RegulatoryMappingBatchRun> = {}): RegulatoryMa
}
describe('local regulatory mapping batch persistence', () => {
it('preserves idempotency and active-scope uniqueness, exports batches and deletes them with the project', async () => {
const repository = new LocalAssessorRepository();
await repository.saveProject({ id: 'project-1', name: 'Synthetic', createdAt: stamp, updatedAt: stamp, attributes: {} });
await repository.saveAssessment({ id: 'assessment-1', projectId: 'project-1', name: 'Synthetic', createdAt: stamp, updatedAt: stamp });
it('preserves idempotency and active-scope uniqueness and exports batches per project', async () => {
const repository = new LocalComplianceStore();
const first = await repository.createRegulatoryMappingBatchRun(batch());
await expect(repository.createRegulatoryMappingBatchRun(batch({ id: 'batch-idempotent' }))).resolves.toEqual(first);
@ -44,7 +42,6 @@ describe('local regulatory mapping batch persistence', () => {
expect((await repository.listRegulatoryMappingBatchRuns('project-1', 'scope-1')).map(item => item.id)).toEqual(['batch-2', 'batch-1']);
expect(retry.id).toBe('batch-2');
await repository.deleteProject('project-1', { projectId: 'project-1', cascade: true });
await expect(repository.listRegulatoryMappingBatchRuns('project-1')).resolves.toEqual([]);
expect((await repository.exportProject('project-2')).regulatoryMappingBatchRuns).toEqual([]);
});
});

View File

@ -4,7 +4,7 @@ import { resolve } from 'node:path';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { describe, expect, it, vi } from 'vitest';
import { RegulatoryMappingBatchDialog } from '../../src/features/results-browser/RegulatoryMappingBatchDialog';
import { RegulatoryMappingBatchDialog } from '../../src/compliance/ui/RegulatoryMappingBatchDialog';
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@ -23,6 +23,7 @@ describe('Result DB regulatory mapping batch', () => {
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => root.render(<RegulatoryMappingBatchDialog filteredResultCount={75} onClose={() => {}} controller={{
available: true,
loading: false,
starting: false,
start: vi.fn(),

View File

@ -1,7 +1,7 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import { RegulatoryMappingPanel } from '../../src/features/finding-reader/RegulatoryMappingPanel';
import type { RegulatoryMappingResponse } from '../../src/domain/regulatory-mapping';
import { RegulatoryMappingPanel } from '../../src/compliance/ui/RegulatoryMappingPanel';
import type { RegulatoryMappingResponse } from '../../src/compliance/regulatory-mapping';
const response: RegulatoryMappingResponse = {
version: 1, projectId: 'project-1', resultProjectionId: 'scanner-finding:occurrence-1', generationEnabled: true,

View File

@ -4,8 +4,8 @@ import { act, type ReactNode } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, expect, it, vi } from 'vitest';
import { AssessorApiClient } from '../../src/api/assessor-api-client';
import type { RegulatoryMappingResponse } from '../../src/domain/regulatory-mapping';
import { useRegulatoryMapping } from '../../src/features/finding-reader/use-regulatory-mapping';
import type { RegulatoryMappingResponse } from '../../src/compliance/regulatory-mapping';
import { useRegulatoryMapping } from '../../src/compliance/ui/use-regulatory-mapping';
afterEach(() => {
vi.restoreAllMocks();

View File

@ -1,10 +1,13 @@
import { describe, expect, it, vi } from 'vitest';
import { RegulatoryMappingService } from '../../server/regulatory/regulatory-mapping-service';
import { RegulatoryFindingRetrievalService } from '../../server/regulatory/regulatory-finding-retrieval';
import type { RegulatoryMappingBatchRun, RegulatoryMappingDecision, RegulatoryMappingRun } from '../../src/domain/regulatory-mapping';
import type { RegulatoryChunk, RegulatoryRetrievalRequest } from '../../src/domain/regulatory-rag';
import { AUTO_ACCEPT_COMMENT, RegulatoryMappingService } from '../../server/compliance/regulatory-mapping-service';
import { RegulatoryFindingRetrievalService } from '../../server/compliance/regulatory-finding-retrieval';
import { acceptedControlIds, type RegulatoryMappingBatchRun, type RegulatoryMappingDecision, type RegulatoryMappingRun } from '../../src/compliance/regulatory-mapping';
import type { RegulatoryChunk, RegulatoryRetrievalRequest } from '../../src/compliance/regulatory-rag';
import { filterUnifiedResults, type UnifiedResultProjection } from '../../src/domain/unified-result';
import type { AssessorRepository } from '../../src/persistence/assessor-repository';
import type { ComplianceReadPort, ComplianceStore } from '../../src/compliance/compliance-store';
type EngineRepository = ComplianceReadPort & ComplianceStore;
import { removeResultDbScopeIdentifiers } from '../../src/domain/result-db-disclosure';
const stamp = '2026-09-15T10:00:00.000Z';
// Result-table / occurrence data that must never reach the model or the query.
@ -55,7 +58,11 @@ function mockRepository(findings: UnifiedResultProjection[]) {
const offset = query.offset ?? 0;
return { total: filtered.length, items: filtered.slice(offset, offset + (query.limit ?? filtered.length)) };
}),
getUnifiedResultById: vi.fn(async (id: string) => byProjection.get(id) ?? null),
// Mirrors the real Result DB read: scoped to the project, returned without real scope ids.
getUnifiedResultById: vi.fn(async (id: string, projectId?: string) => {
const item = byProjection.get(id);
return item && (projectId === undefined || item.projectId === projectId) ? removeResultDbScopeIdentifiers(item) : null;
}),
getRegulatoryMappingRun: vi.fn(async (id: string) => runs.get(id) ?? null),
claimRegulatoryMappingRun: vi.fn(async (run: RegulatoryMappingRun, force: boolean) => {
const existing = runs.get(run.id);
@ -96,11 +103,11 @@ function mockRepository(findings: UnifiedResultProjection[]) {
}),
listRegulatoryMappingDecisions: vi.fn(async (ruleKey: string) => decisions.filter(d => d.ruleKey === ruleKey)
.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id)))
} as unknown as AssessorRepository;
} as unknown as EngineRepository;
}
function service(repository: AssessorRepository, complete: (system: string, input: string) => Promise<unknown>) {
return new RegulatoryMappingService(repository, {
function service(repository: EngineRepository, complete: (system: string, input: string) => Promise<unknown>) {
return new RegulatoryMappingService(repository, repository, {
findingRetrieval: new RegulatoryFindingRetrievalService({ retrieve: vi.fn(async (_r: RegulatoryRetrievalRequest) => [{ score: 0.9, chunk: chunk('ISO/IEC 27002') }]) }),
index: { ensureCollection: vi.fn(), replaceDocuments: vi.fn(), searchDense: vi.fn(), list: vi.fn(async () => [chunk('ISO/IEC 27001')]) },
client: { model: 'work-model', complete: complete as never }, corpusId: 'iso-test', corpusVersion: 'v2', embeddingModel: 'bge-m3',
@ -136,10 +143,112 @@ describe('regulatory mapping service', () => {
expect(complete.mock.calls[0][1]).not.toContain('DC02.other.local');
expect(complete.mock.calls[0][1]).not.toContain('A.5.1');
// A decision made in project-1 is visible to project-2 (global decisions).
await svc.decide('project-1', { resultProjectionId: 'scanner-finding:occurrence-1', controlId: '5.1', decision: 'accepted' });
// The automatic acceptance in project-1 is visible to project-2 (global decisions), and so is a later manual decision.
expect(shared.decisions.map(d => ({ controlId: d.controlId, decision: d.decision }))).toEqual([{ controlId: '5.1', decision: 'accepted' }]);
await svc.decide('project-1', { resultProjectionId: 'scanner-finding:occurrence-1', controlId: '5.1', decision: 'rejected', expectedLatestDecisionId: shared.decisions[0].id });
const afterDecision = await svc.get('project-2', 'scanner-finding:occurrence-2');
expect(afterDecision.decisions.map(d => ({ controlId: d.controlId, decision: d.decision }))).toEqual([{ controlId: '5.1', decision: 'accepted' }]);
const rejected = afterDecision.decisions.find(d => d.decision === 'rejected');
expect(rejected).toMatchObject({ controlId: '5.1', previousDecisionId: shared.decisions[0].id });
expect(acceptedControlIds(afterDecision.decisions)).toEqual([]);
});
it('maps a finding although the Result DB row carries no real project id, but never across projects', async () => {
const repository = mockRepository([finding()]);
const complete = vi.fn(async (_system: string, _input: string) => ({ value: {
schemaVersion: 1, outcome: 'mapped', mappings: [{ controlId: '5.1', relationship: 'primary', confidence: 'high',
rationale: 'Synthetic rationale.', evidenceChunkIds: ['semantic-5.1', 'reference-5.1'] }]
} }));
const svc = service(repository, complete);
expect((await repository.getUnifiedResultById('scanner-finding:occurrence-1'))?.projectId).toBe('scoped-project');
await expect(svc.get('project-1', 'scanner-finding:occurrence-1')).resolves.toMatchObject({ generationEnabled: true });
await svc.start('project-1', { resultProjectionId: 'scanner-finding:occurrence-1' });
await svc.close();
const automatic = (await svc.get('project-1', 'scanner-finding:occurrence-1')).decisions[0];
await expect(svc.decide('project-1', { resultProjectionId: 'scanner-finding:occurrence-1', controlId: '5.1', decision: 'rejected', expectedLatestDecisionId: automatic.id }))
.resolves.toMatchObject({ state: 'succeeded' });
await expect(svc.get('project-2', 'scanner-finding:occurrence-1')).rejects.toThrow('does not exist in this project');
await expect(svc.start('project-2', { resultProjectionId: 'scanner-finding:occurrence-1' })).rejects.toThrow('does not exist in this project');
await expect(svc.decide('project-2', { resultProjectionId: 'scanner-finding:occurrence-1', controlId: '5.1', decision: 'rejected' }))
.rejects.toThrow('does not exist in this project');
});
it('counts accepted controls once per finding for the timeslot deviations of a client', async () => {
const gpo = (id: string) => finding({ resultProjectionId: `policy-evaluation-comparison:${id}`, sourceResultId: `comparison-${id}`,
sourceKind: 'policy-evaluation', sourceTool: 'GPOs', sourceRuleId: 'registry:machine:software\policies\synthetic:mode',
policyScope: 'computer', title: 'Synthetic policy mode' });
const findings = [
finding(),
finding({ resultProjectionId: 'scanner-finding:occurrence-2', sourceResultId: 'occurrence-2' }),
finding({ resultProjectionId: 'scanner-finding:not-deviation', sourceResultId: 'not-deviation', isDeviation: false }),
finding({ resultProjectionId: 'scanner-finding:rejected', sourceResultId: 'rejected', sourceRuleId: 'A-Rejected', title: 'SMB signing is not enforced' }),
// Two baseline packages of one GPO setting are one Work record and count once.
gpo('one'), gpo('two')
];
const repository = mockRepository(findings);
const svc = service(repository, vi.fn(async () => ({ value: {
schemaVersion: 1, outcome: 'mapped', mappings: [{ controlId: '5.1', relationship: 'primary', confidence: 'high',
rationale: 'Synthetic rationale.', evidenceChunkIds: ['semantic-5.1', 'reference-5.1'] }]
} })));
for (const resultProjectionId of ['scanner-finding:occurrence-1', 'scanner-finding:rejected', 'policy-evaluation-comparison:one']) {
await svc.start('project-1', { resultProjectionId });
await svc.close();
}
const accepted = (await svc.get('project-1', 'scanner-finding:rejected')).decisions[0];
await svc.decide('project-1', { resultProjectionId: 'scanner-finding:rejected', controlId: '5.1', decision: 'rejected', expectedLatestDecisionId: accepted.id });
const overview = await svc.controlOverview('project-1', { assessmentIds: ['assessment-1'], scanRunIds: ['run-1'] });
expect(overview).toMatchObject({ version: 1, projectId: 'project-1', findingCount: 3,
controls: [{ controlId: '5.1', annexAControlId: 'A.5.1', title: 'Synthetic control', theme: 'Organizational' }] });
expect(overview.controls[0].findings.map(item => item.resultProjectionId))
.toEqual(['scanner-finding:occurrence-1', 'scanner-finding:occurrence-2', 'policy-evaluation-comparison:one']);
// Only the timeslot deviations are read, and only through the read-only port.
expect(vi.mocked(repository.queryUnifiedResults).mock.calls.at(-1)![0]).toMatchObject({ audience: 'result-db', deviation: true, projectId: 'project-1' });
await expect(svc.controlOverview('project-1', { assessmentIds: [], scanRunIds: [] })).rejects.toThrow('timeslot scope is required');
await expect(svc.controlOverview('project-1', { assessmentIds: ['foreign-assessment'], scanRunIds: [] })).rejects.toThrow('outside this project');
});
it('accepts the first two proposals automatically, keeps existing decisions and accepts nothing without a proposal', async () => {
const semantic = (controlId: string): RegulatoryChunk => ({ ...chunk('ISO/IEC 27002'), controlId, annexAControlId: `A.${controlId}`,
documentId: `27002-${controlId}`, chunkId: `semantic-${controlId}` });
const proposal = (controlId: string) => ({ controlId, relationship: 'supporting', confidence: 'medium', rationale: 'Synthetic rationale.',
evidenceChunkIds: [`semantic-${controlId}`] });
const build = (repository: EngineRepository, value: unknown) => new RegulatoryMappingService(repository, repository, {
findingRetrieval: new RegulatoryFindingRetrievalService({ retrieve: vi.fn(async (_r: RegulatoryRetrievalRequest) =>
['8.20', '5.15', '5.1'].map((controlId, index) => ({ score: 0.9 - index / 10, chunk: semantic(controlId) }))) }),
index: { ensureCollection: vi.fn(), replaceDocuments: vi.fn(), searchDense: vi.fn(), list: vi.fn(async () => [chunk('ISO/IEC 27001')]) },
client: { model: 'work-model', complete: vi.fn(async () => ({ value })) as never }, corpusId: 'iso-test', corpusVersion: 'v2',
embeddingModel: 'bge-m3', now: () => new Date(stamp)
});
const accepted = async (svc: RegulatoryMappingService) => acceptedControlIds((await svc.get('project-1', 'scanner-finding:occurrence-1')).decisions).sort();
const mapped = (...controls: string[]) => ({ schemaVersion: 1, outcome: 'mapped', mappings: controls.map(proposal) });
// Three proposals: the first two in the model's order are accepted, the third stays undecided.
const three = build(mockRepository([finding()]), mapped('5.15', '8.20', '5.1'));
await three.start('project-1', { resultProjectionId: 'scanner-finding:occurrence-1' });
await three.close();
expect(await accepted(three)).toEqual(['5.15', '8.20']);
expect((await three.get('project-1', 'scanner-finding:occurrence-1')).decisions.every(item => item.comment === AUTO_ACCEPT_COMMENT)).toBe(true);
// A single proposal is accepted alone.
const one = build(mockRepository([finding()]), mapped('8.20'));
await one.start('project-1', { resultProjectionId: 'scanner-finding:occurrence-1' });
await one.close();
expect(await accepted(one)).toEqual(['8.20']);
// Regenerating never overrides a manual reject; a still undecided first proposal is accepted.
const automatic = (await three.get('project-1', 'scanner-finding:occurrence-1')).decisions.find(item => item.controlId === '5.15')!;
await three.decide('project-1', { resultProjectionId: 'scanner-finding:occurrence-1', controlId: '5.15', decision: 'rejected', expectedLatestDecisionId: automatic.id });
await three.start('project-1', { resultProjectionId: 'scanner-finding:occurrence-1' });
await three.close();
expect(await accepted(three)).toEqual(['8.20']);
// Without a proposal nothing is accepted.
const none = build(mockRepository([finding()]), { schemaVersion: 1, outcome: 'no_relevant_control', mappings: [], reason: 'Synthetic refusal.' });
await none.start('project-1', { resultProjectionId: 'scanner-finding:occurrence-1' });
await none.close();
expect((await none.get('project-1', 'scanner-finding:occurrence-1')).decisions).toEqual([]);
});
it('keeps a saved mapping readable when the retrieval index is unavailable', async () => {
@ -152,7 +261,7 @@ describe('regulatory mapping service', () => {
await online.start('project-1', { resultProjectionId: 'scanner-finding:occurrence-1' });
await online.close();
const offline = new RegulatoryMappingService(repository, {
const offline = new RegulatoryMappingService(repository, repository, {
findingRetrieval: {} as never,
index: { list: vi.fn(async () => { throw new Error('Index unavailable'); }) } as never,
client: { model: 'work-model', complete } as never,

View File

@ -4,8 +4,10 @@ import { describe, expect, it } from 'vitest';
import { createLiteLlmClientFromEnvironment } from '../../server/ai/litellm-client';
import { runDatabaseMigrations } from '../../server/postgres/migration-runner';
import { PostgresAssessorRepository } from '../../server/postgres/postgres-assessor-repository';
import { createRegulatoryRagRuntime } from '../../server/regulatory/regulatory-rag-runtime';
import { RegulatoryMappingService } from '../../server/regulatory/regulatory-mapping-service';
import { createRegulatoryRagRuntime } from '../../server/compliance/regulatory-rag-runtime';
import { RegulatoryMappingService } from '../../server/compliance/regulatory-mapping-service';
import { PostgresComplianceStore } from '../../server/compliance/postgres-compliance-store';
import { complianceReadPortFrom } from '../../src/compliance/compliance-store';
import type { Assessment, AssessmentProject, ScanRun } from '../../src/domain/canonical-model';
import { RepositoryConflictError } from '../../src/persistence/repository-errors';
@ -26,7 +28,8 @@ describeIntegration('regulatory mapping end-to-end integration', () => {
const rag = createRegulatoryRagRuntime();
const client = createLiteLlmClientFromEnvironment();
if (!client) throw new Error('Approved LiteLLM configuration is required.');
const service = new RegulatoryMappingService(repository, {
const store = new PostgresComplianceStore(pool);
const service = new RegulatoryMappingService(complianceReadPortFrom(repository), store, {
findingRetrieval: rag.findingRetrieval, index: rag.index, embeddingModel: rag.embeddingModel, client,
corpusId: process.env.ASSESSOR_RAG_ACTIVE_CORPUS_ID,
corpusVersion: process.env.ASSESSOR_RAG_ACTIVE_CORPUS_VERSION
@ -74,15 +77,15 @@ describeIntegration('regulatory mapping end-to-end integration', () => {
});
expect(reviewed.decisions[0]).toMatchObject({ controlId: candidate.controlId, decision: 'accepted' });
// Omitting expectedLatestDecisionId conflicts with the existing global decision for this rule+control.
await expect(repository.createRegulatoryMappingDecision({
await expect(store.createRegulatoryMappingDecision({
version: 1, id: `synthetic-conflict-${suffix}`, ruleKey, sourceTool: 'purple-knight', sourceRuleId: 'SYNTHETIC-SMB',
mappingId: result.run!.id, controlId: candidate.controlId, decision: 'rejected', createdAt: new Date().toISOString()
})).rejects.toBeInstanceOf(RepositoryConflictError);
await repository.deleteProject(project.id, { projectId: project.id, cascade: true });
deleted = true;
// Regulatory mappings and decisions are global: they survive project deletion.
await expect(repository.getRegulatoryMappingRun(result.run!.id)).resolves.not.toBeNull();
expect((await repository.listRegulatoryMappingDecisions(ruleKey)).length).toBeGreaterThan(0);
await expect(store.getRegulatoryMappingRun(result.run!.id)).resolves.not.toBeNull();
expect((await store.listRegulatoryMappingDecisions(ruleKey)).length).toBeGreaterThan(0);
} finally {
await service.close();
if (!deleted) await repository.deleteProject(project.id, { projectId: project.id, cascade: true }).catch(() => false);

View File

@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { groundRegulatoryMappingResult, regulatoryMappingResultValidationErrors } from '../../src/domain/regulatory-mapping';
import { groundRegulatoryMappingResult, regulatoryMappingResultValidationErrors } from '../../src/compliance/regulatory-mapping';
const grounded = new Map([['5.1', new Set(['semantic-5.1', 'reference-5.1'])]]);

View File

@ -1,12 +1,12 @@
import { describe, expect, it, vi } from 'vitest';
import type { RegulatoryControlDocument, RegulatoryRetrievalCandidate } from '../../src/domain/regulatory-rag';
import type { TextEmbeddingClient } from '../../server/regulatory/embedding-client';
import type { IndexedRegulatoryChunk, RegulatoryChunkIndex } from '../../server/regulatory/qdrant-regulatory-index';
import type { RegulatoryControlDocument, RegulatoryRetrievalCandidate } from '../../src/compliance/regulatory-rag';
import type { TextEmbeddingClient } from '../../server/compliance/embedding-client';
import type { IndexedRegulatoryChunk, RegulatoryChunkIndex } from '../../server/compliance/qdrant-regulatory-index';
import {
DenseRegulatoryCandidateRetriever,
RegulatoryIngestionService,
RegulatoryRetrievalPipeline
} from '../../server/regulatory/regulatory-rag-service';
} from '../../server/compliance/regulatory-rag-service';
const document: RegulatoryControlDocument = {
schemaVersion: 1, corpusId: 'nis2', corpusVersion: '2024-1', documentId: 'nis2-21-2-a-de',

View File

@ -2,8 +2,8 @@ import { describe, expect, it } from 'vitest';
import {
evaluateRegulatoryRetriever,
regulatoryRetrievalEvaluationCases
} from '../../server/regulatory/regulatory-retrieval-evaluation';
import type { RegulatoryRetrievalCandidate } from '../../src/domain/regulatory-rag';
} from '../../server/compliance/regulatory-retrieval-evaluation';
import type { RegulatoryRetrievalCandidate } from '../../src/compliance/regulatory-rag';
function candidate(controlId: string, language: string, chunkIndex: number): RegulatoryRetrievalCandidate {
return {

View File

@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { validateRegulatoryControlDocument } from '../../server/regulatory/regulatory-chunker';
import { regulatoryRetrievalEvaluationCases } from '../../server/regulatory/regulatory-retrieval-evaluation';
import { validateRegulatoryControlDocument } from '../../server/compliance/regulatory-chunker';
import { regulatoryRetrievalEvaluationCases } from '../../server/compliance/regulatory-retrieval-evaluation';
import corpus from '../fixtures/regulatory-corpus.synthetic.json';
import evaluation from '../fixtures/regulatory-evaluation.synthetic.json';

View File

@ -25,11 +25,11 @@ it.each(['dark', 'light'])('opens engine selection, locks Core and restores keyb
await act(async () => trigger.click());
const dialog = document.querySelector('[role="dialog"]')!;
const checks = [...dialog.querySelectorAll<HTMLInputElement>('input')];
expect(checks.map(input => input.checked)).toEqual([true, true, true, true]);
expect(checks.map(input => input.disabled)).toEqual([true, false, false, false]);
await act(async () => { checks[0].click(); checks[1].click(); });
expect(readEnginePreferences()).toEqual({ core: true, context: false, report: true, remediation: true });
checks[3].focus();
expect(checks.map(input => input.checked)).toEqual([true, true, true, true, true]);
expect(checks.map(input => input.disabled)).toEqual([true, false, false, false, false]);
await act(async () => { checks[0].click(); checks[1].click(); checks[4].click(); });
expect(readEnginePreferences()).toEqual({ core: true, context: false, report: true, remediation: true, compliance: false });
checks[4].focus();
await act(async () => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true })));
expect(document.activeElement).toBe(dialog.querySelector('button'));
await act(async () => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));
@ -43,22 +43,22 @@ it.each(['dark', 'light'])('opens engine selection, locks Core and restores keyb
it('persists independent choices, ignores the obsolete Context preference and cannot disable Core', () => {
localStorage.setItem('ASSESSOR.contextLayer', 'off');
expect(readEnginePreferences()).toEqual({ core: true, context: true, report: true, remediation: true });
expect(readEnginePreferences()).toEqual({ core: true, context: true, report: true, remediation: true, compliance: true });
setEngineEnabled('report', false); setEngineEnabled('core', false);
resetEnginePreferencesForTests();
expect(readEnginePreferences()).toEqual({ core: true, context: true, report: false, remediation: true });
expect(readEnginePreferences()).toEqual({ core: true, context: true, report: false, remediation: true, compliance: true });
localStorage.setItem(ENGINE_PREFERENCES_KEY, '{"core":false,"context":false}');
resetEnginePreferencesForTests();
expect(readEnginePreferences()).toEqual({ core: true, context: false, report: true, remediation: true });
expect(readEnginePreferences()).toEqual({ core: true, context: false, report: true, remediation: true, compliance: true });
});
it('defaults safely when storage is malformed or blocked and still allows session toggles', () => {
localStorage.setItem(ENGINE_PREFERENCES_KEY, 'bad json');
expect(readEnginePreferences()).toEqual({ core: true, context: true, report: true, remediation: true });
expect(readEnginePreferences()).toEqual({ core: true, context: true, report: true, remediation: true, compliance: true });
resetEnginePreferencesForTests();
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('blocked'); });
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('blocked'); });
expect(readEnginePreferences()).toEqual({ core: true, context: true, report: true, remediation: true });
expect(readEnginePreferences()).toEqual({ core: true, context: true, report: true, remediation: true, compliance: true });
expect(() => setEngineEnabled('context', false)).not.toThrow();
expect(readEnginePreferences().context).toBe(false);
});

View File

@ -27,7 +27,8 @@ describe('DB Structure data flow', () => {
try {
await act(async () => root.render(createElement(EngineDataFlow)));
const engines = [...container.querySelectorAll<HTMLButtonElement>('.db-engine-flow__node.is-engine')];
expect(engines.map(engine => engine.dataset.node)).toEqual(['core', 'context', 'report']);
expect(engines.map(engine => engine.dataset.node)).toEqual(['core', 'context', 'report', 'compliance']);
const connectionCount: Record<string, number> = { core: 3, context: 3, report: 3, compliance: 4 };
// Remove the initial Core selection; identity frames must remain independently.
await act(async () => engines[0].click());
const highlighted = () => container.querySelectorAll('.db-engine-flow__edges > path.is-related');
@ -40,7 +41,7 @@ describe('DB Structure data flow', () => {
await act(async () => engine.click());
expect(engine.getAttribute('aria-pressed')).toBe('true');
const selectedPaths = [...highlighted()].map(path => path.getAttribute('d'));
expect(selectedPaths).toHaveLength(3);
expect(selectedPaths).toHaveLength(connectionCount[engine.dataset.node!]);
await act(async () => engine.click());
expect(highlighted()).toHaveLength(0);
expect(engine.classList.contains('is-engine')).toBe(true);
@ -59,9 +60,9 @@ describe('DB Structure data flow', () => {
const container = document.createElement('div');
const root = createRoot(container);
await act(async () => root.render(createElement(EngineDataFlow)));
expect(container.querySelectorAll('.db-engine-flow__node')).toHaveLength(9);
expect(container.querySelectorAll('.db-engine-flow__edges > path')).toHaveLength(9);
expect(container.querySelectorAll('.db-engine-flow__edges > path[marker-start]')).toHaveLength(1);
expect(container.querySelectorAll('.db-engine-flow__node')).toHaveLength(13);
expect(container.querySelectorAll('.db-engine-flow__edges > path')).toHaveLength(13);
expect(container.querySelectorAll('.db-engine-flow__edges > path[marker-start]')).toHaveLength(3);
expect(container.querySelectorAll('.db-engine-flow__edges > path.is-related')).toHaveLength(3);
expect(container.querySelector('.db-engine-flow__dictionary')?.hasAttribute('open')).toBe(false);
const context = [...container.querySelectorAll<HTMLButtonElement>('.db-engine-flow__node')]
@ -75,11 +76,21 @@ describe('DB Structure data flow', () => {
await act(async () => context.click());
expect(container.querySelector('.db-engine-flow__inspector')).toBeNull();
expect(container.querySelectorAll('.db-engine-flow__edges > path.is-related')).toHaveLength(0);
expect(container.querySelectorAll('.db-engine-flow__node')).toHaveLength(9);
// The Compliance Engine reads through the port, owns its tables and reaches the UI only through extension points.
const compliance = [...container.querySelectorAll<HTMLButtonElement>('.db-engine-flow__node')]
.find(button => button.textContent?.startsWith('Compliance Engine'))!;
await act(async () => compliance.click());
expect(container.querySelector('.db-engine-flow__inspector h4')?.textContent).toBe('Compliance Engine');
expect([...container.querySelectorAll('.db-engine-flow__inspector li strong')].map(item => item.textContent)).toEqual([
'Core read-only port → Compliance Engine', 'Compliance Engine ↔ Compliance tables',
'Compliance Engine ↔ Retrieval & model', 'Compliance Engine → ISO mapping in the UI']);
await act(async () => compliance.click());
expect(container.querySelectorAll('.db-engine-flow__node')).toHaveLength(13);
const dictionary = container.querySelector<HTMLDetailsElement>('.db-engine-flow__dictionary')!;
await act(async () => dictionary.querySelector('summary')!.click());
expect(dictionary.open).toBe(true);
expect(dictionary.querySelectorAll('tbody tr')).toHaveLength(9);
expect(dictionary.querySelector('summary')?.textContent).toBe('All relationships (13)');
expect(dictionary.querySelectorAll('tbody tr')).toHaveLength(13);
act(() => root.unmount());
});
@ -187,9 +198,9 @@ describe('DB Structure data flow', () => {
expect(container.querySelector('.db-flow__header p')).toBeNull();
expect(container.querySelector('.db-flow .db-flow__header h3')?.textContent).toBe('Data flow');
expect([...container.querySelectorAll('.db-engine-flow__node.is-engine strong')].map(item => item.textContent))
.toEqual(['Core Engine', 'Context Engine', 'Report Engine']);
.toEqual(['Core Engine', 'Context Engine', 'Report Engine', 'Compliance Engine']);
const relations = container.querySelector('table[aria-label="Directed engine relationships"]');
expect(relations?.querySelectorAll('tbody tr')).toHaveLength(9);
expect(relations?.querySelectorAll('tbody tr')).toHaveLength(13);
expect(relations?.textContent).toContain('Core read-only port');
expect(relations?.textContent).toContain('Planned');
expect(relations?.textContent).toContain('not yet connected in report generation');
@ -197,8 +208,8 @@ describe('DB Structure data flow', () => {
container.querySelector<HTMLButtonElement>('.db-structure-intro-actions button')!.click();
await new Promise(resolve => setTimeout(resolve, 0));
});
expect(container.querySelectorAll('.db-engine-flow__node.is-engine')).toHaveLength(3);
expect(container.querySelectorAll('.db-engine-flow tbody tr')).toHaveLength(9);
expect(container.querySelectorAll('.db-engine-flow__node.is-engine')).toHaveLength(4);
expect(container.querySelectorAll('.db-engine-flow tbody tr')).toHaveLength(13);
expect(container.querySelector('.db-structure-intro-actions button')?.textContent).toBe('Refresh schema');
expect(container.querySelector('.db-flow__lane.is-reference')?.textContent).toContain('Input to GPO step');
const chips = [...container.querySelectorAll<HTMLButtonElement>('.db-flow__table')];

View File

@ -1,5 +1,5 @@
// @vitest-environment jsdom
import { regulatoryMappingResultId } from '../../src/features/finding-reader/use-regulatory-mapping';
import { regulatoryMappingResultId } from '../../src/compliance/ui/use-regulatory-mapping';
import { renderToStaticMarkup } from 'react-dom/server';
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';

View File

@ -184,6 +184,10 @@ describe('Unified result read model', () => {
});
await expect(repository.getUnifiedResultById('scanner-finding:occurrence-pingcastle-ntlm'))
.resolves.toMatchObject({ title: finding.title, sourceRuleId: 'S-oldNtlm' });
// A project-scoped read finds the row although the returned row carries no real scope ids.
await expect(repository.getUnifiedResultById('scanner-finding:occurrence-pingcastle-ntlm', project.id))
.resolves.toMatchObject({ sourceRuleId: 'S-oldNtlm', projectId: 'scoped-project' });
await expect(repository.getUnifiedResultById('scanner-finding:occurrence-pingcastle-ntlm', 'other-project')).resolves.toBeNull();
});
it('keeps Purple Knight AD and Entra ID separately filterable in Result DB', async () => {

View File

@ -127,6 +127,8 @@ describePostgres('PostgresAssessorRepository integration', () => {
const disclosed = await repository.getUnifiedResultById('scanner-finding:pg-occurrence-1');
expect(disclosed).not.toHaveProperty('reviewStatus');
expect(disclosed).not.toHaveProperty('reviewPriority');
await expect(repository.getUnifiedResultById('scanner-finding:pg-occurrence-1', project.id)).resolves.toMatchObject({ sourceResultId: 'pg-occurrence-1' });
await expect(repository.getUnifiedResultById('scanner-finding:pg-occurrence-1', 'other-project')).resolves.toBeNull();
const internal = await repository.queryUnifiedResults({ audience: 'internal-analysis', projectId: project.id });
expect(internal.items.find(item => item.sourceResultId === 'pg-occurrence-1')).toMatchObject({
reviewStatus: 'open',

View File

@ -13,10 +13,10 @@ export default defineConfig({
server: 'server/index.ts',
'import-worker': 'server/import-worker.ts',
'gpo-inventory-worker': 'server/gpo/gpo-inventory-worker.ts',
'regulatory-ingest': 'server/regulatory/regulatory-ingest.ts',
'regulatory-prepare-iso': 'server/regulatory/regulatory-prepare-iso.ts',
'iso-pdf-worker': 'server/regulatory/iso-pdf-worker.ts',
'regulatory-evaluate': 'server/regulatory/regulatory-evaluate.ts'
'regulatory-ingest': 'server/compliance/regulatory-ingest.ts',
'regulatory-prepare-iso': 'server/compliance/regulatory-prepare-iso.ts',
'iso-pdf-worker': 'server/compliance/iso-pdf-worker.ts',
'regulatory-evaluate': 'server/compliance/regulatory-evaluate.ts'
},
output: {
entryFileNames: '[name].mjs'