Compare commits

...

53 Commits

Author SHA1 Message Date
Benjamin Admin c5ecfa8f6c feat(bridge): export 7 accepted CRA->OWASP controls for obligation_id proposal
CI / detect-changes (push) Successful in 5s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 9s
CI / validate-canonical-controls (push) Successful in 5s
CI / loc-budget (push) Successful in 23s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Has been skipped
CI / iace-gt-coverage (push) Has been skipped
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
obligations/controls_for_obligation_mapping.json — the Compliance Execution
Graph's accepted controls (V6 auth / V11 crypto / V16 logging) handed to the
Obligation Registry to propose the SEMANTIC control->obligation_id, replacing
the coarse citation_unit interim join (Befund 1). Registry fills
proposed_obligation_id; we then adopt it into control_mapping.obligation_id.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 11:36:57 +02:00
Benjamin Admin 9e0a9ccef4 Add obligation_id join-key contract (cross-session bridge)
CI / detect-changes (push) Successful in 5s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 8s
CI / validate-canonical-controls (push) Successful in 7s
CI / loc-budget (push) Successful in 19s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Has been skipped
CI / iace-gt-coverage (push) Has been skipped
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
Macht meine Seite des Cross-Session-Vertrags konkret: obligation_id ist der stabile Join-Key
zwischen Legal Knowledge Graph (citation_spans -> obligation_id) und Compliance Execution Graph
(control_mapping.source_norm -> obligation_id). Export aller 47 obligation_ids (CRA: 11 sbom +
7 vuln + 29 auth) mit citation_units als Interim-Brücke. Disziplin: obligation_id nie neu
vergeben (re-link, Pendant zu span_id/control_uuid).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 10:29:29 +02:00
Benjamin Admin 7e1c3668bf Merge remote-tracking branch 'origin/main' into feat/obligation-aggregation
CI / detect-changes (push) Successful in 8s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 5s
CI / validate-canonical-controls (push) Successful in 4s
CI / loc-budget (push) Successful in 14s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Has been skipped
CI / iace-gt-coverage (push) Has been skipped
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
2026-06-25 10:15:25 +02:00
Benjamin Admin ab3cb86b1c feat(ucca): Evidence-Requirement model (step A)
CI / detect-changes (push) Successful in 5s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 7s
CI / validate-canonical-controls (push) Successful in 5s
CI / loc-budget (push) Successful in 20s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Successful in 1m5s
CI / iace-gt-coverage (push) Successful in 17s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
The last edge of the compliance graph: what concrete, fresh evidence proves a
framework control is met (config_export/test_report/sbom/audit_log/pentest/...
from github/ci/scanner/manual_upload, with a freshness requirement).

Seeded for all 7 accepted CRA->OWASP controls (Auth/Crypto/Logging). A graph
test enforces connectivity: every accepted control must carry >=1 required
evidence — no dangling node in Obligation -> Control -> Evidence.

This is what will let the Advisor state "the CRA requirement is fulfilled" from
present evidence, not from the mere existence of a document.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 10:06:09 +02:00
Benjamin Admin 0db0e9a129 feat(ucca): curate CRA Annex I -> OWASP mappings (review B)
7 accepted, 13 rejected (reviewed_by=benjamin, 2026-06-25). The accepted set is
the first audited ground truth of the compliance graph:
  (2c) Zugriff   -> V6.3.1, V6.1.1   (Auth)
  (2d) Crypto    -> V11.2.1, V11.7.1 (corrected from the retriever's wrong V14)
  (2k) Logging   -> V16.3.3, V16.3.4, V16.1.1

Rejected stay as audit trail. (2e) integrity, (2l) updates, (2i) attack surface
rejected with reason "OWASP ASVS not the right target standard, map via NIST/BSI"
— architectural proof for the multi-framework framework_* layer.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 10:01:06 +02:00
Benjamin Admin 53ea388ea0 refactor(ucca): control-mapping model per review feedback
- DROP confidence from the persisted mapping: a curated mapping is a
  professional statement, not an AI guess (retriever score -> rationale only).
- ADD mapping_status (candidate|accepted|rejected|superseded) — the review state.
- ADD audit trail (reviewed_by/review_date/review_reason); accepted/rejected
  fail-closed without it.
- EXTEND mapping_type: + implements, + contradicts.
- Advisor truth = mapping_status=accepted (acceptedOnly filter).
- migrate the 18 CRA->OWASP rows to mapping_status=candidate.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 09:50:37 +02:00
Benjamin Admin e5cce9caff Extend advisor proof with procedure→evidence chain
Vollständige Begründungskette aus der Registry: Rechtsgrundlage → Obligation → Procedure
→ Controls → Evidence → Antwort. Join cra.json × cra_procedures.json, deterministisch, kein LLM.

SBOM-Beweis: 7 Pflichten je mit CRA-Rechtsgrundlage + Procedure (wie umgesetzt) + Controls
(Prüfung) + aggregierte Required Evidence; 4 Best-Practice (Guidance OWASP/NIST/ENISA);
Beziehung sbom_*→supports→vuln_identification; citation 7/7 pending_span_anchor.

Der Unterschied zu RAG sichtbar: RAG beantwortet — BreakPilot begründet UND operationalisiert.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 09:44:27 +02:00
Benjamin Admin 2f3c98fbe0 feat(ucca): first CRA Annex I -> OWASP retriever candidates (step 3)
18 retriever_candidate mappings generated via the sdk-dev control-intent
retriever. All marked retriever_candidate (NOT curated truth) — the review
step turns the good ones into human_curated.

Empirical validation of the A-decision: the retriever proposes, but produces
wrong candidates (e.g. encryption -> V14 Config instead of V11 Crypto;
V14.2.4 over-appears) that only human review catches. Review notes inline.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 09:36:53 +02:00
Benjamin Admin d987e4fde6 feat(ucca): persisted Control-Mapping data model (Obligation -> framework control)
Versioned JSONL store + Go model for Regulation->Control mappings, per the
A-decision: the retriever only PROPOSES candidates; the curated mapping is the
audited truth the Advisor uses at runtime, never re-invented per query.

- ControlMapping struct (source_norm/source_role/target_framework/target_control/
  mapping_type/confidence/provenance/rationale/version)
- enum validation (rule layer), fail-closed loader, forward+reverse index,
  curated-only filter (IsCurated)
- seed: 2 retriever_candidate rows CRA Annex I -> OWASP ASVS (not yet curated)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 09:32:15 +02:00
Benjamin Admin 67dba5f641 Add CRA procedure model (SBOM + Vuln)
Schließt die Lücke Obligation→Procedure→Control→Evidence (Schritt 3, Compliance-OS-Ebene).
Procedure = Umsetzungs-/Nachweisebene EINER Obligation, KEINE neue Pflicht (LEGAL_MINIMUM
bleibt an der Obligation; Procedure beschreibt Umsetzung; Evidence belegt sie).

- 11 Procedures (5 SBOM + 6 Vuln), 2 Worked Examples; source_role=procedural_requirement
  (Konvergenz mit der Legal-Knowledge-Engine der anderen Session)
- fulfills_obligations[] referenziert die cra.json-Obligations (alle gültig, volle Abdeckung)
- steps/controls/evidence je Procedure; KEINE tier/legal_basis-Felder (kein Pflicht-Duplikat)
- citation_spans: [] / pending_span_anchor (Join folgt mit dem zitierfähigen Re-Ingest)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 09:28:40 +02:00
Benjamin Admin a3053c3c86 docs(architecture): RAG retrieval engine architecture set (01-09)
CI / detect-changes (push) Successful in 14s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 9s
CI / validate-canonical-controls (push) Successful in 19s
CI / loc-budget (push) Successful in 23s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Has been skipped
CI / iace-gt-coverage (push) Has been skipped
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
9 docs + index in docs-src/architecture/ documenting the deterministic
retrieval engine: retrieval pipeline, authority rerank, source_class,
source_role, control-intent + diversity, assessment, confidence,
explainability + supersede, framework_* layer. Each doc carries the exact
constants, the rationale behind them, code refs, and the failure class
it addresses. Audit/onboarding reference.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 09:25:22 +02:00
Benjamin Admin db2fd9d8e9 Add obligation advisor proof (P3)
Demonstriert den Produktnutzen der Registry: obligation-basierte Antwort statt RAG-Text.
Frage → Pflicht (LEGAL_MINIMUM + Rechtsgrundlage + Applicability) ⊥ Best Practice
(guidance_basis) ⊥ Nachweise (evidence_facets + member controls) + Beziehungen, deterministisch
aus obligations/cra.json (kein LLM, zitierfähig).

Beleg (SBOM, Maschinenbauer): JA — 7 CRA-Mindestpflichten + 4 Best-Practice (OWASP/NIST/ENISA);
sbom_* supports vuln_identification_inventory.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 09:06:34 +02:00
Benjamin Admin d21e1247c9 Merge remote-tracking branch 'origin/main' into feat/obligation-aggregation
CI / detect-changes (push) Successful in 5s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 4s
CI / validate-canonical-controls (push) Successful in 3s
CI / loc-budget (push) Successful in 17s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Has been skipped
CI / iace-gt-coverage (push) Has been skipped
CI / test-python-backend (push) Successful in 25s
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
2026-06-25 07:49:16 +02:00
Benjamin Admin e1b270c36e Add obligation discovery pipeline tooling
Sichert die validierte Obligation Discovery Pipeline aus /tmp als dauerhaftes,
committetes Tooling (scripts/obligation_discovery/) — der eigentliche Vermögenswert.

Stufen: precluster (Embedding-Cache + Mikro-Cluster) → meta_cluster (Review Units,
Skalierungs-Fix) → synthesize_obligations (Opus, Key aus ENV, Streaming, harte Tier-Regel,
Provenance) → validate_registry → merge_review_diff. Reine Helfer in _core.py, 16 Unit-Tests.

Doku docs-src/development/obligation_discovery_pipeline_v1.md mit Meilensteinen
(SBOM/Vuln reproduziert, Auth 4408→170 Review Units→54→kuriert 29) und der Architekturregel:
Runtime deterministisch, Discovery LLM-gestützt.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 07:41:45 +02:00
Benjamin Admin 48e39423e6 Add curated CRA authentication obligations (scaling test)
Erster großer Skalierungstest der Registry-Pipeline mit Zwei-Stufen-Clustering:
4408 Controls → 2134 Mikro → 170 Review Units → Opus-Synthese 54 → Kuration 29.

- Zwei-Stufen-Clustering (Mikro→Meta/Review-Unit) ist der Skalierungs-Fix für große Domänen
- harte Tier-Regel generalisiert: nur 6 LEGAL_MINIMUM (CRA fordert nur High-Level-Auth),
  23 BEST_PRACTICE; MFA/Passwort/Session/Krypto = guidance_basis, kein CRA-Primärrecht
- Kuration (key-frei, regelbasiert): Krypto-Mikro→guidance · Prüf/Nachweis→evidence-Facette ·
  Mechanismus-Familien behalten · eID/PSD2→out_of_scope; 6 LM unangetastet
- Provenance pro Obligation (source_meta_cluster/confidence/model/version)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 07:30:55 +02:00
Benjamin Admin 31222885b3 feat(ai-sdk): control-intent result diversity + standard-name classifier override
CI / detect-changes (push) Successful in 7s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 5s
CI / validate-canonical-controls (push) Successful in 8s
CI / loc-budget (push) Successful in 19s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Successful in 58s
CI / iace-gt-coverage (push) Successful in 17s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
On an implementation question impl_guidance (ENISA) keeps its earned semantic
Top-1, but the top-K now surfaces the best operational_requirement and
control_standard from the pool (ensureControlDiversity) — so different source
roles are visible instead of one role flooding the list, without forcing the
binding sources to Top-1.

A recognised standard NAME (NIST/OWASP/ISO 27001/CIS/CSA CCM/Grundschutz) now
overrides a mis-applied supervisory_guidance source_class in classifyAuthority,
so those standards classify and rank as technical_standard (control_standard
role). The corpus tags many standards as guidance (weight 70); the name wins.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 01:54:36 +02:00
Benjamin Admin 188bb787d2 Add proposed CRA obligation relationships
11 human-reasoned Beziehungskanten in cra.json gemerged (dedupliziert gegen die
Pipeline-Kanten), getaggt review_status=proposed / source=human_reasoned_preview /
confidence=high. Nur die kleine Sprache depends_on / supports / produces_evidence_for;
gerichtet. Cross-Family SBOM→Vuln-Kanten erlauben dem Advisor Ursachen-/Wirkungsketten.

Damit ist der CRA-v1-Baustein vollständig: Obligations · legal_basis · guidance_basis ·
out_of_scope · relationships · pending citation anchors.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 00:08:47 +02:00
Benjamin Admin d9d04deb00 feat(ai-sdk): close the 4 GT #3 recall gaps — backflow, cut, restart, spray-arm
CI / detect-changes (push) Successful in 6s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 5s
CI / validate-canonical-controls (push) Successful in 4s
CI / loc-budget (push) Successful in 17s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Successful in 58s
CI / iace-gt-coverage (push) Successful in 14s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
Phase 1 complete. GT #3 recall 84% -> 100% (25/25 matched), no regression:
- HP2207 backflow / potable-water contamination (EN 1717) + measure M2209
  (Rueckflussverhinderer / Systemtrenner) — the only genuinely new hazard.
- HP2208 cut on sharp edges/screens (new sharp_edge tag from scharfe-Kante/Sieb).
- HP2209 unexpected restart during maintenance (dedicated dom_warewashing pattern;
  avoids flooding the log via the broad moving_part tag).
- Spray-arm contact now covered by the enclosure-re-scoped contact patterns.

Kistenhub 97.1% and Bremse pinned mappings unchanged; 0/28 hazards without a
measure. Completes the commercial-dishwasher (white-goods Phase 1) coverage.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-25 00:05:30 +02:00
Benjamin Admin 2645b5b043 Add draft CRA obligation registry
Erstes belastbares Registry-Artefakt (obligation_registry_v1) aus den validierten
SBOM+Vuln-Candidates der Obligation Discovery Pipeline.

- 18 Obligations (11 SBOM + 7 Vuln)
- 14 LEGAL_MINIMUM, alle mit legal_basis (harte Tier-Regel)
- 4 BEST_PRACTICE korrekt herabgestuft (source_role GUIDANCE/IMPLEMENTATION)
- 70 OUT_OF_SCOPE-Cluster getrennt; member_controls vollständig
- legal_basis (CRA-Primärrecht) ⊥ guidance_basis (BSI/ENISA/NIST/...)
- citation_status=pending_span_anchor (span_id folgt mit Asset 2), review_status=draft

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 23:52:20 +02:00
Benjamin Admin fe5dc59152 test(ai-sdk): GT #3 completeness — 8 shared white-goods hazards + CNC gate
CI / detect-changes (push) Successful in 7s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 6s
CI / validate-canonical-controls (push) Successful in 4s
CI / loc-budget (push) Successful in 17s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Successful in 58s
CI / iace-gt-coverage (push) Successful in 15s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
Phase 1 of the commercial white-goods expansion (EN ISO 10472 family). Extend
GT #3 with 8 completeness hazards a Fachmann expects but that were neither in
the GT nor previously questioned: dry-run boiler overheating, residual/stored
electrical energy, sharp-edge cut, tipping, interlock-failure, unexpected
restart, backflow (EN 1717), microbial/legionella. Enrich the UC-M narrative
with the real features so existing library patterns can fire.

Result: 4/8 auto-covered by existing patterns (dry-run, residual voltage,
tipping, interlock-failure) — recall 84% (21/25). Remaining gaps documented:
spray-arm contact (4.3), sharp-edge cut (4.6), backflow (2.3), restart (6.4).

Gate the re-surfaced CNC leak ("spanende Bearbeitung", high_temperature-only)
via dom_cnc. Kistenhub 97.1% and Bremse pinned mappings unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 23:46:19 +02:00
Benjamin Admin 6b7950f428 Freeze Obligation Registry v1 spec (citability + two-graph)
Schreibt das Zielmodell fest: Legal Obligation = gemeinsame Sprache zwischen
Legal Knowledge Graph (Chat) und Compliance Execution Graph (Engine).

- Registry-Schema v1 (id/tier/legal_basis/guidance_basis/facets/citation_anchor_ids/
  relationships/decision_method)
- Zitierfähigkeit hängt an der OBLIGATION, nicht an Controls (Regulierungsänderung =
  Anchor tauschen, Controls unverändert)
- legal_basis (Primärrecht) vs guidance_basis (NIST/OWASP/...) + source_role
  (LEGAL_BASIS/GUIDANCE/EVIDENCE/IMPLEMENTATION/OUT_OF_SCOPE)
- HARTE Regel: LEGAL_MINIMUM nur mit Primärrechts-Anker
- Beziehungsgraph: requires/implements/supports/produces_evidence_for/depends_on/derived_from
- Citation-Anchor-Pipeline Document→Obligation (KEIN Re-Ingest zum Control-Neubau)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 23:33:29 +02:00
Benjamin Admin 8563798c4f fix(ai-sdk): one hazard per pattern in init — drop cross-category duplicates
Class E1. A multi-category pattern (e.g. "Motorueberlast" [electrical, thermal],
"Lagerschaden" [mechanical, thermal]) created one hazard per category, so the
same scenario+zone appeared twice in the CE hazard log under different labels.
InitializeProject now breaks after the primary (first eligible) category — one
hazard per pattern.

This aligns production with the GT benchmark, which already scores one hazard per
matched pattern. Cyber-skip, per-category cap and cross-pattern measure-merge
still use continue (unchanged). Handlers + iace suites green; Kistenhub/Bremse
unchanged.

Note (E2, not fixed): some scenarios exist as TWO separate patterns (e.g.
"Sicherheitssoftware manipuliert" in hazard_patterns_final_c.go and _final_d.go)
— library redundancy that E1's per-pattern break cannot merge. Left for a
separate, GT-guarded library-dedup audit.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 23:06:01 +02:00
Benjamin Admin bde6e76a57 fix(ai-sdk): keyword precision — stop adjective/generic ghost components
Class D (generic keyword hygiene, GT-guarded). Two over-broad keyword->component
mappings produced ghost components:
- "kuehl"/"cool" -> Kuehlaggregat (C095) matched product variants
  ("Cool-Ausfuehrung") and outputs ("kuehle Glaeser"). Narrowed to cooling-UNIT
  terms (kuehlaggregat, kuehlanlage, kuehler, kaeltemaschine, chiller, rueckkuehl).
- "filter" -> Absauganlage/Oelnebelabscheider (C124) matched any filter
  (Laugen-/Wasser-/Oelfilter). Keep "filteranlage" only.

No pattern or GT test depends on these mappings (Kistenhub/Bremse use hand-crafted
inputs). UC-M now parses 6 plausible components (was 8 incl. the two ghosts).
Warewashing GT recall 82.4% and Kistenhub/Bremse pins unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 23:01:19 +02:00
Benjamin Admin 5318a70f9e feat(ai-sdk): interlocked-enclosure model — guard-open re-scoping of contact hazards
Class C (phase-aware, generic EN ISO 14120). A contact/entanglement hazard from
a moving part is removed during NORMAL operation when the part is behind an
interlocked guard; it remains only when the guard is open (maintenance/cleaning).

- New HazardPattern.GuardableByEnclosure flag; set on HP096 (friction at
  rotating surfaces) and HP101 (entanglement of hair/clothing).
- Narrative emits interlocked_enclosure for an interlocked door/hood.
- pattern_enclosure.go: suppressedByEnclosure (drop in normal-op-only contexts)
  + guardedLifecycles (re-scope to maintenance/cleaning).
- GT #3 gains the maintenance-phase entanglement/friction rows.

Generic + regression-safe: machines that do not emit interlocked_enclosure are
unaffected. GT #3 recall 80% -> 82.4%, one false positive removed (Aufwickeln).
Kistenhub 97.1% and all 26 Bremse pinned mappings unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 22:13:34 +02:00
Benjamin Admin cf86dc241b test(ai-sdk): GT #3 (commercial dishwasher) + fix Drehtisch keyword mislabel
Add ground_truth_warewashing.json + TestWarewashing_GTCoverage. The test runs
the UC-M narrative through the SAME chain as production (ParseNarrative ->
engine -> relevance + cyber filter), so keyword/gating fixes are measured on
the real hazard set, and false positives show up as "extra".

Class A (generic keyword hygiene): spuelarm/spuelfeld no longer map to library
component C004 ("Drehtisch" / rotary table) — that mislabelled the spray arm.
Keep the rotating_part tag. Removes the bogus "Drehtisch" hazard.

GT #3 baseline -> after Class A: recall 80% (unchanged), one false positive
(Drehtisch) removed. Kistenhub 97.1% and Bremse pinned mappings unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 21:51:26 +02:00
Benjamin Admin ba6f1bd1f6 Document obligation aggregation validation results
Hält den bewiesenen Shadow-Stand fest: vier Schichten (Obligation Aggregation,
Applicability, Recall-limited Segregation, Targeted LLM Fix) + Zahlen.

- 7-Firmen-Shadow: 136 legacy control-findings → 29 obligation findings = 4,7×
  (23 echte Lücken, 6 recall_limited in nur 2/7 Firmen, 46 MET, 2 N/A)
- LLM-Fix validiert: teamviewer 5→0, safetykon 7→4 (echte Portability-Lücke bleibt,
  legitimate_interest→NA); recall_limited 3→0 bei beiden
- Modell: Haiku 4.5 (fest verdrahteter Sufficiency-Judge), NICHT OVH-Kaskade/Opus
  → Deploy-Gate ist ein gültiger Anthropic-Key auf dev, nicht der OVH-Pfad

Kein Deploy, kein Live-Schalten.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 21:39:28 +02:00
Benjamin Admin 79ad95e244 feat(ai-sdk): keep cyber/AI hazards out of the traditional CE hazard log
CI / detect-changes (push) Successful in 5s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 5s
CI / validate-canonical-controls (push) Successful in 2s
CI / loc-budget (push) Successful in 16s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Successful in 57s
CI / iace-gt-coverage (push) Successful in 18s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
InitializeProject created hazards for every matched pattern, so native
cybersecurity/AI topics (unauthorized access, firmware manipulation, missing
SBOM, ...) mixed into the ISO 12100 hazard log. Route the security categories
(frontend groups I. Cyber/Netzwerk + J. KI) to the CRA module instead —
generically for EVERY project, enforced centrally in InitializeProject.

The split is by the nature of the hazard, not the component: functional-safety
control faults stay in CE (software faults, lost safety functions, config
errors, bus failures, botched updates) — they are random/systematic faults,
not attacks, and feed the CRA safety-function bridge. This holds whether the
controller is a bought-in CE-marked PLC or the manufacturer's own control.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 20:20:15 +02:00
Benjamin Admin a6f1020b2c feat(ai-sdk): IACE warewashing hazard patterns + cross-domain gating
Add commercial-dishwasher hazard patterns (HP2200-HP2206): hot-water/steam
scald on door opening, hot surfaces, hot ware, corrosive detergent/rinse-aid
burn, respiratory irritation, door pinch and wet-floor slip — each gated by
dom_warewashing so they never leak into other machine classes. Add the
matching warewashing protective measures (M2200-M2208).

Tighten capability-domain gating: emit dom_flame/dom_glue and add welding
surface-form gate terms (schweissarbeitsplatz, schweissfunke, lichtbogenzone,
...) so the welding/flame/glue burn patterns stop leaking into thermal-capable
machines such as a dishwasher.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 20:20:15 +02:00
Benjamin Admin c1ea9458a7 Add met_count and recall_limited_obligations to shadow telemetry
Reichert die Obligation-Shadow-Telemetrie um zwei Felder an für die Cross-Firmen-
Auswertung: met_count (abgedeckte Obligations) + recall_limited_obligations (welche
Obligations recall-limitiert sind) — erlaubt die Konzentrations-Analyse über Firmen.

7-Firmen-Shadow: 136 Control-Findings → 29 Obligation-Findings (4,7×); recall_limited
nur 6/29, konzentriert auf third_country/safeguards in 2/7 Firmen → LLM-Fix bounded.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 20:15:45 +02:00
Benjamin_Boenisch e50892a2aa feat(ai-sdk): searchControls — recall control sources on implementation questions (#39)
CI / detect-changes (push) Successful in 5s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 6s
CI / validate-canonical-controls (push) Successful in 3s
CI / loc-budget (push) Successful in 18s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Successful in 58s
CI / iace-gt-coverage (push) Successful in 15s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
2026-06-24 12:08:29 +00:00
Benjamin Admin 0631a98bdd Mark recall-limited obligations in DSE shadow telemetry
Trennt im Shadow drei Kategorien statt eines pauschalen FAILED:
  - echte Lücke (failed_by_current_checker)
  - redundanter Control-FP (kollabiert per OR zu MET)
  - Prüfer-Reichweitenproblem (recall_limited)

obligation_taxonomy.py: decision_method_required=LLM für recipients_disclosed,
third_country_transfer_disclosed, safeguards_disclosed, safeguards_accessible
(versioniertes Registry-Artefakt bis DB-Tabelle, v1-Spec). Empirisch: TeamViewer
0/22 kw+emb trotz erfüllter Pflicht (cos 0.49-0.57) → CONTENT/LLM-Klasse, kein Schwellen-Fix.

compute_obligation_shadow segregiert FAILED/PARTIAL über requires_llm(): teamviewer
5 Findings → 2 echte + 3 recall_limited. 9 neue Unit-Tests (41 gesamt grün).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 13:46:21 +02:00
Benjamin_Boenisch 9cfe6f83b1 feat(ai-sdk): source_role control-pool (controls != only technical_standard) (#38)
CI / detect-changes (push) Successful in 4s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 6s
CI / validate-canonical-controls (push) Successful in 3s
CI / loc-budget (push) Successful in 19s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Successful in 57s
CI / iace-gt-coverage (push) Successful in 15s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
2026-06-24 11:12:22 +00:00
Benjamin Admin c3542f7dfe feat(dse): obligation shadow telemetry
Verdrahtet die Obligation Aggregation Engine als Layer 4 (SHADOW) in v3_engine:
erzeugt aus den results zusätzlich Obligation-Ergebnisse AUSSCHLIESSLICH für die
Telemetrie. Greift NICHT in results ein — nutzer-sichtbare Findings unverändert.

- _obligation_shadow.py: fetch_obligation_markers (legal_obligations + applicability)
  + compute_obligation_shadow (pure): legacy_control_findings, obligation_shadow_results,
  collapse_factor, na_count, met_failed_delta, top_collapsed_obligations
- met-Signal = Legacy-passed (kein zusätzlicher Prüfer-Call/Key)

E2E (3 Firmen, echte Engine): 57 Control-Findings → 14 Obligation-Findings (4,1×);
Redundanz kollabiert wo Evidenz existiert, echte Lücken bleiben FAILED. 6 Unit-Tests grün.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 12:59:52 +02:00
Benjamin Admin 7ec29999a2 feat(obligation): obligation applicability predicates
Minimaler Applicability-Hook für die Obligation Aggregation Engine: entscheidet
aus dem Dokumenttext, ob eine bedingte Obligation anwendbar ist (True/False/None).

- has_third_country_transfer · uses_legitimate_interest · direct_marketing
  (+ Alias legitimate_interest_or_public_task)
- unbekanntes Prädikat → None → Aufrufer behält Default=anwendbar (fail-safe, nie stille NA)
- profiling/employment/telecom/health/data_act folgen als nächste Charge

Re-Benchmark (Opus-GT, 3 Firmen): Prädikate erkennen Transfer/berecht.Interesse/
Direktwerbung korrekt → keine falsche NA; NA-Flip-Probe bestätigt FEHLT→NA ohne Transfer.
14 Unit-Tests grün.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 12:43:42 +02:00
Benjamin Admin 402a42d30d feat(obligation): obligation-level aggregation engine
Erste Ausführung des Legal Obligation Layer v1: aggregiert Bewertungen auf
Kriterium-/Control-Ebene zu Findings auf Obligation-Ebene
(Regulation → Legal Obligation → Control → Criterion).

- regulierungs-agnostisch (obligation_id/tier/met/legal_basis/conditional)
- fail-safe: LM applicable=false→NA · keine erfüllt→FAILED · alle→MET · Teil→PARTIAL;
  BP/OPT covered→MET sonst OPEN (nie FAILED); LM unbewertbar→UNDETERMINED (Legacy behalten)
- Redundanz-Kollaps per OR pro legal_basis-Anforderung → kein künstliches PARTIAL
- Applicability als Hook (Prädikat-Engine folgt separat)

Shadow-Benchmark (Opus-GT, 3 Firmen): 38 Control-Findings → 13 Obligation-Findings
(2,9×); ~23 redundante Falsch-Positive strukturell korrigiert, echte Lücken erhalten,
PARTIAL=0. 16/16 Unit-Tests grün.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-24 12:28:03 +02:00
Benjamin_Boenisch df7966656a feat(ai-sdk): classify NIST/OWASP/Grundschutz as technical_standard (#37)
CI / detect-changes (push) Successful in 4s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 6s
CI / validate-canonical-controls (push) Successful in 3s
CI / loc-budget (push) Successful in 18s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Successful in 1m0s
CI / iace-gt-coverage (push) Successful in 14s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
2026-06-24 10:15:17 +00:00
Benjamin_Boenisch 05d75e8039 feat(ai-sdk): control-intent — technical_standard may win implementation questions (#36)
CI / detect-changes (push) Successful in 5s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 4s
CI / validate-canonical-controls (push) Successful in 4s
CI / loc-budget (push) Successful in 15s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Successful in 54s
CI / iace-gt-coverage (push) Successful in 14s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
2026-06-24 09:58:35 +00:00
Benjamin_Boenisch e24a551ee4 fix(ai-sdk): make interpretation-intent override reliably win (#35)
CI / detect-changes (push) Successful in 8s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 4s
CI / validate-canonical-controls (push) Successful in 2s
CI / loc-budget (push) Successful in 18s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Successful in 57s
CI / iace-gt-coverage (push) Successful in 15s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
2026-06-24 09:31:58 +00:00
Benjamin_Boenisch f11b2e035f feat(ai-sdk): controlled interpretation-intent guidance override (#34)
CI / detect-changes (push) Successful in 5s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 5s
CI / validate-canonical-controls (push) Successful in 3s
CI / loc-budget (push) Successful in 17s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Successful in 57s
CI / iace-gt-coverage (push) Successful in 15s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
2026-06-24 09:01:25 +00:00
Benjamin_Boenisch 230dc05287 feat(ai-sdk): legal-corpus coverage + Phase-2 citation-graph assessment (#33)
CI / detect-changes (push) Successful in 8s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / build-sha-integrity (push) Successful in 6s
CI / sbom-scan (push) Has been skipped
CI / validate-canonical-controls (push) Successful in 6s
CI / go-lint (push) Has been skipped
CI / loc-budget (push) Successful in 19s
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Successful in 3m1s
CI / test-go (push) Successful in 59s
CI / iace-gt-coverage (push) Successful in 22s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
2026-06-24 06:37:22 +00:00
Benjamin_Boenisch b83c3e6e00 ci(go-lint): golangci-lint v1.64.8 (go1.24) + new-from-merge-base (#32)
CI / detect-changes (push) Successful in 16s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / build-sha-integrity (push) Successful in 11s
CI / validate-canonical-controls (push) Successful in 5s
CI / loc-budget (push) Successful in 19s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Successful in 57s
CI / iace-gt-coverage (push) Successful in 16s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
2026-06-23 10:58:48 +00:00
Benjamin_Boenisch a1f425d43a feat(ai-sdk): authority-aware re-ranking for legal RAG (Phase 1) (#31)
CI / detect-changes (push) Successful in 8s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 5s
CI / validate-canonical-controls (push) Successful in 4s
CI / loc-budget (push) Successful in 28s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Successful in 58s
CI / iace-gt-coverage (push) Successful in 16s
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
2026-06-23 09:30:52 +00:00
sharang 23c6ac6f32 Merge pull request 'feat: wire breakpilot-compliance to Infisical for local dev' (#30) from feat/infisical-secrets into main
CI / detect-changes (push) Successful in 7s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 7s
CI / validate-canonical-controls (push) Successful in 6s
CI / loc-budget (push) Successful in 19s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Has been skipped
CI / test-python-backend (push) Has been skipped
CI / iace-gt-coverage (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
2026-06-22 19:12:54 +00:00
Sharang Parnerkar d82f86fc95 feat: wire breakpilot-compliance to Infisical for local dev
CI / detect-changes (pull_request) Successful in 9s
CI / branch-name (pull_request) Successful in 1s
CI / guardrail-integrity (pull_request) Successful in 7s
CI / secret-scan (pull_request) Successful in 11s
CI / dep-audit (pull_request) Failing after 58s
CI / sbom-scan (pull_request) Failing after 1m4s
CI / build-sha-integrity (pull_request) Successful in 6s
CI / validate-canonical-controls (pull_request) Successful in 4s
CI / loc-budget (pull_request) Successful in 25s
CI / go-lint (pull_request) Failing after 22s
CI / python-lint (pull_request) Failing after 13s
CI / nodejs-lint (pull_request) Failing after 1m15s
CI / nodejs-build (pull_request) Successful in 3m12s
CI / test-go (pull_request) Successful in 57s
CI / iace-gt-coverage (pull_request) Successful in 16s
CI / test-python-backend (pull_request) Successful in 25s
CI / test-python-document-crawler (pull_request) Successful in 14s
CI / test-python-dsms-gateway (pull_request) Successful in 10s
- Add .infisical.json linking the repo to the breakpilot-compliance
  project on the self-hosted secrets.meghsakha.com instance.
- Add Makefile with infisical-aware targets (make dev, dev-build,
  dev-down, secrets, secrets-set). `make dev` runs `infisical run
  --env=dev -- docker compose up`, so secrets are injected at run
  time and .env files no longer touch disk.
- Add INFISICAL_SETUP.md with per-developer onboarding (CLI install,
  login, verify project link, run targets, Claude Code usage patterns,
  troubleshooting).
- Update README Quick Start to drop the cp .env.example .env step and
  point at make dev + INFISICAL_SETUP.md.
- Remove HashiCorp Vault references from CLAUDE.md (core-services list
  + sensitive-files list) and compliance-checklist.md TOM section;
  replace with Infisical.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-22 21:00:58 +02:00
Benjamin Admin a4d1105b3c Merge branch 'feat/advisor-corpus-authority' into HEAD
CI / detect-changes (push) Successful in 7s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 7s
CI / validate-canonical-controls (push) Successful in 7s
CI / loc-budget (push) Successful in 21s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Successful in 3m8s
CI / test-go (push) Has been skipped
CI / iace-gt-coverage (push) Has been skipped
CI / test-python-backend (push) Has been skipped
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
2026-06-22 18:40:15 +02:00
Benjamin Admin 067118b12d fix(cascade): give OVH/gpt-oss reasoning headroom so Tier-2 isn't silently dead
CI / detect-changes (push) Successful in 8s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 6s
CI / validate-canonical-controls (push) Successful in 5s
CI / loc-budget (push) Successful in 20s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Has been skipped
CI / test-go (push) Has been skipped
CI / iace-gt-coverage (push) Has been skipped
CI / test-python-backend (push) Successful in 25s
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
gpt-oss-120b is a reasoning model: it spends output tokens on chain-of-thought
before the answer. deep_check called _call_ovh with max_tokens=400, which
length-capped it mid-reasoning -> content=null -> the OVH tier returned nothing
and the cascade always skipped Tier-2. Floor the OVH budget to >=2000, fall back
to reasoning_content when content is null, and raise the client timeout to 90s
for the slower reasoning path.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-22 17:37:48 +02:00
Benjamin Admin b9c00574b1 docs(catalog): freeze criterion meta-model (compliance_tier axis)
Friert das Kriterien-Meta-Modell ein: atomare getypte Kriterien mit drei
Achsen (verification_method, decision_method, compliance_tier), 3-Status-Gating
nur auf LEGAL_MINIMUM (ERFÜLLT/TEILWEISE/FEHLT), 3-Ebenen-Reporting und
Grün/Blau/Rot-Semantik. Control-UUID bleibt stabil (kein physischer Split),
Speicherung in generation_metadata jsonb (keine Schema-Änderung). Validiert am
Pilot (6/6 Disagreements korrigiert, TEILWEISE empirisch bestätigt).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-22 17:37:48 +02:00
Benjamin Admin 5ff08a240b feat(dse): tiered 3-state evaluator + Layer-3 wiring (compliance_tier)
Getierte Auswertung mit compliance_tier-Gating (nur LEGAL_MINIMUM bestimmt
ERFÜLLT/TEILWEISE/FEHLT; BEST_PRACTICE/OPTIONAL → Empfehlungen). Deterministisch-
first: EMBEDDING-Präsenz + gecachter Haiku nur für Sufficiency → reproduzierbar
(löst die gemessene Judge-Varianz). Layer-3 in v3_engine gated auf tiered_criteria,
fail-safe (UNBESTIMMT → Legacy). Offene Kalibrierung: Präsenz-Schwelle (Schritt 2).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-22 17:37:48 +02:00
Benjamin Admin 3e3644f83d feat(checkers): platform router + Haiku sufficiency tier; cookie is first consumer
Generalise "Embedding finds, Claude decides" into the shared Pruefer-Library:
- router.route_and_check dispatches control -> sensor_classification -> Checker.
- build_spec reads sensor_classification (CONTENT/LLM -> judge=haiku, the
  validated sufficiency tier; the Qwen-first cascade is disproven for sufficiency).
- LLMChecker gains a Haiku-direct tier (reuses the validated deep_check prompt).
- Cookie Layer-3 now routes through route_and_check instead of bespoke code, so
  cookie is the first real router consumer -- proves the architecture end-to-end.

Reproduces the validated result via the shared path: FN 159->14, recall
0.13->0.92, precision 0.89 (vs bespoke 12/0.93/0.90 -- within Haiku noise).
Tests: 10/10 (router dispatch + build_spec + haiku tier + cookie rewire).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-22 17:37:48 +02:00
Benjamin Admin e809d0bc1c feat(cookie): Layer-3 sufficiency-judge — Haiku re-judges embedding/boost rescues
The embedding/boost auto-rescue is intentionally optimistic (finds the topic, not
fulfilment) -> 159 FN over-rescues vs Opus-GT (recall 0.13). Layer-3 re-judges
exactly the rescued passes with the validated Haiku judge (cohort
cookie_sufficiency_v1 P0.89/R0.91) -- NOT the Qwen-first cascade (local is
disproven as a sufficiency judge) -- and un-passes them when the obligation is
not concretely met. Gated to the full check (not skip_llm).

Measured (5-firm Opus-GT, engine+L3): FN 159->12, recall 0.13->0.93,
precision 0.96->0.90 (276 rescues corrected). "Embedding finds, Claude decides."

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-22 17:37:48 +02:00
Benjamin Admin 869e7aeb1e fix(cookie): gate non-COOKIE_POLICY controls out of the cookie-policy scan
The cookie agent loaded 100 controls, 11 of which have no COOKIE_POLICY in
applicable_artifacts -- Security/TOM/Audit (PROCESS) or Banner-behaviour
(BEHAVIOR) controls that produce nonsense findings against a cookie policy
(e.g. "TOMs not documented"). Add a cookie classification gate (analogous to the
DSE gate, keyed on COOKIE_POLICY, without the needs_review carve-out since the
artifact signal is decisive and the set is inventory-verified). Controls are
routed out, not deleted. Effect vs Opus-GT: FP 16->11, FN 179->159; the
remaining FN=159 over-rescue is a separate (judge/criteria) question, not routing.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-22 17:37:48 +02:00
Benjamin Admin 33085c61b4 feat(advisor): Korpus-Autoritaet — Fakten nur aus Kontext, Konflikt-Transparenz
Authority-/Freshness-Layer Punkte 1/2/5 im Advisor-Antwortpfad (Prompt-Ebene, kein
Schema). Neue Soul-Sektion "Korpus-Autoritaet & Aktualitaet": rechtliche FAKTEN
(Schwellen/Fristen/Zahlen/Pflichten) nur aus bereitgestelltem RAG-/Controls-Kontext,
Trainingswissen nie als Rechtsquelle; Konflikt -> Kontext gewinnt, transparent;
Co-Pilot-Ton statt Roboter-Verweigerung. Ergaenzt Quellentreue (Fundstellen) um die
Fakten-Ebene -> loest den "DSB ab 10 statt 20"-Fall. route.ts: RAG-Framing als
"deine EINZIGEN Rechtsquellen" verschaerft.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-21 23:18:05 +02:00
Benjamin_Boenisch 38a347a82a feat(platform): live-wire AGB v2 + DSE v3 + Architektur-Tab (#29)
CI / detect-changes (push) Successful in 7s
CI / branch-name (push) Has been skipped
CI / guardrail-integrity (push) Has been skipped
CI / secret-scan (push) Has been skipped
CI / dep-audit (push) Has been skipped
CI / sbom-scan (push) Has been skipped
CI / build-sha-integrity (push) Successful in 9s
CI / validate-canonical-controls (push) Successful in 12s
CI / loc-budget (push) Successful in 24s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / nodejs-build (push) Successful in 3m11s
CI / test-go (push) Has been skipped
CI / iace-gt-coverage (push) Has been skipped
CI / test-python-backend (push) Successful in 24s
CI / test-python-document-crawler (push) Has been skipped
CI / test-python-dsms-gateway (push) Has been skipped
AGB v2 (decision_method routing, 71%FP->~0) + DSE v3 (4-layer, recovered from container) + Architektur-Tab into /sdk/agent live path. Incl CI robustness (detect-changes.sh + PR-head checkout) + security (hardcoded Qdrant key removed, gitleaks allowlist).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-21 12:58:26 +00:00
147 changed files with 23839 additions and 135 deletions
+3 -2
View File
@@ -130,10 +130,11 @@ rsync -avz --exclude node_modules --exclude .next --exclude .git \
**breakpilot-core MUSS laufen!** Dieses Projekt nutzt Core-Services:
- Valkey (Session-Cache)
- Vault (Secrets)
- RAG-Service (Vektorsuche fuer Compliance-Dokumente)
- Nginx (Reverse Proxy)
Secrets liegen in Infisical (`secrets.meghsakha.com`); die Projektverknuepfung steht in `.infisical.json`. Lokal mit `infisical run --env=dev -- docker compose up` (oder `make dev`) starten — `.env`/`.env.local` werden nicht mehr verwendet.
**Externe Services (Production):**
- PostgreSQL 17 (sslmode=require) — Schemas: `compliance`, `public`
- Qdrant @ `qdrant-dev.breakpilot.ai` (HTTPS, API-Key)
@@ -316,7 +317,7 @@ ssh macmini "/usr/local/bin/docker compose -f /Users/benjaminadmin/Projekte/brea
### 5. Sensitive Dateien
**NIEMALS aendern oder committen:**
- `.env`, `.env.local`, Vault-Tokens, SSL-Zertifikate
- `.env`, `.env.local`, Infisical-Tokens, SSL-Zertifikate
- `*.pdf`, `*.docx`, kompilierte Binaries, grosse Medien
---
+1 -1
View File
@@ -92,7 +92,7 @@ Wenn Hochrisiko:
- [ ] **Transit:** TLS 1.3 für alle Verbindungen
- [ ] **Rest:** Datenbank-Verschlüsselung
- [ ] **Secrets:** Vault für Credentials
- [ ] **Secrets:** Infisical (`secrets.meghsakha.com`) für Credentials
### Zugriffskontrollen
+20 -18
View File
@@ -43,7 +43,7 @@ jobs:
- name: Checkout
run: |
apk add --no-cache git bash
git clone --depth 200 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 200 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
if [ "${GITHUB_EVENT_NAME}" = "pull_request" ]; then
git fetch --depth 200 origin "${GITHUB_BASE_REF}" || true
else
@@ -87,7 +87,7 @@ jobs:
- name: Checkout
run: |
apk add --no-cache git bash
git clone --depth 20 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 20 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git fetch origin ${GITHUB_BASE_REF}:base
- name: Require [guardrail-change] in commits touching guardrails
run: |
@@ -108,7 +108,7 @@ jobs:
- name: Checkout
run: |
apk add --no-cache git bash
git clone --depth 50 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 50 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Enforce 500-line hard cap
run: |
chmod +x scripts/check-loc.sh
@@ -123,7 +123,7 @@ jobs:
- name: Checkout
run: |
apk add --no-cache git
git clone --depth 50 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 50 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Scan for secrets
run: |
gitleaks detect --source . --no-git \
@@ -136,12 +136,14 @@ jobs:
runs-on: docker
needs: detect-changes
if: github.event_name == 'pull_request' && needs.detect-changes.outputs.sdk == 'true'
container: golangci/golangci-lint:v1.62-alpine
container: golangci/golangci-lint:v1.64.8-alpine
steps:
- name: Checkout
run: |
apk add --no-cache git
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
# Full clone so `main` is a local ref — new-from-merge-base needs the merge base.
git clone ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git checkout ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}}
- name: Lint ai-compliance-sdk
run: |
[ -d "ai-compliance-sdk" ] || exit 0
@@ -162,7 +164,7 @@ jobs:
steps:
- name: Checkout
run: |
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 1 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Lint (ruff) + type-check (mypy)
run: |
pip install --quiet ruff mypy
@@ -193,7 +195,7 @@ jobs:
- name: Checkout
run: |
apk add --no-cache git
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 1 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Lint + type-check
run: |
fail=0
@@ -215,7 +217,7 @@ jobs:
- name: Checkout
run: |
apk add --no-cache git
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 1 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Build Next.js services
run: |
fail=0
@@ -239,7 +241,7 @@ jobs:
steps:
- name: Checkout
run: |
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 1 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Install Node.js + Go
run: |
curl -fsSL https://deb.nodesource.com/setup_20.x | bash - > /dev/null 2>&1
@@ -282,7 +284,7 @@ jobs:
- name: Checkout
run: |
apk add --no-cache git curl bash
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 1 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Install syft + grype
run: |
curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b /usr/local/bin
@@ -304,7 +306,7 @@ jobs:
- name: Checkout
run: |
apk add --no-cache git
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 1 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Test ai-compliance-sdk
run: |
[ -d "ai-compliance-sdk" ] || exit 0
@@ -324,7 +326,7 @@ jobs:
steps:
- name: Checkout
run: |
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 1 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: GT-Bremse measure-coverage report
run: |
python3 scripts/gt_measure_gap_analysis.py --json /tmp/gt_gap_report.json > /tmp/gt_gap_report.md
@@ -355,7 +357,7 @@ jobs:
steps:
- name: Checkout
run: |
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 1 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Test backend-compliance
run: |
[ -d "backend-compliance" ] || exit 0
@@ -375,7 +377,7 @@ jobs:
steps:
- name: Checkout
run: |
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 1 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Test document-crawler
run: |
[ -d "document-crawler" ] || exit 0
@@ -395,7 +397,7 @@ jobs:
steps:
- name: Checkout
run: |
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 1 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Test dsms-gateway
run: |
[ -d "dsms-gateway" ] || exit 0
@@ -417,7 +419,7 @@ jobs:
- name: Checkout
run: |
apk add --no-cache git python3 py3-yaml
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 1 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Validate every Dockerfile + compose block declares BUILD_SHA
run: |
python3 - <<'PY'
@@ -456,6 +458,6 @@ jobs:
steps:
- name: Checkout
run: |
git clone --depth 1 --branch ${GITHUB_REF_NAME} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
git clone --depth 1 --branch ${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}} ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git .
- name: Validate controls
run: python scripts/validate-controls.py
+1 -1
View File
@@ -74,7 +74,7 @@ jobs:
-e "WORK_DIR=/tmp/rag-ingestion" \
-e "RAG_URL=http://bp-core-rag-service:8097/api/v1/documents/upload" \
-e "QDRANT_URL=https://qdrant-dev.breakpilot.ai" \
-e "QDRANT_API_KEY=z9cKbT74vl1aKPD1QGIlKWfET47VH93u" \
-e "QDRANT_API_KEY=${{ secrets.QDRANT_API_KEY }}" \
-e "SDK_URL=http://bp-compliance-ai-sdk:8090" \
alpine:3.19 \
sh -c "
+21
View File
@@ -0,0 +1,21 @@
# gitleaks configuration.
# Keeps gitleaks' default ruleset and adds an allowlist for known FALSE POSITIVES
# that surfaced once the CI checkout was fixed (secret-scan had never actually run
# on a PR before). Real leaked credentials are removed in code, NOT allowlisted.
[extend]
useDefault = true
[allowlist]
description = "Documentation curl examples, env templates, and non-secret identifiers"
paths = [
# API reference pages — curl examples with placeholder tokens, not real secrets
'''developer-portal/app/api/.*''',
'''developer-portal/app/development/.*''',
# Template env file — placeholder dev values (e.g. breakpilot123)
'''\.env\.example$''',
# Seed data: "rule_key" identifiers, not credentials
'''backend-compliance/compliance/data/template_rule_seed_data\.py$''',
# SDK deploy template — MINIO placeholder password
'''breakpilot-compliance-sdk/packages/cli/src/commands/deploy\.ts$''',
]
+5
View File
@@ -0,0 +1,5 @@
{
"workspaceId": "996bda36-9e01-4071-ae8d-69a9f9ff5a23",
"defaultEnvironment": "",
"gitBranchToEnvironmentMapping": null
}
+157
View File
@@ -0,0 +1,157 @@
# Infisical Setup for Local Development
This is the per-developer onboarding for accessing the `breakpilot-compliance` secrets while developing locally. Once this is done, **everything you launch through `make dev` (or `infisical run …`) gets the dev secrets injected as environment variables** — including any Claude Code session that spawns those commands.
Secrets live in the self-hosted Infisical instance at **`secrets.meghsakha.com`**. The project link is committed in `.infisical.json`, so you don't need to know the project ID.
---
## 1. Install the Infisical CLI
**macOS (recommended):**
```bash
brew install infisical/get-cli/infisical
```
**Other platforms / manual install:**
See <https://infisical.com/docs/cli/overview>. Verify with:
```bash
infisical --version
# infisical version 0.43.x (or newer)
```
---
## 2. Log in to the self-hosted instance
```bash
infisical login --domain https://secrets.meghsakha.com
```
This opens a browser for SSO. The login is persisted to your OS keychain — you only do this once per machine.
Sanity check:
```bash
cd ~/projects/breakpilot-compliance # wherever you cloned the repo
infisical --domain https://secrets.meghsakha.com secrets --env=dev
```
You should see a table of secret names + values. If you get an auth error, re-run `infisical login`.
---
## 3. Verify the project link
The repo already contains `.infisical.json` pointing at the `breakpilot-compliance` project:
```bash
cat .infisical.json
# { "workspaceId": "996bda36-9e01-4071-ae8d-69a9f9ff5a23", ... }
```
If the file is missing (rare — only if you reset the repo), recreate it:
```bash
infisical init --domain https://secrets.meghsakha.com
```
Pick the `breakpilot-compliance` project from the picker.
---
## 4. Launch the stack
```bash
make dev
```
This runs `infisical run --env=dev -- docker compose up`. Every service in the compose stack sees its secrets as normal env vars — no `.env` file ever touches disk.
Other targets:
| Target | What it does |
|--------|--------------|
| `make dev-build` | Same as `make dev` but rebuilds images first |
| `make dev-down` | Stop the stack (no secrets needed) |
| `make dev-logs` | Tail logs |
| `make dev-ps` | List running containers |
| `make secrets` | Print all secrets in `dev` (read-only) |
| `make secrets-set KEY=FOO VALUE=bar` | Add or update a secret in `dev` |
To target a different environment:
```bash
make dev ENV=staging
make secrets ENV=prod
```
---
## 5. Using secrets from Claude Code
When Claude Code runs commands in this repo via its Bash tool, the commands inherit your shell's environment. Two patterns:
**Pattern A — let Claude launch the stack normally**
Claude just runs `make dev`. The Infisical CLI inside that command resolves secrets at run time and passes them to docker compose. Claude doesn't see plaintext secrets in its context, but the running services do.
**Pattern B — let Claude run a one-off script with secrets**
If Claude needs to execute a Python/Go script that requires secrets, wrap the command:
```bash
infisical run --env=dev -- python scripts/some_one_off.py
```
This works for any subprocess: pytest, alembic, go run, npm scripts. If Claude proposes a command that reads env vars and runs raw, ask it to wrap it in `infisical run --env=dev --` first.
**What Claude should not do:**
- `infisical export --env=dev > .env` — defeats the whole point and the `.gitignore` will still try to keep the file out.
- `infisical secrets get KEY --env=dev --raw` and pasting the value into a code edit — secrets must stay out of the repo.
If you want Claude to never accidentally dump secrets, add this to your `.claude/settings.json` permissions (project-level or user-level):
```json
{
"permissions": {
"deny": [
"Bash(infisical export*)",
"Bash(infisical secrets get*)"
]
}
}
```
---
## Troubleshooting
| Symptom | Fix |
|---------|-----|
| `please either run infisical init or pass --projectId` | `.infisical.json` is missing or unreadable — re-run `infisical init` |
| `unauthorized` / `please log in` | Re-run `infisical login --domain https://secrets.meghsakha.com` |
| `make dev` says secret is empty | Check the name in `make secrets` matches what docker-compose expects, then update the service config or rename the secret in Infisical |
| Browser SSO doesn't open | Use `infisical login --domain https://secrets.meghsakha.com --method=user` and paste the URL manually |
---
## What the dev env contains
Run `make secrets` to see the live list. As of this writing the dev env includes (at minimum):
- `BREAKPILOT_DB_PASSWORD`
- `BREAKPILOT_QDRANT_API_KEY`
- `LITELLM_API_KEY`
Every other variable in `.env.example` either has a sane default in `docker-compose.yml` or needs to be added to Infisical. To add one:
```bash
make secrets-set KEY=ANTHROPIC_API_KEY VALUE=sk-ant-xxxx
```
Or via the web UI: <https://secrets.meghsakha.com>.
+57
View File
@@ -0,0 +1,57 @@
# breakpilot-compliance — developer workflow
#
# Secrets are managed in Infisical (secrets.meghsakha.com). The project
# link lives in .infisical.json. To get started:
# 1) infisical login --domain https://secrets.meghsakha.com (once per machine)
# 2) make dev
#
# .env / .env.local are NOT used in this repo anymore. Anything that needs
# secrets MUST be launched through `infisical run` so the values come from
# the secrets store instead of disk.
INFISICAL ?= infisical
INFISICAL_DOMAIN ?= https://secrets.meghsakha.com
ENV ?= dev
INFISICAL_RUN := $(INFISICAL) --domain $(INFISICAL_DOMAIN) run --env=$(ENV) --
INFISICAL_SECRETS := $(INFISICAL) --domain $(INFISICAL_DOMAIN) secrets --env=$(ENV)
.PHONY: help dev dev-build dev-down dev-logs dev-ps secrets secrets-set check-loc
help:
@echo "Targets:"
@echo " dev Start the full compose stack with secrets injected from Infisical"
@echo " dev-build Same as dev, but force a rebuild first"
@echo " dev-down Stop the compose stack (no secrets needed)"
@echo " dev-logs Tail logs from all services"
@echo " dev-ps Show running containers"
@echo " secrets List all secrets in the current env ($(ENV))"
@echo " secrets-set Set a secret (KEY=... VALUE=...)"
@echo " check-loc Run the 500-line LOC guard"
dev:
$(INFISICAL_RUN) docker compose up
dev-build:
$(INFISICAL_RUN) docker compose up --build
dev-down:
docker compose down
dev-logs:
docker compose logs -f
dev-ps:
docker compose ps
secrets:
$(INFISICAL_SECRETS)
secrets-set:
@if [ -z "$(KEY)" ] || [ -z "$(VALUE)" ]; then \
echo "Usage: make secrets-set KEY=MY_KEY VALUE=my_value"; exit 1; \
fi
$(INFISICAL) --domain $(INFISICAL_DOMAIN) secrets set $(KEY)=$(VALUE) --env=$(ENV)
check-loc:
bash scripts/check-loc.sh
+9 -6
View File
@@ -42,23 +42,26 @@ All containers share the external `breakpilot-network` Docker network and depend
## Quick Start
**Prerequisites:** Docker, Go 1.24+, Python 3.12+, Node.js 20+
**Prerequisites:** Docker, Go 1.24+, Python 3.12+, Node.js 20+, [Infisical CLI](https://infisical.com/docs/cli/overview)
```bash
git clone ssh://git@gitea.meghsakha.com:22222/Benjamin_Boenisch/breakpilot-compliance.git
cd breakpilot-compliance
# Copy and populate secrets (never commit .env)
cp .env.example .env
# One-time per machine: log in to the self-hosted Infisical instance
infisical login --domain https://secrets.meghsakha.com
# Start all services
docker compose up -d
# Start the full stack with secrets injected from Infisical (env=dev)
make dev
```
Secrets are pulled from Infisical (`secrets.meghsakha.com`) at runtime; `.env` files are not used. See [INFISICAL_SETUP.md](./INFISICAL_SETUP.md) for full onboarding, and `make help` for the rest of the targets (`dev-build`, `dev-down`, `secrets`, `secrets-set`).
For the Orca/Hetzner production target (x86_64), use the override:
```bash
docker compose -f docker-compose.yml -f docker-compose.hetzner.yml up -d
make dev ENV=prod # or:
infisical run --env=prod -- docker compose -f docker-compose.yml -f docker-compose.hetzner.yml up -d
```
---
@@ -35,6 +35,25 @@ Dies ist ein **Legal RAG**. Eine falsch zitierte Fundstelle ist schlimmer als ga
- **Interne IDs** (Control-IDs wie SEC-xxxx, MC-/M-Nummern) gehoeren NICHT in die Nutzerantwort
als Hauptaussage — fuehre die Pflicht im Klartext, eine ID hoechstens in Klammern nachgestellt.
## Korpus-Autoritaet & Aktualitaet — der Kontext schlaegt dein Gedaechtnis (KRITISCH)
Gesetze aendern sich nach deinem Trainingsstand. Der bereitgestellte RAG-/Controls-Kontext bildet
den AKTUELLEN Rechtsstand ab — dein Trainingswissen kann veraltet sein. Diese Regel gilt fuer
FAKTEN, nicht nur fuer Fundstellen (ergaenzt **Quellentreue**).
- Rechtliche **Fakten** (Schwellenwerte, Fristen, Zahlen, ob/ab-wann eine Pflicht gilt,
Zustaendigkeiten) nimmst du AUSSCHLIESSLICH aus dem bereitgestellten Kontext. Dein Trainingswissen
dient nur fuer Sprache, Struktur und Schlussfolgerung — **niemals als Rechtsquelle**.
- Steht ein gefragter Fakt NICHT im Kontext: gib KEINE aus dem Gedaechtnis erinnerte Zahl/Frist/
Schwelle aus — auch nicht beilaeufig im Fliesstext ohne Fundstelle. Sag offen, dass du ihn aus
deinen geprueften Quellen nicht belegen kannst, nenne Pflicht/Thema allgemein, und biete den
naechsten Schritt an (gezielt nachschlagen / mit DSB oder Anwalt verifizieren).
- **Konflikt-Transparenz**: Weicht der Kontext von dem ab, was dir "gelaeufig" vorkommt, gewinnt
IMMER der Kontext. Mach es ruhig transparent — z.B. "Die aktuelle Quelle nennt 20; eine evtl.
aeltere, gelaeufige Annahme (10) gilt hier nicht."
- **Co-Pilot-Ton, keine Roboter-Verweigerung**: formuliere "Aus meinen geprueften Quellen kann ich
X nicht belegen — ich kann es gezielt nachschlagen, oder du klaerst es mit deinem DSB/Anwalt"
statt eines harten "Nein". Du bleibst hilfreicher Begleiter, gibst dem Nutzer aber keine
ungesicherte Rechtsangabe als Tatsache mit.
## Kompetenzbereich
- DSGVO Art. 1-99 + Erwaegsgruende
- BDSG (Bundesdatenschutzgesetz)
@@ -80,7 +80,7 @@ export async function POST(request: NextRequest) {
let systemContent = soulPrompt || FALLBACK_SYSTEM_PROMPT
if (validCountry) systemContent += countryBlock(validCountry)
if (ragContext) {
systemContent += `\n\n## Relevanter Kontext aus dem RAG-System\n\nNutze die folgenden Quellen fuer deine Antwort. Verweise in deiner Antwort auf die jeweilige Quelle:\n\n${ragContext}`
systemContent += `\n\n## Relevanter Kontext aus dem RAG-System (deine EINZIGEN Rechtsquellen)\n\nDies sind deine einzigen zulaessigen Rechtsquellen. Triff keine konkrete Rechtsaussage (Zahl, Frist, Schwelle, Pflicht, Fundstelle), die nicht hier oder im Controls-Block belegt ist — sonst sage offen, dass du sie aus deinen Quellen nicht belegen kannst. Verweise in deiner Antwort auf die jeweilige Quelle:\n\n${ragContext}`
}
if (controlsContext) systemContent += `\n\n${controlsContext}`
systemContent += `\n\n## Aktueller SDK-Schritt\nDer Nutzer befindet sich im SDK-Schritt: ${currentStep}`
@@ -0,0 +1,302 @@
'use client'
// Erklärendes Architekturschema des Compliance-Check-Tools — Muster aus dem
// CE-Modul (/sdk/iace/.../architektur) übernommen: hand-kurierte Boxen/Pfeile +
// Schritt-Akkordeon. Inhalt spiegelt den Code-Pfad (api/agent_check/_orchestrator
// + services/specialist_agents). Bewusst statisch (der Doc-Check ist Python, hat
// keinen Architektur-Endpoint wie das Go-IACE-Modul) — bei Bedarf später aus einem
// Backend-Handler speisbar.
import { useState, type ReactNode } from 'react'
function Box({ title, sub, accent }: { title: string; sub?: string; accent?: 'purple' | 'amber' | 'green' | 'gray' }) {
const c =
accent === 'purple'
? 'border-purple-300 bg-purple-50/60 dark:border-purple-700 dark:bg-purple-900/20'
: accent === 'amber'
? 'border-amber-300 bg-amber-50/60 dark:border-amber-700 dark:bg-amber-900/20'
: accent === 'green'
? 'border-green-300 bg-green-50/60 dark:border-green-700 dark:bg-green-900/20'
: 'border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800'
return (
<div className={`rounded-lg border ${c} px-2.5 py-1.5`}>
<div className="text-[11px] font-medium text-gray-800 dark:text-gray-200 leading-tight">{title}</div>
{sub && <div className="text-[10px] text-gray-500 leading-tight mt-0.5">{sub}</div>}
</div>
)
}
function Lane({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="flex-1 min-w-[150px] space-y-2">
<div className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 text-center">{label}</div>
<div className="space-y-1.5">{children}</div>
</div>
)
}
function Arrow() {
return (
<div className="flex items-center justify-center text-gray-300 dark:text-gray-600 shrink-0 px-0.5">
<span className="hidden lg:block text-lg"></span>
<span className="lg:hidden text-sm"></span>
</div>
)
}
type Stage = {
id: string
title: string
summary: string
input: string
logic: string
source: string
example: string
}
// Spiegelt run_compliance_check (Phasen AF) + die Spezialagenten-Schicht.
const STAGES: Stage[] = [
{
id: 'a',
title: 'Phase A — Auflösen & Crawl',
summary: 'URLs + hochgeladene Dokumente einsammeln, fehlende Pflichtseiten automatisch finden.',
input: 'Start-URL, Dokument-Uploads, 8 Wizard-Felder (scan_context)',
logic: 'Discovery (Sitemap/Heuristik) + Fetch je Seite, Text-Extraktion pro Doc-Typ',
source: 'consent-tester /dsi-discovery, Playwright',
example: 'Findet /impressum, /datenschutz, /agb ohne manuelle Eingabe',
},
{
id: 'b',
title: 'Phase B — Profil & Dokument-Checks',
summary: 'Geschäftsprofil erkennen, jedes Dokument gegen seine Controls prüfen.',
input: 'Doc-Texte je Typ + Business-Scope',
logic: 'Regex-Runner + MC-Keyword + BGE-M3-Embedding + LLM-Verify (nur unscharf)',
source: 'doc_check_controls (DB), mc_classification.db (Embeddings)',
example: 'DSE: 267 Text-MCs, Keyword + semantischer Recall',
},
{
id: 'agents',
title: 'Spezialagenten (nebenläufig)',
summary: 'Pro Dokumenttyp ein typisierter Agent → eigener Ergebnis-Tab, gefüllt per SSE.',
input: 'Doc-Text, Scope, scan_context',
logic: 'Impressum + AGB + DSE laufen parallel (asyncio.gather), je ein AgentOutput',
source: 'api/agent_check/_agent_outputs._TOPIC_AGENTS',
example: 'AGB-Tab + DSE-Tab erscheinen, sobald ihr Agent fertig ist',
},
{
id: 'c',
title: 'Phase C — Cookie-Banner',
summary: 'Consent-Banner + gesetzte Cookies vor/nach Einwilligung live prüfen.',
input: 'Live-Seite im Browser',
logic: 'Consent-Tester-Scan: Banner, Vendors, Enforcement, Browser-Matrix',
source: 'consent-tester /scan',
example: 'Cookie vor Einwilligung gesetzt → Verstoß-Kandidat',
},
{
id: 'd',
title: 'Phase D — Vendors & Plausibilität',
summary: 'Dritt-Dienste extrahieren + Findings auf Plausibilität prüfen.',
input: 'Banner-/Seiten-Daten, Findings',
logic: 'Vendor-Extraktion (+OCR-Fallback), Plausibilitäts-Check je FAIL',
source: 'Cookie-/Vendor-Kataloge, LLM-Kaskade',
example: 'Analytics ohne Rechtsgrundlage → bestätigtes Finding',
},
{
id: 'reconcile',
title: 'Cross-Finding-Abgleich',
summary: 'Findings über Dokumente hinweg abgleichen — Doppel & Scheinverstöße auflösen.',
input: 'Alle Modul-Findings',
logic: 'Deckt ein anderes Dokument die Pflicht ab, wird das Cross-Finding unterdrückt',
source: 'cross_doc_reconcile (B-Wirings)',
example: '§36 VSBG im Impressum statt DSE → kein Doppel-Finding',
},
{
id: 'f',
title: 'Phase E/F — Bericht & Snapshot',
summary: 'Ergebnis persistieren, Snapshot für die Historie speichern.',
input: 'Konsolidiertes Ergebnis',
logic: 'Mail-Render + DB-Persist + Snapshot (Tab-Ansicht ohne Re-Crawl)',
source: 'compliance_check_snapshots',
example: 'Historie erneut öffnen, ohne die Seite neu zu crawlen',
},
]
type ModuleEngine = { name: string; mechanism: string }
const MODULES: ModuleEngine[] = [
{ name: 'Impressum', mechanism: 'Scope-Gate + Feld-Matcher (§5 DDG / §18 MStV)' },
{ name: 'AGB', mechanism: 'decision_method-Routing: Keyword → Geschäftsmodell-Gate → Embedding/Reference/LLM' },
{ name: 'DSE', mechanism: '4-Layer: Regex-Boost → Keyword → BGE-M3-Recall (0.65) → Semantic-Validator' },
{ name: 'Cookie-Banner', mechanism: 'Consent-Tester: Banner, Vendors, Enforcement, Browser-Matrix' },
]
type Pruefer = { method: string; mechanism: string; deterministic: string; example: string }
// Meta-Modell: jede Pflicht → ein Prüfertyp (decision_method). Wenige
// wiederverwendbare Prüfer statt Logik pro Control.
const PRUEFER: Pruefer[] = [
{ method: 'REGEX', mechanism: 'Kuratierte Muster / Keyword', deterministic: 'ja', example: 'Pflicht-Stichwort im Text' },
{ method: 'EMBEDDING', mechanism: 'BGE-M3 Kosinus ≥ Schwelle', deterministic: 'ja (feste Funktion)', example: '„Recht auf Berichtigung" ≈ Umschreibung' },
{ method: 'REFERENCE', mechanism: 'Link-/Verweis-Auflösung', deterministic: 'ja', example: 'Verweis auf die Datenschutzerklärung' },
{ method: 'LLM', mechanism: 'Kaskade Qwen→OVH→Claude, nur unscharfe Fälle', deterministic: 'nein (eskaliert)', example: 'Speicherdauer inhaltlich erfüllt?' },
{ method: 'BEHAVIOR', mechanism: 'Playwright: Live-Verhalten', deterministic: 'ja', example: 'Cookies vor Einwilligung gesetzt?' },
{ method: 'SCANNER', mechanism: 'Repo-/Netzwerk-/Prozess-Scan', deterministic: 'ja', example: 'Geplant: technische Nachweise' },
]
function Field({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
return (
<div>
<dt className="text-[10px] uppercase tracking-wide text-gray-400">{label}</dt>
<dd className={`text-gray-600 dark:text-gray-300 ${mono ? 'font-mono text-[11px]' : ''}`}>{value}</dd>
</div>
)
}
function StageRow({ stage, last, open, onToggle }: { stage: Stage; last: boolean; open: boolean; onToggle: () => void }) {
return (
<div>
<button
onClick={onToggle}
className={`w-full text-left rounded-lg border p-3 transition-colors ${
open
? 'border-purple-300 bg-purple-50/60 dark:border-purple-700 dark:bg-purple-900/20'
: 'border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700/50'
}`}
>
<div className="flex items-start justify-between gap-3">
<div>
<div className="text-sm font-semibold text-gray-800 dark:text-gray-200">{stage.title}</div>
<div className="text-xs text-gray-500 mt-0.5">{stage.summary}</div>
</div>
<span className="text-gray-400 text-xs shrink-0">{open ? '▲' : '▼'}</span>
</div>
{open && (
<dl className="mt-3 grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-2 text-xs">
<Field label="Input" value={stage.input} />
<Field label="Logik" value={stage.logic} />
<Field label="Datenquelle" value={stage.source} mono />
<Field label="Beispiel" value={stage.example} />
</dl>
)}
</button>
{!last && <div className="flex justify-center text-gray-300 dark:text-gray-600 text-xs leading-none py-0.5"></div>}
</div>
)
}
export function ArchitekturView() {
const [open, setOpen] = useState<string | null>('b')
return (
<div className="space-y-8">
<div>
<h2 className="text-xl font-bold text-gray-900 dark:text-gray-100">Architektur &amp; Datenfluss</h2>
<p className="text-sm text-gray-500 dark:text-gray-400 max-w-3xl mt-1">
Nachvollziehbar: <strong>woher jedes Finding stammt</strong> und <strong>wie es geprüft wird</strong>.
Die Engine ist überwiegend <strong>deterministisch</strong> (Regex + Embedding); ein LLM entscheidet nur
die unscharfen Fälle. Ergebnisse erscheinen pro Modul progressiv und werden am Ende per
Cross-Finding-Abgleich bereinigt.
</p>
</div>
<section className="space-y-2">
<h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">Datenfluss (Überblick)</h3>
<div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-900/20 p-3 overflow-x-auto">
<div className="flex flex-col lg:flex-row gap-1.5 lg:items-stretch min-w-[280px]">
<Lane label="Eingabe">
<Box title="Website + Dokumente" sub="Impressum · DSE · AGB · Cookies" accent="purple" />
<Box title="Wizard-Kontext" sub="8 Felder: Shop, Drittland, Beruf…" accent="purple" />
</Lane>
<Arrow />
<Lane label="Crawl + Text">
<Box title="Discovery + Fetch" sub="consent-tester, Playwright" />
<Box title="Doc-Text je Typ" />
</Lane>
<Arrow />
<Lane label="Engine (deterministisch)">
<div className="rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-1.5 space-y-1">
{STAGES.map((s) => (
<div key={s.id} className="text-[10px] text-gray-600 dark:text-gray-300 leading-tight">
{s.title}
</div>
))}
</div>
</Lane>
<Arrow />
<Lane label="Ausgaben">
<Box title="Findings je Modul-Tab" sub="Impressum/AGB/DSE/Cookie" accent="green" />
<Box title="Severity + Maßnahme" accent="green" />
<Box title="Snapshot + Bericht" sub="ohne Re-Crawl" accent="green" />
</Lane>
</div>
<p className="text-[10px] text-gray-400 mt-2">
Linksrechts reproduzierbar. Embedding ist semantisch UND deterministisch (feste Funktion: gleicher
Text gleicher Vektor). Das LLM läuft nur für unscharfe Fälle und eskaliert mit Selbstkonfidenz.
</p>
</div>
</section>
<section className="space-y-2">
<h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">Pipeline (Schritt für Schritt)</h3>
<div className="space-y-1">
{STAGES.map((s, i) => (
<StageRow
key={s.id}
stage={s}
last={i === STAGES.length - 1}
open={open === s.id}
onToggle={() => setOpen(open === s.id ? null : s.id)}
/>
))}
</div>
</section>
<section className="space-y-3">
<h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">Modul-Engines (live)</h3>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{MODULES.map((m) => (
<div key={m.name} className="rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-3">
<div className="flex items-baseline justify-between gap-2">
<span className="text-sm font-medium text-gray-800 dark:text-gray-200">{m.name}</span>
<span className="inline-block rounded px-1.5 py-0.5 text-[10px] font-medium bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300">
live
</span>
</div>
<p className="text-xs text-gray-500 mt-1">{m.mechanism}</p>
</div>
))}
</div>
</section>
<section className="space-y-3">
<h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">Prüfer-Matrix (Meta-Modell)</h3>
<p className="text-xs text-gray-500 max-w-3xl">
Jede Pflicht wird einem <strong>Prüfertyp</strong> zugeordnet so braucht es nicht pro Control eigene
Logik, sondern wenige wiederverwendbare Prüfer.
</p>
<div className="overflow-x-auto">
<table className="w-full text-xs">
<thead>
<tr className="text-gray-500 border-b border-gray-200 dark:border-gray-700 text-left">
<th className="py-1.5 pr-3">Prüfer</th>
<th className="py-1.5 pr-3">Mechanismus</th>
<th className="py-1.5 pr-3">Deterministisch</th>
<th className="py-1.5">Beispiel</th>
</tr>
</thead>
<tbody>
{PRUEFER.map((p) => (
<tr key={p.method} className="border-b border-gray-100 dark:border-gray-700/50 align-top">
<td className="py-1.5 pr-3">
<code className="text-[11px] bg-gray-100 dark:bg-gray-700 rounded px-1">{p.method}</code>
</td>
<td className="py-1.5 pr-3 text-gray-600 dark:text-gray-300">{p.mechanism}</td>
<td className="py-1.5 pr-3 text-gray-500">{p.deterministic}</td>
<td className="py-1.5 text-gray-500">{p.example}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
</div>
)
}
+24 -2
View File
@@ -4,10 +4,12 @@ import React, { useState } from 'react'
import { ComplianceCheckTab } from './_components/ComplianceCheckTab'
import { ComplianceFAQ } from './_components/ComplianceFAQ'
import { SnapshotHistoryList } from './_components/SnapshotHistoryList'
import { ArchitekturView } from './_components/ArchitekturView'
export default function AgentPage() {
// Nach einem abgeschlossenen Check die Historie unten neu laden.
const [historyKey, setHistoryKey] = useState(0)
const [tab, setTab] = useState<'check' | 'architektur'>('check')
return (
<div className="space-y-6 max-w-4xl">
@@ -16,11 +18,31 @@ export default function AgentPage() {
<p className="text-gray-500 mt-1">Webseiten + Dokumente auf DSGVO-Konformität prüfen.</p>
</div>
<div className="flex gap-1 border-b border-gray-200 dark:border-gray-700">
{([['check', 'Check'], ['architektur', 'Architektur']] as const).map(([id, label]) => (
<button
key={id}
onClick={() => setTab(id)}
className={`px-3 py-2 text-sm font-medium -mb-px border-b-2 transition-colors ${
tab === id
? 'border-purple-500 text-purple-600 dark:text-purple-400'
: 'border-transparent text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'
}`}
>
{label}
</button>
))}
</div>
{tab === 'check' ? (
<>
<ComplianceCheckTab onComplete={() => setHistoryKey(k => k + 1)} />
<SnapshotHistoryList refreshKey={historyKey} />
<ComplianceFAQ />
</>
) : (
<ArchitekturView />
)}
</div>
)
}
@@ -46,6 +46,28 @@ export interface CorpusOverview {
totals: { documents: number; catalog_sources: number }
}
// --- Ingested legal-corpus structure (from the vector store, via the Go SDK).
// Shows WHAT each eur-lex act consists of (articles/annexes/recitals), so the
// ingested corpus is not a black box for developers. ---
export interface LegalActStructure {
regulation_short: string
regulation_name: string
articles: number
annexes: number
recitals: number
chunks: number
}
export interface LegalCorpus {
regulations: LegalActStructure[]
totals: {
regulations: number
articles: number
annexes: number
recitals: number
}
}
// --- Korpus-Dokumente: gruppieren nach Art (Gesetz/Leitfaden/Standard/Urteil)
// + Herausgeber-Familie (DSK, EDPB, OWASP, NIST …). Deterministisch, pure. ---
interface DocCat {
+83 -3
View File
@@ -3,6 +3,7 @@ import Link from 'next/link'
import {
type UseCaseRow,
type CorpusOverview,
type LegalCorpus,
licenseTierBadgeClass,
commercialBadgeClass,
groupUseCases,
@@ -11,28 +12,46 @@ import {
const BACKEND_URL =
process.env.COMPLIANCE_BACKEND_URL || 'http://backend-compliance:8002'
// The legal-corpus structure comes from the Go SDK (it owns the vector store).
const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'
export const dynamic = 'force-dynamic'
// Fetched from the SDK and isolated in its own try/catch so a vector-store
// hiccup degrades to "no structure shown" instead of blanking the whole page.
async function fetchLegalCorpus(): Promise<LegalCorpus | null> {
try {
const res = await fetch(`${SDK_URL}/sdk/v1/rag/legal-corpus`, {
cache: 'no-store',
})
return res.ok ? await res.json() : null
} catch {
return null
}
}
async function getData(): Promise<{
useCases: UseCaseRow[]
corpus: CorpusOverview | null
legalCorpus: LegalCorpus | null
}> {
try {
const [ucRes, corpusRes] = await Promise.all([
const [ucRes, corpusRes, legalCorpus] = await Promise.all([
fetch(`${BACKEND_URL}/api/compliance/v1/controls/use-cases`, {
cache: 'no-store',
}),
fetch(`${BACKEND_URL}/api/compliance/v1/controls/corpus`, {
cache: 'no-store',
}),
fetchLegalCorpus(),
])
return {
useCases: ucRes.ok ? await ucRes.json() : [],
corpus: corpusRes.ok ? await corpusRes.json() : null,
legalCorpus,
}
} catch {
return { useCases: [], corpus: null }
return { useCases: [], corpus: null, legalCorpus: null }
}
}
@@ -46,7 +65,7 @@ function Stat({ label, value }: { label: string; value: string | number }) {
}
export default async function CoveragePage() {
const { useCases, corpus } = await getData()
const { useCases, corpus, legalCorpus } = await getData()
const groups = groupUseCases(useCases)
const totalRelevant = useCases.reduce((s, u) => s + u.atom_relevant, 0)
const totalAtoms = useCases.reduce((s, u) => s + u.atom_total, 0)
@@ -221,6 +240,67 @@ export default async function CoveragePage() {
</div>
</section>
{legalCorpus?.regulations?.length ? (
<section className="space-y-2">
<h2 className="text-lg font-semibold text-gray-900">
Ingestierter Rechtskorpus Struktur ({legalCorpus.totals.regulations}{' '}
Rechtsakte)
</h2>
<p className="text-xs text-gray-500">
Woraus jeder ingestierte eur-lex-Rechtsakt tatsächlich besteht:
Artikel (§), Anhänge, Erwägungsgründe und retrievbare Chunks direkt
aus dem Vektorspeicher, damit kein Black-Box-Korpus entsteht.
</p>
<div className="overflow-auto rounded-lg border border-gray-200">
<table className="min-w-full divide-y divide-gray-200 text-sm">
<thead className="bg-gray-50 text-left text-xs uppercase text-gray-500">
<tr>
<th className="px-4 py-2">Rechtsakt</th>
<th className="px-4 py-2 text-right">Artikel (§)</th>
<th className="px-4 py-2 text-right">Anhänge</th>
<th className="px-4 py-2 text-right">Erwägungsgründe</th>
<th className="px-4 py-2 text-right">Chunks</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 bg-white">
{legalCorpus.regulations.map((r) => (
<tr key={r.regulation_short}>
<td className="px-4 py-2 text-gray-900">
<span className="font-medium">{r.regulation_short}</span>
{r.regulation_name !== r.regulation_short ? (
<span className="ml-2 text-xs text-gray-500">
{r.regulation_name}
</span>
) : null}
</td>
<td className="px-4 py-2 text-right font-semibold">
{r.articles.toLocaleString('de-DE')}
</td>
<td className="px-4 py-2 text-right">
{r.annexes > 0 ? (
r.annexes.toLocaleString('de-DE')
) : (
<span className="text-gray-300"></span>
)}
</td>
<td className="px-4 py-2 text-right text-gray-500">
{r.recitals > 0 ? (
r.recitals.toLocaleString('de-DE')
) : (
<span className="text-gray-300"></span>
)}
</td>
<td className="px-4 py-2 text-right text-gray-500">
{r.chunks.toLocaleString('de-DE')}
</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
) : null}
{corpus?.license_catalog?.length ? (
<section className="space-y-2">
<h2 className="text-lg font-semibold text-gray-900">
+4 -5
View File
@@ -55,8 +55,7 @@ linters-settings:
rules:
- name: exported
arguments:
- checkPrivateReceivers: false
- disableStutteringCheck: true
- disableStutteringCheck
- name: error-return
- name: increment-decrement
- name: var-declaration
@@ -83,6 +82,6 @@ issues:
max-issues-per-linter: 50
max-same-issues: 5
# New code only: don't fail on pre-existing issues in files we haven't touched.
# Remove this once a clean baseline is established.
new: false
# New code only: lint lines changed vs main, so pre-existing debt doesn't fail CI.
# Needs the go-lint job to clone with a local `main` ref (see .gitea/workflows/ci.yaml).
new-from-merge-base: main
@@ -0,0 +1,24 @@
// Control-Mapping: CRA Annex I -> OWASP ASVS 5.0. Eine Zeile = ein Mapping (Schema: ControlMapping).
// Reviewt 2026-06-25 (benjamin): 7 accepted, 13 rejected. accepted = Audit-Wahrheit (Advisor nutzt acceptedOnly).
// rejected bleiben als Audit-Spur ("warum verworfen"). KEIN confidence — kuratiert = fachliche Feststellung.
// Architekturbeweis: CRA -> OWASP fuer AppSec/Auth/Crypto/Logging; Ops/Update/Attack-Surface/Integritaet -> NIST/BSI.
{"source_norm": "CRA Annex I Part I (2)(c) — Schutz vor unbefugtem Zugriff", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V6.3.1", "mapping_type": "supports", "mapping_status": "accepted", "provenance": "human_curated", "rationale": "V6 = Authentication.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "V6 = Authentication, sauberer Treffer fuer Zugriffsschutz/Authentisierung.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(c) — Schutz vor unbefugtem Zugriff", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V6.1.1", "mapping_type": "supports", "mapping_status": "accepted", "provenance": "human_curated", "rationale": "V6 = Authentication.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "V6 = Authentication, sauberer Treffer fuer Zugriffsschutz/Authentisierung.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(d) — Vertraulichkeit / Verschluesselung", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V11.2.1", "mapping_type": "supports", "mapping_status": "accepted", "provenance": "human_curated", "rationale": "V11 = Cryptography.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "Korrektur von V14: V11 = Cryptography, richtiger Bereich fuer Verschluesselung.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(d) — Vertraulichkeit / Verschluesselung", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V11.7.1", "mapping_type": "supports", "mapping_status": "accepted", "provenance": "human_curated", "rationale": "V11.7 = Key Management.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "Korrektur von V14: V11.7 = Key Management fuer Verschluesselung/Schluesselverwaltung.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(k) — Sicherheitsrelevante Ereignisse / Logging", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V16.3.3", "mapping_type": "supports", "mapping_status": "accepted", "provenance": "human_curated", "rationale": "V16 = Security Logging.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "V16 = Logging, sauberer Treffer fuer sicherheitsrelevante Ereignisse.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(k) — Sicherheitsrelevante Ereignisse / Logging", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V16.3.4", "mapping_type": "supports", "mapping_status": "accepted", "provenance": "human_curated", "rationale": "V16 = Security Logging.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "V16 = Logging, sauberer Treffer fuer sicherheitsrelevante Ereignisse.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(k) — Sicherheitsrelevante Ereignisse / Logging", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V16.1.1", "mapping_type": "supports", "mapping_status": "accepted", "provenance": "human_curated", "rationale": "V16 = Security Logging.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "V16 = Logging, sauberer Treffer fuer sicherheitsrelevante Ereignisse.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(c) — Schutz vor unbefugtem Zugriff", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V14.2.4", "mapping_type": "related", "mapping_status": "rejected", "provenance": "human_curated", "rationale": "Retriever-Kandidat.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "V14 = Config, kein Auth — verworfen.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(d) — Vertraulichkeit / Verschluesselung", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V14.2.4", "mapping_type": "related", "mapping_status": "rejected", "provenance": "human_curated", "rationale": "Retriever-Kandidat.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "V14 = Config, Crypto gehoert zu V11 — verworfen.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(d) — Vertraulichkeit / Verschluesselung", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V14.3.2", "mapping_type": "related", "mapping_status": "rejected", "provenance": "human_curated", "rationale": "Retriever-Kandidat.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "V14 = Config, Crypto gehoert zu V11 — verworfen.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(d) — Vertraulichkeit / Verschluesselung", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V14.2.3", "mapping_type": "related", "mapping_status": "rejected", "provenance": "human_curated", "rationale": "Retriever-Kandidat.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "V14 = Config, Crypto gehoert zu V11 — verworfen.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(e) — Integritaet", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V14.2.4", "mapping_type": "related", "mapping_status": "rejected", "provenance": "human_curated", "rationale": "Retriever-Kandidat.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "OWASP ASVS ist hier nicht der passende Zielstandard. Mapping ueber NIST/BSI erforderlich.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(e) — Integritaet", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V1.2.4", "mapping_type": "related", "mapping_status": "rejected", "provenance": "human_curated", "rationale": "Retriever-Kandidat.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "OWASP ASVS ist hier nicht der passende Zielstandard. Mapping ueber NIST/BSI erforderlich.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(e) — Integritaet", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V6.1.1", "mapping_type": "related", "mapping_status": "rejected", "provenance": "human_curated", "rationale": "Retriever-Kandidat.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "OWASP ASVS ist hier nicht der passende Zielstandard. Mapping ueber NIST/BSI erforderlich.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(l) — Sichere Updates", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V14.2.4", "mapping_type": "related", "mapping_status": "rejected", "provenance": "human_curated", "rationale": "Retriever-Kandidat.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "OWASP ASVS ist hier nicht der passende Zielstandard. Mapping ueber NIST/BSI erforderlich.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(l) — Sichere Updates", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V2.4.1", "mapping_type": "related", "mapping_status": "rejected", "provenance": "human_curated", "rationale": "Retriever-Kandidat.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "OWASP ASVS ist hier nicht der passende Zielstandard. Mapping ueber NIST/BSI erforderlich.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(l) — Sichere Updates", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V6.1.1", "mapping_type": "related", "mapping_status": "rejected", "provenance": "human_curated", "rationale": "Retriever-Kandidat.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "OWASP ASVS ist hier nicht der passende Zielstandard. Mapping ueber NIST/BSI erforderlich.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(i) — Angriffsflaeche minimieren", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V6.1.1", "mapping_type": "related", "mapping_status": "rejected", "provenance": "human_curated", "rationale": "Retriever-Kandidat.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "OWASP ASVS ist hier nicht der passende Zielstandard. Mapping ueber NIST/BSI erforderlich.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(i) — Angriffsflaeche minimieren", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V15.3.3", "mapping_type": "related", "mapping_status": "rejected", "provenance": "human_curated", "rationale": "Retriever-Kandidat.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "OWASP ASVS ist hier nicht der passende Zielstandard. Mapping ueber NIST/BSI erforderlich.", "version": "2026-06-25"}
{"source_norm": "CRA Annex I Part I (2)(i) — Angriffsflaeche minimieren", "source_role": "operational_requirement", "target_framework": "OWASP ASVS", "target_control": "V8.2.4", "mapping_type": "related", "mapping_status": "rejected", "provenance": "human_curated", "rationale": "Retriever-Kandidat.", "reviewed_by": "benjamin", "review_date": "2026-06-25", "review_reason": "OWASP ASVS ist hier nicht der passende Zielstandard. Mapping ueber NIST/BSI erforderlich.", "version": "2026-06-25"}
@@ -0,0 +1,16 @@
// Evidence-Requirements je OWASP-ASVS-Control (Schema: EvidenceRequirement). Eine Zeile = eine geforderte Evidenz.
// Autoriert/kuratiert (nicht Retriever). Der Advisor kann eine CRA-Anforderung erst dann als erfuellt melden,
// wenn die required Evidenzen der gemappten, accepted Controls vorliegen + frisch genug sind.
// Stand 2026-06-25, Basis: die 7 accepted CRA->OWASP-Mappings (Auth V6, Crypto V11, Logging V16).
{"framework": "OWASP ASVS", "control": "V6.3.1", "evidence_type": "config_export", "evidence_source": "github", "freshness_requirement": "per_release", "required": true, "rationale": "IAM-/Zugriffskonfiguration als Nachweis der Authentisierungs-Anforderung.", "version": "2026-06-25"}
{"framework": "OWASP ASVS", "control": "V6.3.1", "evidence_type": "test_report", "evidence_source": "ci", "freshness_requirement": "per_release", "required": true, "rationale": "Automatisierter Zugriffstest (CI) belegt funktionierende Zugriffskontrolle.", "version": "2026-06-25"}
{"framework": "OWASP ASVS", "control": "V6.3.1", "evidence_type": "pentest", "evidence_source": "manual_upload", "freshness_requirement": "annually", "required": false, "rationale": "Jaehrlicher PenTest der Authentisierung — vertieft, aber nicht Pflicht je Release.", "version": "2026-06-25"}
{"framework": "OWASP ASVS", "control": "V6.1.1", "evidence_type": "config_export", "evidence_source": "github", "freshness_requirement": "per_release", "required": true, "rationale": "Rollenmodell/Auth-Architektur als Nachweis.", "version": "2026-06-25"}
{"framework": "OWASP ASVS", "control": "V11.2.1", "evidence_type": "config_export", "evidence_source": "github", "freshness_requirement": "per_release", "required": true, "rationale": "Krypto-Konfiguration (zugelassene Algorithmen) als Nachweis der Verschluesselung.", "version": "2026-06-25"}
{"framework": "OWASP ASVS", "control": "V11.2.1", "evidence_type": "sbom", "evidence_source": "ci", "freshness_requirement": "per_release", "required": true, "rationale": "SBOM weist die eingesetzten Krypto-Bibliotheken/-Versionen nach.", "version": "2026-06-25"}
{"framework": "OWASP ASVS", "control": "V11.7.1", "evidence_type": "policy", "evidence_source": "manual_upload", "freshness_requirement": "annually", "required": true, "rationale": "Key-Management-Policy (Rotation, Aufbewahrung) als organisatorischer Nachweis.", "version": "2026-06-25"}
{"framework": "OWASP ASVS", "control": "V11.7.1", "evidence_type": "config_export", "evidence_source": "github", "freshness_requirement": "per_release", "required": true, "rationale": "Konfiguration der Schluesselverwaltung als technischer Nachweis.", "version": "2026-06-25"}
{"framework": "OWASP ASVS", "control": "V16.3.3", "evidence_type": "audit_log", "evidence_source": "ci", "freshness_requirement": "continuous", "required": true, "rationale": "Security-Audit-Logs belegen, dass sicherheitsrelevante Ereignisse protokolliert werden.", "version": "2026-06-25"}
{"framework": "OWASP ASVS", "control": "V16.3.3", "evidence_type": "config_export", "evidence_source": "github", "freshness_requirement": "per_release", "required": true, "rationale": "Logging-Konfiguration als Nachweis der erfassten Ereignisarten.", "version": "2026-06-25"}
{"framework": "OWASP ASVS", "control": "V16.3.4", "evidence_type": "audit_log", "evidence_source": "ci", "freshness_requirement": "continuous", "required": true, "rationale": "Security-Audit-Logs.", "version": "2026-06-25"}
{"framework": "OWASP ASVS", "control": "V16.1.1", "evidence_type": "config_export", "evidence_source": "github", "freshness_requirement": "per_release", "required": true, "rationale": "Logging-Architektur-Konfiguration als Nachweis.", "version": "2026-06-25"}
@@ -211,6 +211,13 @@ func (h *IACEHandler) InitializeProject(c *gin.Context) {
}
for _, cat := range mp.HazardCats {
// Native cyber/AI categories (frontend groups I+J) belong to the
// CRA module, not the traditional CE (ISO 12100) hazard log.
// Enforced centrally here so it holds for EVERY project.
if isCyberSecurityCategory(cat) {
fmt.Printf("CYBER-SKIP: cat=%s pattern=%s — routed to CRA module\n", cat, mp.PatternID)
continue
}
maxForCat := categoryHazardCap(cat, len(comps))
if catCount[cat] >= maxForCat {
continue
@@ -291,6 +298,10 @@ func (h *IACEHandler) InitializeProject(c *gin.Context) {
if len(mp.SuggestedMeasureIDs) > 0 {
hazardPatternMeasures[hz.ID] = mp.SuggestedMeasureIDs
}
// E1: one hazard per pattern — keep only the primary (first
// eligible) category; a secondary category would be the same
// scenario+zone under a different label (cross-category duplicate).
break
}
}
}
@@ -0,0 +1,45 @@
package handlers
// Safety/Security separation for the IACE hazard log.
//
// The traditional CE risk assessment (Maschinenrichtlinie / EN ISO 12100) and
// the cybersecurity assessment (Cyber Resilience Act) are two distinct steps.
// IACE owns the traditional, physical + functional-safety hazards; the CRA
// module (/sdk/iace/{id}/cra) owns the native cyber/AI topics and re-examines
// which safety functions a cyber attack can re-open (see iace-safety-bridge).
//
// The split is by the NATURE of the hazard, not by the component: a control
// fault, bus failure or botched update is FUNCTIONAL safety (random/systematic
// fault) and stays in CE — independent of whether the controller is a bought-in
// CE-marked PLC or the manufacturer's own embedded control. Only the security
// PROPERTIES against malicious actors (access control, firmware/update
// integrity, SBOM, vulnerability handling, default passwords) are CRA.
//
// Functional-safety control categories (software_control, software_fault,
// safety_function_failure, configuration_error, communication_failure,
// update_failure, sensor_fault, …) therefore intentionally STAY in IACE — they
// are the safety functions whose loss the CRA bridge re-examines.
//
// Enforced centrally in InitializeProject so it holds for EVERY project.
var nativeCyberSecurityCategories = map[string]bool{
// I. Cyber / Netzwerk — security against malicious actors
"unauthorized_access": true,
"firmware_corruption": true,
"cyber_resilience": true,
"logging_audit_failure": true,
"cyber_network": true,
"sensor_spoofing": true,
// J. KI-spezifisch
"ai_specific": true,
"ai_misclassification": true,
"false_classification": true,
"model_drift": true,
"data_poisoning": true,
"unintended_bias": true,
}
// isCyberSecurityCategory reports whether a hazard category is a native cyber/AI
// topic that belongs to the CRA module rather than the traditional CE hazard log.
func isCyberSecurityCategory(category string) bool {
return nativeCyberSecurityCategories[category]
}
@@ -0,0 +1,37 @@
package handlers
import "testing"
func TestIsCyberSecurityCategory_RoutedToCRA(t *testing.T) {
cyber := []string{
"unauthorized_access", "firmware_corruption", "cyber_resilience",
"logging_audit_failure", "cyber_network", "sensor_spoofing",
"ai_specific", "ai_misclassification", "false_classification",
"model_drift", "data_poisoning", "unintended_bias",
}
for _, c := range cyber {
if !isCyberSecurityCategory(c) {
t.Errorf("category %q must be routed to the CRA module, not the traditional IACE log", c)
}
}
}
func TestIsCyberSecurityCategory_StaysInIACE(t *testing.T) {
// Physical + functional-safety categories must remain in the traditional CE
// hazard log. communication_failure (bus failure -> loss of control) and
// update_failure (botched update -> lost safety function) are FUNCTIONAL
// faults, not attacks, so they stay too.
keep := []string{
"mechanical_hazard", "electrical_hazard", "thermal_hazard",
"pneumatic_hydraulic", "noise_vibration", "ergonomic_hazard",
"material_environmental", "chemical_risk", "fire_explosion",
"software_control", "software_fault", "safety_function_failure",
"configuration_error", "sensor_fault", "hmi_error",
"communication_failure", "update_failure",
}
for _, c := range keep {
if isCyberSecurityCategory(c) {
t.Errorf("category %q must stay in the traditional IACE log, not be routed to CRA", c)
}
}
}
@@ -78,6 +78,7 @@ func (h *RAGHandlers) Search(c *gin.Context) {
"query": req.Query,
"results": results,
"count": len(results),
"assessment": ucca.Assess(results),
})
}
@@ -206,3 +207,32 @@ func (h *RAGHandlers) HandleScrollChunks(c *gin.Context) {
"total": len(chunks),
})
}
// LegalCorpusStructure returns the composition (distinct articles, annexes,
// recitals + chunk count) of every ingested eur-lex legal act, so the coverage
// page can show WHAT was ingested instead of just the act name.
// GET /sdk/v1/rag/legal-corpus
func (h *RAGHandlers) LegalCorpusStructure(c *gin.Context) {
acts, err := h.ragClient.CorpusStructure(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to aggregate legal corpus: " + err.Error()})
return
}
arts, anns, recs := 0, 0, 0
for _, a := range acts {
arts += a.Articles
anns += a.Annexes
recs += a.Recitals
}
c.JSON(http.StatusOK, gin.H{
"regulations": acts,
"totals": gin.H{
"regulations": len(acts),
"articles": arts,
"annexes": anns,
"recitals": recs,
},
})
}
+1
View File
@@ -161,6 +161,7 @@ func registerRAGRoutes(v1 *gin.RouterGroup, h *handlers.RAGHandlers) {
ragRoutes.GET("/corpus-status", h.CorpusStatus)
ragRoutes.GET("/corpus-versions/:collection", h.CorpusVersionHistory)
ragRoutes.GET("/scroll", h.HandleScrollChunks)
ragRoutes.GET("/legal-corpus", h.LegalCorpusStructure)
}
}
@@ -0,0 +1,182 @@
package iace
import (
"encoding/json"
"os"
"path/filepath"
"sort"
"testing"
)
// GT #3 — commercial UNDERCOUNTER dishwasher (Winterhalter UC-M). Self-assessed
// ground truth: we can judge what a dishwasher is. The test runs the narrative
// through the SAME chain as production (ParseNarrative -> engine -> relevance
// filter + cyber-skip), so keyword/gating fixes are measured on the hazard set
// the user actually sees — not the raw pattern flood.
// Condensed UC-M limits_form narrative. Deliberately includes "Cool-Ausfuehrung"
// and "Filter" so the known false components (Kuehlaggregat, Absauganlage) are
// reproduced and visible in the baseline.
const warewashingNarrative = `Gewerbliche Untertisch-Geschirrspuelmaschine fuer Gastronomie-Kueche, ` +
`vernetzt ueber LAN und WLAN (Connected Wash Internetportal). Heisswasser-Boiler mit ` +
`Nachspueltemperatur ca. 85 Grad C, Tank mit Hygiene-Tankheizkoerper. Spuelpumpe 150-200 l/min ` +
`mit rotierenden Spuelfeldern und Spuelarmen, Ablaufpumpe. Eingebautes Dosiergeraet fuer Reiniger ` +
`und Klarspueler (aetzende Konzentrate). 4-fach-Laugenfiltration mit Filter. Doppelwandige Tuer ` +
`mit Sicherheitsschalter und Rastposition (Thermostopp). Elektromotor (Drehstrom) 400 V. ` +
`Touch-Steuerung (SPS) mit Bedienfeld und HMI, USB-Schnittstelle fuer Softwareupdates, ` +
`PIN-geschuetzter Servicetechniker-Fernzugriff. Cool-Ausfuehrung mit kalter Nachspuelung. ` +
`Untertischmontage. Eingreifen in die Spuelkammer moeglich. Aerosole und Daempfe der ` +
`Reinigungschemie gelangen in die Atemzone. Manuelles Be- und Entladen der Spuelkoerbe von Hand. ` +
`Reinigung und Wartung durch Servicetechniker. Branche Lebensmittel und Getraenke. ` +
`Siebe und scharfe Blechkanten in der Spuelkammer. Boiler kann bei Wassermangel trockenlaufen. ` +
`Frequenzumrichter und Elektronik mit Restspannung nach dem Abschalten. Wartung nur im ` +
`freigeschalteten Zustand; Gefahr des unerwarteten Wiederanlaufs. Frischwasseranschluss mit ` +
`Rueckflussverhinderer gegen Ruecksaugen in das Trinkwassernetz. Stehwasser im Boiler ` +
`(Hygiene/Legionellen). Standsicherheit bei Untertischmontage.`
// warewashingCyberCategories mirrors handlers.nativeCyberSecurityCategories —
// native cyber/AI hazards are routed to the CRA module, not the CE hazard log.
var warewashingCyberCategories = map[string]bool{
"unauthorized_access": true, "firmware_corruption": true, "cyber_resilience": true,
"logging_audit_failure": true, "cyber_network": true, "sensor_spoofing": true,
"ai_specific": true, "ai_misclassification": true, "false_classification": true,
"model_drift": true, "data_poisoning": true, "unintended_bias": true,
}
// warewashingEngineOutput runs the production chain and returns the filtered
// hazards/mitigations the user would see for the UC-M.
func warewashingEngineOutput() ([]Hazard, []Mitigation, int) {
res := ParseNarrative(warewashingNarrative, "Gewerbliche Untertisch-Geschirrspuelmaschine (vernetzt)")
var compIDs, compNames []string
for _, c := range res.Components {
if c.Negated {
continue
}
compIDs = append(compIDs, c.LibraryID)
compNames = append(compNames, c.NameDE)
}
var energyIDs []string
for _, e := range res.EnergySources {
energyIDs = append(energyIDs, e.SourceID)
}
lifecycles := append([]string{}, res.LifecyclePhases...)
lifecycles = append(lifecycles, "normal_operation", "maintenance", "cleaning", "setup", "fault_clearing")
input := MatchInput{
ComponentLibraryIDs: compIDs,
EnergySourceIDs: energyIDs,
LifecyclePhases: lifecycles,
CustomTags: res.CustomTags,
OperationalStates: append(res.OperationalStates, "normal_operation", "cleaning", "maintenance"),
HumanRoles: res.Roles,
MachineTypes: []string{"food_processing", "Gewerbliche Untertisch-Geschirrspuelmaschine (vernetzt)"},
}
out := NewPatternEngine().Match(input)
var kept []PatternMatch
for _, pm := range out.MatchedPatterns {
if !IsPatternRelevant(pm, warewashingNarrative, compNames) {
continue
}
allCyber := len(pm.HazardCats) > 0
for _, c := range pm.HazardCats {
if !warewashingCyberCategories[c] {
allCyber = false
}
}
if allCyber {
continue
}
kept = append(kept, pm)
}
filtered := *out
filtered.MatchedPatterns = kept
hazards, mitigations := patternsToHazardsAndMitigations(&filtered)
return hazards, mitigations, len(kept)
}
func TestWarewashing_GTCoverage(t *testing.T) {
gtPath := filepath.Join("testdata", "ground_truth_warewashing.json")
raw, err := os.ReadFile(gtPath)
if err != nil {
t.Fatalf("read GT: %v", err)
}
var gt GroundTruth
if err := json.Unmarshal(raw, &gt); err != nil {
t.Fatalf("parse GT: %v", err)
}
{
res := ParseNarrative(warewashingNarrative, "Gewerbliche Untertisch-Geschirrspuelmaschine (vernetzt)")
var cn []string
for _, c := range res.Components {
if !c.Negated {
cn = append(cn, c.NameDE)
}
}
t.Logf("Parsed components: %v", cn)
}
hazards, mitigations, nPatterns := warewashingEngineOutput()
t.Logf("Engine: %d patterns kept (relevance+cyber filter) -> %d hazards", nPatterns, len(hazards))
result := CompareBenchmark(&gt, hazards, mitigations)
precision := 0.0
if result.TotalEngine > 0 {
precision = float64(len(result.MatchedPairs)) / float64(result.TotalEngine)
}
t.Logf("=== Warewashing-GT (GT #3) Baseline ===")
t.Logf("Recall (Coverage): %.1f%% (%d/%d matched, %d missing)",
result.CoverageScore*100, len(result.MatchedPairs), result.TotalGT, len(result.MissingFromEngine))
t.Logf("Precision: %.1f%% (%d engine hazards, %d extra)",
precision*100, result.TotalEngine, len(result.ExtraInEngine))
if len(result.MissingFromEngine) > 0 {
t.Logf("--- MISSING (recall gaps) ---")
for _, m := range result.MissingFromEngine {
t.Logf(" MISS %s: %s", m.Nr, abbrev(m.HazardType, 60))
}
}
// Measure completeness: which generated hazards have NO protective measure?
t.Logf("--- Measure completeness ---")
t.Logf("Measure coverage (GT-matched): %.0f%%", result.MeasureCoverage*100)
withMeas := make(map[string]bool)
for _, m := range mitigations {
withMeas[m.HazardID.String()] = true
}
noMeasure := 0
for _, h := range hazards {
if !withMeas[h.ID.String()] {
noMeasure++
n := h.Name
if n == "" {
n = h.Scenario
}
t.Logf(" NO-MEASURE: [%s] %s", h.Category, abbrev(n, 60))
}
}
t.Logf("Hazards without any measure: %d/%d", noMeasure, len(hazards))
if len(result.ExtraInEngine) > 0 {
t.Logf("--- EXTRA (false positives / precision loss) ---")
names := make([]string, 0, len(result.ExtraInEngine))
for _, e := range result.ExtraInEngine {
n := e.Name
if n == "" {
n = e.Scenario
}
names = append(names, "["+e.Category+"] "+n)
}
sort.Strings(names)
for _, n := range names {
t.Logf(" EXTRA %s", abbrev(n, 85))
}
}
// Loose smoke floor for the baseline — fixes should push recall up, not down.
if result.CoverageScore < 0.4 {
t.Errorf("warewashing recall below 40%% floor: %.1f%%", result.CoverageScore*100)
}
}
@@ -62,6 +62,13 @@ type HazardPattern struct {
// "hazard" = source only, "hazardous_situation" = person exposed, "harm" = injury.
// Empty = default (hazardous_situation).
GeneratedHazardType string `json:"generated_hazard_type,omitempty"`
// GuardableByEnclosure marks a contact/entanglement hazard that an interlocked
// enclosure removes during normal operation. When the project emits the
// "interlocked_enclosure" tag, such a pattern is re-scoped to maintenance/
// cleaning (guard open) and does NOT fire as a normal-operation hazard.
// Generic EN ISO 14120 logic — surfaced by the warewashing GT (the spray
// arm rotates behind the interlocked door).
GuardableByEnclosure bool `json:"guardable_by_enclosure,omitempty"`
// RequiredFailureModes restricts this pattern to fire only when at least one
// of the listed failure modes is relevant (by ComponentType match against project components).
// Empty/nil = fires regardless of failure modes (backwards compatible).
@@ -37,6 +37,7 @@ func GetDGUVExtendedPatterns() []HazardPattern {
},
{
ID: "HP096", NameDE: "Reibung/Abrieb durch rotierende Oberflaechen", NameEN: "Friction/abrasion by rotating surfaces",
GuardableByEnclosure: true,
RequiredComponentTags: []string{"rotating_part"},
RequiredEnergyTags: []string{},
GeneratedHazardCats: []string{"mechanical_hazard"},
@@ -88,6 +89,7 @@ func GetDGUVExtendedPatterns() []HazardPattern {
},
{
ID: "HP101", NameDE: "Aufwickeln von Kleidung/Haaren", NameEN: "Winding up of clothing/hair",
GuardableByEnclosure: true,
RequiredComponentTags: []string{"rotating_part"},
RequiredEnergyTags: []string{"rotational"},
GeneratedHazardCats: []string{"mechanical_hazard"},
@@ -0,0 +1,178 @@
package iace
// GetWarewashingPatterns returns hazard patterns for commercial warewashing
// machines (gewerbliche Geschirrspuelmaschinen / Untertisch-, Hauben-, Korb-
// und Bandspuelmaschinen). These capture the machine-specific hazards a
// Fachmann immediately expects but that the generic library did not cover:
// hot-water/steam scalding on door opening, hot surfaces, hot ware, corrosive
// detergent/rinse-aid contact, door pinch and wet-floor slipping.
//
// Every pattern is gated by the capability tag "dom_warewashing" (emitted only
// by warewashing narrative keywords in keyword_dictionary.go), so none of these
// leak into unrelated machine classes.
//
// HP range: HP2200-HP2206. ISO 12100 Annex B section identifiers only (facts);
// product standard EN 60335-2-58 (commercial dishwashing machines).
func GetWarewashingPatterns() []HazardPattern {
return []HazardPattern{
{
ID: "HP2200", NameDE: "Verbruehung durch Heisswasser/Dampf beim Oeffnen der Tuer", NameEN: "Scalding by hot water/steam when opening the door",
RequiredComponentTags: []string{"dom_warewashing", "steam_emission"},
GeneratedHazardCats: []string{"thermal_hazard"},
SuggestedMeasureIDs: []string{"M2200", "M2201", "M2202", "M2208"},
Priority: 94,
ApplicableLifecycles: []string{"normal_operation", "cleaning"},
ScenarioDE: "Beim Oeffnen der Tuer waehrend oder unmittelbar nach dem Spuelgang tritt ein Schwall aus heissem Wasser und Wrasen (Dampf) aus der Spuelkammer aus und trifft Gesicht, Haende und Arme des Bedieners.",
TriggerDE: "Tuer wird vor Programmende oder bei noch vorhandenem Restdampf geoeffnet; Tuerverriegelung fehlt oder ist ueberbrueckt; Nachspueltemperatur ca. 85 Grad C.",
HarmDE: "Verbruehung 1.-2. Grades an Gesicht, Haenden und Unterarmen; Augenreizung durch heissen Dampf.",
AffectedDE: "Bedienpersonal (Spuelkraft)",
ZoneDE: "Tuer- und Beschickungsoeffnung der Spuelkammer",
ISO12100Section: "6.2.4",
DefaultSeverity: 3, DefaultExposure: 4,
},
{
ID: "HP2201", NameDE: "Verbrennung an heissen Oberflaechen (Boiler/Tank/Spuelkammer)", NameEN: "Burn on hot surfaces (boiler/tank/wash chamber)",
RequiredComponentTags: []string{"dom_warewashing", "high_temperature"},
GeneratedHazardCats: []string{"thermal_hazard"},
SuggestedMeasureIDs: []string{"M2202", "M055", "M2208"},
Priority: 90,
ApplicableLifecycles: []string{"cleaning", "maintenance"},
ScenarioDE: "Beruehrung heisser Oberflaechen von Boiler, Tankheizkoerper oder Spuelkammerwaenden bei Reinigung, Entkalkung oder Wartung fuehrt zu Kontaktverbrennungen.",
TriggerDE: "Reinigung/Entkalkung ohne Abkuehlzeit; Eingriff in die Spuelkammer bei betriebswarmem Geraet.",
HarmDE: "Kontaktverbrennung an Haenden und Unterarmen.",
AffectedDE: "Reinigungspersonal, Wartungspersonal",
ZoneDE: "Boiler, Tankheizkoerper, Spuelkammerwaende",
ISO12100Section: "6.2.4",
DefaultSeverity: 2, DefaultExposure: 3,
},
{
ID: "HP2202", NameDE: "Verbrennung an heissem Spuelgut beim Entladen", NameEN: "Burn on hot ware when unloading",
RequiredComponentTags: []string{"dom_warewashing", "hot_water"},
GeneratedHazardCats: []string{"thermal_hazard"},
SuggestedMeasureIDs: []string{"M2202", "M055", "M2208"},
Priority: 86,
ApplicableLifecycles: []string{"normal_operation"},
ScenarioDE: "Geschirr, Glaeser und Bestecke sind nach dem Spuelgang durch die Heisswasser-Nachspuelung sehr heiss; beim Entladen kommt es zu Verbrennungen.",
TriggerDE: "Sofortiges Entnehmen des Spuelguts nach Programmende ohne Abkuehl-/Trocknungszeit.",
HarmDE: "Verbrennung an Haenden/Fingern beim Greifen heisser Teile.",
AffectedDE: "Bedienpersonal (Spuelkraft)",
ZoneDE: "Spuelkammer, Entnahmebereich/Korb",
ISO12100Section: "6.2.4",
DefaultSeverity: 2, DefaultExposure: 3,
},
{
ID: "HP2203", NameDE: "Chemische Veraetzung (Haut/Augen) durch Reiniger-/Klarspueler-Konzentrat", NameEN: "Chemical burn (skin/eyes) from detergent/rinse-aid concentrate",
RequiredComponentTags: []string{"dom_warewashing", "corrosive_chemical"},
GeneratedHazardCats: []string{"chemical_risk"},
SuggestedMeasureIDs: []string{"M2203", "M2204", "M2208"},
Priority: 92,
ApplicableLifecycles: []string{"normal_operation", "maintenance"},
ScenarioDE: "Direkter Kontakt mit dem aetzenden (alkalischen) Reiniger- bzw. Klarspueler-Konzentrat beim Nachfuellen, Sauglanzenwechsel oder bei Leckage fuehrt zu Veraetzungen von Haut und Augen.",
TriggerDE: "Gebinde-/Sauglanzenwechsel ohne Schutzausruestung; Umfuellen von Konzentrat; undichte Dosierleitung.",
HarmDE: "Veraetzung von Haut und Augen (alkalische Verletzung), bleibende Augenschaeden moeglich.",
AffectedDE: "Bedienpersonal, Reinigungspersonal beim Chemikalien-Handling",
ZoneDE: "Dosiergeraet, Reiniger-/Klarspueler-Gebinde, Sauglanzen",
ISO12100Section: "6.2.4",
DefaultSeverity: 3, DefaultExposure: 3,
ClarificationQuestionsDE: []string{
"Liegt fuer alle eingesetzten Reiniger/Klarspueler/Entkalker ein aktuelles Sicherheitsdatenblatt (SDB) am Geraet vor?",
"Ist ein geschlossenes Dosiersystem mit Sauglanzen vorhanden, sodass kein Umfuellen noetig ist?",
},
},
{
ID: "HP2204", NameDE: "Reizung/Veraetzung der Atemwege durch Reinigungs-Aerosole/Daempfe", NameEN: "Respiratory irritation from cleaning aerosols/vapours",
RequiredComponentTags: []string{"dom_warewashing", "corrosive_chemical"},
GeneratedHazardCats: []string{"chemical_risk"},
SuggestedMeasureIDs: []string{"M2205", "M2203", "M2204"},
Priority: 82,
ApplicableLifecycles: []string{"normal_operation", "maintenance"},
ScenarioDE: "Aerosole und Daempfe der Reinigungschemie (insbesondere beim Oeffnen kurz nach dem Spuelgang oder bei der Entkalkung mit Saeure) gelangen in die Atemzone und reizen Atemwege und Schleimhaeute.",
TriggerDE: "Oeffnen bei laufender/heisser Chemie; Entkalkung mit Saeure; unzureichende Lueftung des Aufstellbereichs.",
HarmDE: "Reizung von Atemwegen, Augen und Schleimhaeuten; bei Saeure-/Laugen-Vermischung gefaehrliche Gase.",
AffectedDE: "Bedienpersonal, Reinigungspersonal",
ZoneDE: "Atemzone vor der Spuelkammer, Aufstellbereich",
ISO12100Section: "6.2.4",
DefaultSeverity: 2, DefaultExposure: 2,
ClarificationQuestionsDE: []string{
"Ist der Aufstellbereich ausreichend be-/entlueftet (Kuechenlueftung)?",
"Wird in der BA vor dem Vermischen von Reiniger und Entkalker/Saeure gewarnt?",
},
},
{
ID: "HP2205", NameDE: "Quetschen der Finger an der Tuer/Haube", NameEN: "Finger crushing at the door/hood",
RequiredComponentTags: []string{"dom_warewashing", "access_door"},
GeneratedHazardCats: []string{"mechanical_hazard"},
SuggestedMeasureIDs: []string{"M2206", "M003", "M2208"},
Priority: 78,
ApplicableLifecycles: []string{"normal_operation"},
ScenarioDE: "Beim Schliessen der Tuer bzw. Absenken der Haube werden Finger zwischen Tuer/Haube und Gehaeuse gequetscht.",
TriggerDE: "Greifen in den Schliessbereich beim Schliessen; hohe Schliesskraft der Haube; scharfe Kanten.",
HarmDE: "Quetschung und Prellung der Finger.",
AffectedDE: "Bedienpersonal (Spuelkraft)",
ZoneDE: "Tuer-/Haubenkante, Schliessbereich",
ISO12100Section: "6.2.3",
DefaultSeverity: 1, DefaultExposure: 3,
},
{
ID: "HP2206", NameDE: "Ausrutschen auf nassem Boden (Wasseraustritt/Leckage)", NameEN: "Slipping on wet floor (water leakage)",
RequiredComponentTags: []string{"dom_warewashing"},
GeneratedHazardCats: []string{"mechanical_hazard"},
SuggestedMeasureIDs: []string{"M2207", "M538", "M2208"},
Priority: 76,
ApplicableLifecycles: []string{"normal_operation", "cleaning", "maintenance"},
ScenarioDE: "Aus der Spuelmaschine austretendes Wasser (Beschickung, Tuer oeffnen, Leckage, Tankwasserwechsel) macht den Boden im Aufstellbereich rutschig; der Bediener rutscht aus.",
TriggerDE: "Wasseraustritt beim Oeffnen/Beschicken; undichter Ablauf; fehlender Bodenablauf.",
HarmDE: "Sturz mit Prellungen, Knochenbruechen oder Kopfaufprall.",
AffectedDE: "Bedienpersonal, Reinigungspersonal",
ZoneDE: "Aufstell- und Bedienbereich der Spuelmaschine",
ISO12100Section: "6.3.5.6",
DefaultSeverity: 2, DefaultExposure: 3,
},
{
ID: "HP2207", NameDE: "Rueckfluss / Kontamination des Trinkwassers", NameEN: "Backflow / potable-water contamination",
RequiredComponentTags: []string{"dom_warewashing", "backflow_risk"},
GeneratedHazardCats: []string{"material_environmental"},
SuggestedMeasureIDs: []string{"M2209"},
Priority: 84,
ApplicableLifecycles: []string{"normal_operation"},
ScenarioDE: "Verschmutztes Spuel- oder Chemiewasser wird ueber den Frischwasseranschluss in das Trinkwassernetz zurueckgesaugt und kontaminiert es (Ruecksaugen bei Unterdruck im Netz).",
TriggerDE: "Fehlender oder defekter Rueckflussverhinderer/Systemtrenner; Unterdruck im Trinkwassernetz; kein freier Auslauf.",
HarmDE: "Gesundheitsgefaehrdung Dritter durch kontaminiertes Trinkwasser (Chemie, Keime).",
AffectedDE: "Verbraucher am selben Trinkwassernetz, Betreiber",
ZoneDE: "Frischwasseranschluss, Wasserzulauf",
ISO12100Section: "6.2.4",
DefaultSeverity: 3, DefaultExposure: 2,
},
{
ID: "HP2208", NameDE: "Schnittverletzung an scharfen Kanten/Sieben", NameEN: "Cut injury on sharp edges/screens",
RequiredComponentTags: []string{"dom_warewashing", "sharp_edge"},
GeneratedHazardCats: []string{"mechanical_hazard"},
SuggestedMeasureIDs: []string{"M003"},
Priority: 74,
ApplicableLifecycles: []string{"cleaning", "maintenance"},
ScenarioDE: "Schneiden an scharfen Blechkanten, Sieben oder dem Ablaufpumpen-Laufrad beim Reinigen oder Eingreifen in die Spuelkammer.",
TriggerDE: "Entnehmen/Reinigen der Siebe; Eingreifen an scharfen Kanten ohne Schutzhandschuhe.",
HarmDE: "Schnittwunden an Haenden und Fingern.",
AffectedDE: "Reinigungspersonal, Bedienpersonal",
ZoneDE: "Zugaengliche Kanten, Siebe, Spuelkammer, Ablaufpumpe",
ISO12100Section: "6.2.2.1",
DefaultSeverity: 1, DefaultExposure: 3,
},
{
ID: "HP2209", NameDE: "Unerwarteter Wiederanlauf bei Wartung/Reinigung", NameEN: "Unexpected restart during maintenance/cleaning",
RequiredComponentTags: []string{"dom_warewashing", "programmable"},
RequiredLifecycles: []string{"maintenance", "cleaning", "fault_clearing"},
GeneratedHazardCats: []string{"safety_function_failure"},
SuggestedMeasureIDs: []string{"M042"},
Priority: 80,
ApplicableLifecycles: []string{"maintenance", "cleaning"},
ScenarioDE: "Waehrend Wartung oder Reinigung laeuft die Maschine durch fehlende Freischaltung (LOTO) oder automatischen Wiederanlauf unerwartet an (Pumpe, Spuelgang).",
TriggerDE: "Kein Freischalten/Sichern gegen Wiedereinschalten; automatischer Wiederanlauf nach Netzunterbrechung.",
HarmDE: "Verbruehung, Quetschen oder elektrischer Schlag durch unerwartet anlaufende Maschine.",
AffectedDE: "Wartungspersonal, Reinigungspersonal",
ZoneDE: "Gesamte Maschine, Pumpe, Antriebe",
ISO12100Section: "6.2.11.4",
DefaultSeverity: 3, DefaultExposure: 2,
},
}
}
@@ -0,0 +1,112 @@
package iace
import "testing"
// firedSet runs the engine for the given custom tags and returns the set of
// fired pattern IDs.
func firedSet(customTags []string) map[string]bool {
engine := NewPatternEngine()
out := engine.Match(MatchInput{CustomTags: customTags})
fired := make(map[string]bool, len(out.MatchedPatterns))
for _, m := range out.MatchedPatterns {
fired[m.PatternID] = true
}
return fired
}
// A warewashing narrative emits these capability + functional tags.
var warewashingTags = []string{
"dom_warewashing", "steam_emission", "hot_water", "high_temperature",
"corrosive_chemical", "access_door", "rotating_part",
}
func TestWarewashing_PatternsFireForDishwasher(t *testing.T) {
fired := firedSet(warewashingTags)
want := []string{"HP2200", "HP2201", "HP2202", "HP2203", "HP2204", "HP2205", "HP2206"}
for _, id := range want {
if !fired[id] {
t.Errorf("expected warewashing pattern %s to fire for a dishwasher, but it did not", id)
}
}
}
func TestWarewashing_PatternsDoNotLeakIntoOtherMachines(t *testing.T) {
// A machine with thermal + electrical + chemical capability but NOT a
// dishwasher must never produce warewashing hazards (dom_warewashing gate).
fired := firedSet([]string{"high_temperature", "electrical_part", "chemical_risk", "rotating_part", "moving_part"})
for _, id := range []string{"HP2200", "HP2201", "HP2202", "HP2203", "HP2204", "HP2205", "HP2206"} {
if fired[id] {
t.Errorf("warewashing pattern %s leaked into a non-dishwasher machine", id)
}
}
}
func TestWarewashing_WeldingAndGlueDoNotLeakIntoDishwasher(t *testing.T) {
// The gate-term additions must stop the welding/flame/glue burn patterns
// from firing for a dishwasher (they previously leaked via high_temperature
// / electrical_part). dom_welding/dom_flame/dom_glue are absent here.
fired := firedSet(warewashingTags)
leak := map[string]string{
"HP530": "Lichtbogen-Verbrennung (Schweissen)",
"HP532": "Schweissrauch",
"HP533": "Brand durch Schweissfunken (Schweissen)",
}
for id, name := range leak {
if fired[id] {
t.Errorf("cross-domain pattern %s (%s) leaked into a dishwasher", id, name)
}
}
}
func TestWarewashing_MeasureIDsExist(t *testing.T) {
lib := GetProtectiveMeasureLibrary()
have := make(map[string]bool, len(lib))
for _, m := range lib {
have[m.ID] = true
}
for _, p := range GetWarewashingPatterns() {
for _, mid := range p.SuggestedMeasureIDs {
if !have[mid] {
t.Errorf("pattern %s references measure %s which is not in the library", p.ID, mid)
}
}
}
}
func TestWarewashing_NarrativeEmitsTags(t *testing.T) {
// Closes the loop: a realistic dishwasher description must emit the tags
// the warewashing patterns gate on (otherwise the patterns are dead).
narrative := "Gewerbliche Untertisch-Geschirrspuelmaschine mit Heisswasser-Boiler " +
"und Nachspuelung ca. 85 Grad C, Spuelpumpe mit rotierenden Spuelfeldern, " +
"Dampf-/Wrasenabgabe beim Oeffnen, Reiniger und Klarspueler ueber Dosiergeraet, " +
"Tuer mit Sicherheitsschalter, Eingreifen in die Spuelkammer."
res := ParseNarrative(narrative, "Gewerbliche Geschirrspuelmaschine")
got := make(map[string]bool, len(res.CustomTags))
for _, tag := range res.CustomTags {
got[tag] = true
}
for _, want := range []string{"dom_warewashing", "steam_emission", "hot_water", "corrosive_chemical", "access_door", "rotating_part"} {
if !got[want] {
t.Errorf("narrative did not emit expected tag %q (got %v)", want, res.CustomTags)
}
}
// And it must NOT emit any welding/flame/glue domain that would re-open leaks.
for _, bad := range []string{"dom_welding", "dom_flame", "dom_glue"} {
if got[bad] {
t.Errorf("dishwasher narrative unexpectedly emitted cross-domain tag %q", bad)
}
}
}
func TestWarewashing_NewMeasuresPresent(t *testing.T) {
lib := GetProtectiveMeasureLibrary()
have := make(map[string]bool, len(lib))
for _, m := range lib {
have[m.ID] = true
}
for _, mid := range []string{"M2200", "M2201", "M2202", "M2203", "M2204", "M2205", "M2206", "M2207", "M2208"} {
if !have[mid] {
t.Errorf("expected warewashing measure %s to be registered in the library", mid)
}
}
}
@@ -88,6 +88,28 @@ func GetKeywordDictionary() []KeywordEntry {
{Keywords: []string{"folienwickler", "wickelmaschine", "konfektioniermaschine", "folienverpackung", "wellpappe"}, ExtraTags: []string{"dom_converting"}},
{Keywords: []string{"bergbau", "untertage", "tunnelbau", "off-grid"}, ExtraTags: []string{"dom_remote"}},
{Keywords: []string{"asbest", "asbestsanierung", "asbestexposition"}, ExtraTags: []string{"dom_asbestos"}},
{Keywords: []string{"gasbrenner", "brennerbetrieb", "offene flamme", "flammhaert", "abflammen", "flammrichten"}, ExtraTags: []string{"dom_flame"}},
{Keywords: []string{"heissleim", "heissleimanlage", "schmelzkleber", "schmelzklebstoff", "klebstoffschmelzer", "leimwerk"}, ExtraTags: []string{"dom_glue"}},
// ── Gewerbliche Spuelmaschine / Warewashing ──────────────────────
// dom_warewashing gates the warewashing-specific patterns
// (hazard_patterns_warewashing.go) so they never leak into other
// machine classes. The functional tags (hot_water, steam_emission,
// corrosive_chemical, access_door) are the within-domain triggers.
{Keywords: []string{"spuelmaschine", "geschirrspuelmaschine", "geschirrspueler", "haubenspuelmaschine", "untertischspuelmaschine", "korbspuelmaschine", "bandspuelmaschine", "glaeserspuelmaschine", "bistrospuelmaschine", "warewashing", "dishwasher"}, ExtraTags: []string{"dom_warewashing"}},
{Keywords: []string{"heisswasser", "nachspuelung", "nachspueltemperatur", "spuelgang", "spuelzyklus", "thermostopp", "thermostop"}, ExtraTags: []string{"hot_water", "high_temperature"}},
{Keywords: []string{"dampf", "wrasen", "schwaden", "brueden"}, ExtraTags: []string{"steam_emission", "high_temperature"}},
{Keywords: []string{"boiler", "spuelboiler", "nachspuelboiler", "tankheiz", "boilerheiz"}, ComponentIDs: []string{"C094"}, ExtraTags: []string{"heating_element", "high_temperature"}},
{Keywords: []string{"reiniger", "klarspueler", "spuelmittel", "reinigungsmittel", "reinigerkonzentrat", "spuelchemie", "dosiergeraet", "dosierpumpe", "sauglanze", "entkalker"}, ExtraTags: []string{"corrosive_chemical"}},
// Spuelarm/Spuelfeld emit only the rotating_part capability tag. They are
// NOT mapped to a library component — C004 is a "Drehtisch" (rotary table)
// and that mislabels the spray arm. Keyword->component must be semantically
// honest (generic hygiene; surfaced by the warewashing GT).
{Keywords: []string{"spuelarm", "spuelfeld", "wascharm", "spruehfeld"}, ExtraTags: []string{"rotating_part"}},
{Keywords: []string{"spuelkammer", "spueltuer", "geraetetuer", "haubentuer", "klapptuer"}, ExtraTags: []string{"access_door"}},
// Frischwasseranschluss an das Trinkwassernetz -> Rueckfluss/Ruecksaug-Risiko (EN 1717).
{Keywords: []string{"rueckfluss", "rueckflussverhinderer", "ruecksaug", "trinkwasser", "frischwasseranschluss", "systemtrenner"}, ExtraTags: []string{"backflow_risk"}},
{Keywords: []string{"scharfe kante", "scharfkant", "blechkante", "scharfe blechkante", "sieb", "siebe"}, ExtraTags: []string{"sharp_edge"}},
// Ghost-Closure (Emit-Seite): macht die 34 toten Required-Tags
// emittierbar, jeweils NUR via domaenenspezifische Keywords -> die 120
// Ghost-Patterns feuern wieder, aber nur fuer ihre echte Maschine (kein
@@ -182,6 +204,12 @@ func GetKeywordDictionary() []KeywordEntry {
{Keywords: []string{"lichtgitter", "lichtvorhang", "light curtain", "light grid"}, ComponentIDs: []string{"C102"}, ExtraTags: []string{"safety_device"}},
{Keywords: []string{"sicherheitsschalter", "safety switch"}, ComponentIDs: []string{"C104"}, ExtraTags: []string{"safety_device", "interlocked"}},
{Keywords: []string{"zuhaltung", "guard locking", "interlock"}, ComponentIDs: []string{"C105"}, ExtraTags: []string{"safety_device", "interlocked"}},
// interlocked_enclosure signals that moving parts are inaccessible behind a
// guard that is monitored/locked — feeds the GuardableByEnclosure re-scoping
// (contact/entanglement becomes a maintenance/guard-open hazard, not a
// normal-operation one). Emitted only by explicit "interlocked door/guard"
// vocabulary so it does not trigger for machines with exposed motion.
{Keywords: []string{"tuer mit sicherheitsschalter", "verriegelte tuer", "verriegelte haube", "verriegelte einhausung", "sicherheitstuer", "tuerverriegelung", "haube mit sicherheitsschalter"}, ExtraTags: []string{"interlocked_enclosure"}},
{Keywords: []string{"zweihand", "two-hand", "zweihandschaltung"}, ComponentIDs: []string{"C106"}, ExtraTags: []string{"safety_device", "two_hand_control_required"}},
{Keywords: []string{"schaltmatte", "safety mat"}, ComponentIDs: []string{"C108"}, ExtraTags: []string{"safety_device"}},
{Keywords: []string{"seilzug", "pull wire"}, ComponentIDs: []string{"C109"}, ExtraTags: []string{"safety_device"}},
@@ -194,7 +222,9 @@ func GetKeywordDictionary() []KeywordEntry {
// ── Absaugung / Umwelt ──────────────────────────────────────────
{Keywords: []string{"absaug", "extraction", "abscheider"}, ComponentIDs: []string{"C124"}, ExtraTags: []string{"noise_source"}},
{Keywords: []string{"filter", "filteranlage"}, ComponentIDs: []string{"C124"}, ExtraTags: []string{}},
// "filteranlage" only — bare "filter" falsely mapped any filter (Laugen-,
// Wasser-, Oel-, Netzfilter) to the oil-mist extractor C124.
{Keywords: []string{"filteranlage"}, ComponentIDs: []string{"C124"}, ExtraTags: []string{}},
// ── IT / Netzwerk ───────────────────────────────────────────────
{Keywords: []string{"switch", "netzwerk"}, ComponentIDs: []string{"C111"}, ExtraTags: []string{"networked"}},
@@ -223,7 +253,10 @@ func GetKeywordDictionary() []KeywordEntry {
{Keywords: []string{"biege", "bend"}, ComponentIDs: []string{"C019"}, ExtraTags: []string{"high_force"}},
{Keywords: []string{"stanz", "stamp", "punch"}, ComponentIDs: []string{"C018"}, ExtraTags: []string{"high_force", "crush_point"}},
{Keywords: []string{"heiz", "heater", "heating"}, ComponentIDs: []string{"C094"}, EnergyIDs: []string{"EN06"}, ExtraTags: []string{"high_temperature"}},
{Keywords: []string{"kuehl", "cool"}, ComponentIDs: []string{"C095"}, ExtraTags: []string{}},
// Cooling UNIT only — not the bare adjectives "kuehl"/"cool", which falsely
// matched product-variant names ("Cool-Ausfuehrung") and outputs ("kuehle
// Glaeser"). Keyword->component must name an actual component.
{Keywords: []string{"kuehlaggregat", "kuehlanlage", "kuehler", "kaeltemaschine", "chiller", "rueckkuehl"}, ComponentIDs: []string{"C095"}, ExtraTags: []string{}},
{Keywords: []string{"luefter", "fan", "geblaese"}, ComponentIDs: []string{"C096"}, ExtraTags: []string{"rotating_part", "noise_source"}},
{Keywords: []string{"spannvorrichtung", "fixture", "clamp"}, ComponentIDs: []string{"C100"}, ExtraTags: []string{"clamping_part"}},
@@ -22,6 +22,7 @@ func GetProtectiveMeasureLibrary() []ProtectiveMeasureEntry {
all = append(all, getGTBremseMeasures()...) // GT-Bremse-Coverage-Gaps (M483-M522)
all = append(all, GetCRAMeasures()...) // CRA / DIN EN 40000-1-2 cyber-resilience (M540-M548)
all = append(all, getLiftEndstopMeasures()...) // Lift/hoist endstop (M600-M604) — bridges OSHA MD library
all = append(all, getWarewashingMeasures()...) // Commercial dishwasher (M2200-M2208) — scald/chemical/door/slip
return all
}
@@ -0,0 +1,75 @@
package iace
// getWarewashingMeasures returns protective measures for commercial warewashing
// machines (gewerbliche Geschirrspuelmaschinen): hot-water/steam scalding,
// hot surfaces, corrosive cleaning chemicals, door pinch and wet-floor slip.
// They complement the generic thermal/mechanical/material measures with the
// machine-specific controls a Fachmann expects for this product class.
//
// M-ID range: M2200-M2208. Norm identifiers only (facts) — no norm text is
// reproduced (DIN/Beuth license). Lead standard: EN 60335-2-58 (safety of
// commercial electric dishwashing machines).
func getWarewashingMeasures() []ProtectiveMeasureEntry {
return []ProtectiveMeasureEntry{
{ID: "M2200", ReductionType: "design", SubType: "interlock",
Name: "Tuer-/Haubenverriegelung beendet Spuelgang vor dem Oeffnen",
Description: "Die Tuer bzw. Haube ist so mit der Steuerung verriegelt, dass beim Oeffnen Spuelpumpe und Nachspuelung sofort abschalten und ein Oeffnen erst nach Programmende (bzw. nach Abbau des Restdampfs) freigegeben wird. Verhindert den Schwall aus Heisswasser/Wrasen und den Kontakt mit noch rotierenden Spuelfeldern.",
HazardCategory: "thermal",
Examples: []string{"Tuerkontaktschalter schaltet Pumpe + Heizung beim Oeffnen ab", "Rastposition mit Restdampf-Verzoegerung vor Freigabe"},
NormReferences: []string{"EN 60335-2-58", "EN ISO 12100 — Inhaerent sichere Konstruktion"}},
{ID: "M2201", ReductionType: "design", SubType: "thermal",
Name: "Wrasen-/Dampfreduzierung (Kondensations- / Waermerueckgewinnungssystem)",
Description: "Der beim Oeffnen austretende Wrasen wird durch ein Kondensations- bzw. Waermerueckgewinnungssystem reduziert, sodass beim Entnehmen kein gefaehrlicher Dampfschwall entsteht. Senkt zugleich die Restwaerme- und Feuchtebelastung am Arbeitsplatz.",
HazardCategory: "thermal",
Examples: []string{"Umluft-Waermerueckgewinnung reduziert austretenden Wrasen", "Kondensationshaube ueber der Spuelkammer"},
NormReferences: []string{"EN 60335-2-58"}},
{ID: "M2202", ReductionType: "protection", SubType: "monitoring",
Name: "Thermostop / Temperaturueberwachung von Boiler und Tank",
Description: "Boiler- und Tanktemperatur werden ueberwacht; ein Thermostop gibt den naechsten Schritt erst frei, wenn die Solltemperatur erreicht ist, und begrenzt die maximale Nachspueltemperatur. Schuetzt vor Verbruehung durch unkontrolliert heisses Nachspuelwasser.",
HazardCategory: "thermal",
Examples: []string{"Temperatursensor in Boiler und Tank mit Abschaltgrenze", "Thermostop-Funktion im Spuelprogramm"},
NormReferences: []string{"EN 60335-2-58", "EN ISO 13732-1"}},
{ID: "M2203", ReductionType: "design", SubType: "containment",
Name: "Geschlossenes Dosiersystem mit Sauglanzen und Niveauueberwachung",
Description: "Reiniger und Klarspueler werden ausschliesslich ueber ein geschlossenes Dosiersystem mit Sauglanzen aus dem Originalgebinde gefoerdert (Niveau-Ueberwachung statt Umfuellen). Direkter Haut-/Augenkontakt mit dem aetzenden Konzentrat beim Nachfuellen wird konstruktiv vermieden.",
HazardCategory: "material_environmental",
Examples: []string{"Sauglanze mit Leermeldung im Reiniger-Kanister", "Kein Umfuellen — Gebindewechsel ohne offenen Chemiekontakt"},
NormReferences: []string{"EN 60335-2-58", "Verordnung (EG) Nr. 1272/2008 (CLP/GHS)"}},
{ID: "M2204", ReductionType: "information", SubType: "ppe",
Name: "PSA (Augen-/Hautschutz) + GHS-Kennzeichnung und Sicherheitsdatenblatt",
Description: "Fuer Handhabung, Gebindewechsel und Entkalkung werden Augen- und Handschutz vorgeschrieben; Reiniger/Klarspueler/Entkalker sind GHS-gekennzeichnet und das Sicherheitsdatenblatt liegt am Geraet vor. Stellt die sichere Handhabung der aetzenden Konzentrate sicher.",
HazardCategory: "material_environmental",
Examples: []string{"Schutzbrille + chemikalienbestaendige Handschuhe bei Gebindewechsel", "GHS-Etikett und SDB im Chemikalienschrank am Geraet"},
NormReferences: []string{"Verordnung (EG) Nr. 1272/2008 (CLP/GHS)", "TRGS 500"}},
{ID: "M2205", ReductionType: "protection", SubType: "ventilation",
Name: "Be-/Entlueftung bzw. geschlossene Haube gegen Chemie-Aerosole und Wrasen",
Description: "Der Aufstellbereich ist ausreichend be- und entlueftet bzw. die Spuelkammer bleibt waehrend des Programms geschlossen, sodass Reinigungs-Aerosole und heisser Wrasen nicht in die Atemzone des Bedieners gelangen.",
HazardCategory: "material_environmental",
Examples: []string{"Kuechenlueftung ueber dem Spuelbereich", "Programmstart nur bei geschlossener Haube"},
NormReferences: []string{"EN 60335-2-58", "TRGS 500"}},
{ID: "M2206", ReductionType: "design", SubType: "geometry",
Name: "Tuerkanten mit geringer Schliesskraft / Einklemmschutz",
Description: "Die Tuer-/Haubenmechanik ist so gestaltet (gefuehrte Bewegung, begrenzte Schliesskraft, abgerundete Kanten), dass beim Schliessen keine Finger gequetscht werden.",
HazardCategory: "mechanical",
Examples: []string{"Gefuehrte Haube mit gedaempfter Schliessbewegung", "Abgerundete Tuerkanten ohne Quetschspalt"},
NormReferences: []string{"EN 60335-2-58", "EN ISO 12100 — Geometrie und Anordnung"}},
{ID: "M2207", ReductionType: "design", SubType: "environment",
Name: "Rutschhemmender Bodenbelag + Ablauf/Leckagewanne im Aufstellbereich",
Description: "Im Aufstell- und Bedienbereich der Spuelmaschine sorgen rutschhemmender Bodenbelag und ein definierter Ablauf bzw. eine Leckagewanne dafuer, dass austretendes Wasser nicht zur Sturzgefahr wird.",
HazardCategory: "mechanical",
Examples: []string{"Rutschhemmender Industrieboden (Bewertungsgruppe R11/R12)", "Bodenablauf bzw. Leckagewanne unter dem Geraet"},
NormReferences: []string{"ASR A1.5/1,2", "DGUV Regel 108-003"}},
{ID: "M2208", ReductionType: "information", SubType: "signage",
Name: "Warnhinweis heisser Dampf/Heisswasser — Tuer erst nach Programmende oeffnen",
Description: "Am Geraet und in der Betriebsanleitung wird vor heissem Dampf und Heisswasser gewarnt und das Oeffnen der Tuer erst nach Programmende mit vorsichtigem Anheben vorgeschrieben. Sprachneutrale Piktogramme ergaenzen den Hinweis.",
HazardCategory: "general",
Examples: []string{"Warnpiktogramm 'Heisser Dampf' an der Tuer", "BA-Hinweis 'Tuer nach Programmende langsam oeffnen'"},
NormReferences: []string{"ISO 7010", "EN 60335-2-58"}},
{ID: "M2209", ReductionType: "design", SubType: "containment",
Name: "Rueckflussverhinderer / Systemtrenner nach EN 1717",
Description: "Der Frischwasseranschluss ist durch einen Rueckflussverhinderer bzw. Systemtrenner der passenden Schutzklasse oder durch einen freien Auslauf gegen Ruecksaugen verschmutzten Wassers in das Trinkwassernetz gesichert.",
HazardCategory: "material_environmental",
Examples: []string{"Systemtrenner Typ BA nach EN 1717", "Freier Auslauf Typ AB ueber dem hoechsten Wasserstand"},
NormReferences: []string{"EN 1717", "EN 60335-2-58"}},
}
}
@@ -46,6 +46,20 @@ var domainGateTerms = map[string]string{
"widerstandsschweiss": "dom_welding", "lichtbogenschweiss": "dom_welding",
"schutzgasschweiss": "dom_welding", "punktschweiss": "dom_welding",
"schweisselektrod": "dom_welding", "elektrodenspalt": "dom_welding",
// Schweissen — Oberflaechenformen die bisher ungegatet leakten (z.B. in
// thermische Hazards einer Spuelmaschine ueber high_temperature/electrical_part)
"schweissarbeitsplatz": "dom_welding", "schweissfunke": "dom_welding",
"schweisshelm": "dom_welding", "schweisserschutz": "dom_welding",
"lichtbogenzone": "dom_welding", "lichtbogen-verbrennung": "dom_welding",
"schweissrauch": "dom_welding", "schweissgeraet": "dom_welding",
"schweisszone": "dom_welding", "schweissbrenner": "dom_welding",
"schweissspritzer": "dom_welding", "schweissstrom": "dom_welding",
// Offene Flamme / Brenner (Gasbrenner, Flammhaerten, Abflammen)
"offene flamme": "dom_flame", "brennerbereich": "dom_flame",
"flammenzone": "dom_flame", "gasbrenner": "dom_flame",
// Heissleim / Schmelzkleber
"heissleimanlage": "dom_glue", "klebstoffschmelzer": "dom_glue",
"heisskleber": "dom_glue", "schmelzkleber": "dom_glue",
// Solar / PV
"pv-modul": "dom_solar", "photovoltaik": "dom_solar", "pv-anlage": "dom_solar",
"dc-steckverbindung": "dom_solar", "solarmodul": "dom_solar",
@@ -53,6 +67,7 @@ var domainGateTerms = map[string]string{
"gondel": "dom_wind", "rotorblatt": "dom_wind", "windenergieanlage": "dom_wind",
// CNC / Zerspanung
"drehmaschine": "dom_cnc", "fraesmaschine": "dom_cnc",
"spanende": "dom_cnc", "spanenden bearbeitung": "dom_cnc",
// Landwirtschaft
"maehdrescher": "dom_agri", "ballenpresse": "dom_agri", "feldhaecksler": "dom_agri",
// Roll-/Fahrtreppe
@@ -0,0 +1,44 @@
package iace
// Interlocked-enclosure model (EN ISO 14120 / EN ISO 12100).
//
// A contact or entanglement hazard from a moving part is removed during NORMAL
// operation when that part is inaccessible behind an interlocked guard. The
// hazard then remains only when the guard is open — maintenance, cleaning or
// fault clearing. Patterns flagged GuardableByEnclosure express this; a project
// emits the "interlocked_enclosure" tag (interlocked door/hood, see
// keyword_dictionary.go) to declare the guard.
//
// This is GENERIC: it applies to every enclosed machine (dishwasher spray arm,
// enclosed mixer, centrifuge ...) and is regression-safe — machines that do not
// emit interlocked_enclosure are unaffected.
const (
phaseMaintenance = "maintenance"
phaseCleaning = "cleaning"
phaseFaultClearing = "fault_clearing"
)
// suppressedByEnclosure reports whether a guardable hazard must be dropped: the
// part is enclosed AND none of the project's lifecycle phases opens the guard.
func suppressedByEnclosure(p HazardPattern, tagSet map[string]bool, lifecycles []string) bool {
if !p.GuardableByEnclosure || !tagSet["interlocked_enclosure"] || len(lifecycles) == 0 {
return false
}
for _, lc := range lifecycles {
if lc == phaseMaintenance || lc == phaseCleaning || lc == phaseFaultClearing {
return false // guard is open in some phase → hazard remains there
}
}
return true
}
// guardedLifecycles re-scopes a guardable hazard to the guard-open phases when
// the project declares an interlocked enclosure, so it is documented as a
// maintenance/cleaning hazard rather than a normal-operation one.
func guardedLifecycles(p HazardPattern, tagSet map[string]bool) []string {
if p.GuardableByEnclosure && tagSet["interlocked_enclosure"] {
return []string{phaseMaintenance, phaseCleaning}
}
return p.ApplicableLifecycles
}
@@ -223,7 +223,7 @@ func (e *PatternEngine) Match(input MatchInput) *MatchOutput {
HumanRoles: p.HumanRoles,
GeneratedHazardType: p.GeneratedHazardType,
MatchedFailureModes: matchedFMs,
ApplicableLifecycles: p.ApplicableLifecycles,
ApplicableLifecycles: guardedLifecycles(p, tagSet),
SuggestedMeasureIDs: p.SuggestedMeasureIDs,
ClarificationQuestionsDE: p.ClarificationQuestionsDE,
ISO12100Section: p.ISO12100Section,
@@ -411,6 +411,11 @@ func patternMatches(p HazardPattern, tagSet map[string]bool, input MatchInput) b
}
}
// Interlocked-enclosure gate (guardable contact/entanglement). See pattern_enclosure.go.
if suppressedByEnclosure(p, tagSet, input.LifecyclePhases) {
return false
}
return true
}
@@ -44,6 +44,7 @@ func collectAllPatterns() []HazardPattern {
patterns = append(patterns, GetCRAPatterns()...) // HP1910-HP1918 CRA / DIN EN 40000-1-2 cyber-resilience spur
patterns = append(patterns, GetSecondaryHarmDemoPatterns()...) // HP2000-HP2001 secondary harm chain demos (Cola splitter, Pharma)
patterns = append(patterns, GetLiftEndstopPatterns()...) // HP2100-HP2102 lift body-part crush at endstops
patterns = append(patterns, GetWarewashingPatterns()...) // HP2200-HP2206 commercial dishwasher (scald/chemical/door/slip)
patterns = applyMachineTypeOverrides(patterns) // Fill MachineTypes on legacy patterns to prevent drift
patterns = applyDomainGates(patterns) // Capability-domain gate: stop domain-specific patterns leaking cross-machine
return patterns
@@ -0,0 +1,383 @@
{
"machine_name": "Gewerbliche Untertisch-Geschirrspuelmaschine (Winterhalter UC-M)",
"machine_description": "Untertisch-Gewerbespuelmaschine, vernetzt (Connected Wash), Heisswasser-Boiler, Spuelpumpe mit rotierenden Spuelfeldern, Tuer mit Sicherheitsschalter, Reiniger-/Klarspueler-Dosierung.",
"source": "Selbstbewertung GT #3 (Fachmann-Erwartung, EN 60335-2-58 + EN ISO 12100)",
"version": "1.0",
"entries": [
{
"nr": "1.1",
"hazard_group": "Thermische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Verbrühung durch Heißwasser und Dampf",
"hazard_cause": "Beim Öffnen der Tür während oder kurz nach dem Spülgang tritt heißes Wasser und Wrasen (Dampf) aus der Spülkammer aus und trifft Gesicht, Hände und Arme",
"lifecycle_phases": ["Betrieb", "Reinigung"],
"component_zone": "Tür und Beschickungsöffnung der Spülkammer",
"risk_in": {"f": 4, "w": 3, "p": 2, "s": 3, "r": 27},
"measures": ["Türverriegelung beendet Spülgang vor dem Öffnen", "Wrasen-/Dampfreduzierung", "Warnhinweis heißer Dampf"],
"measure_type": "KM",
"risk_out": {"f": 2, "w": 1, "p": 1, "s": 2, "r": 8},
"norm_references": ["EN 60335-2-58"],
"sufficient": true
},
{
"nr": "1.2",
"hazard_group": "Thermische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Verbrennung an heißen Oberflächen",
"hazard_cause": "Berührung heißer Oberflächen von Boiler, Tankheizkörper oder Spülkammerwänden bei Reinigung, Entkalkung oder Wartung",
"lifecycle_phases": ["Reinigung", "Instandhaltung"],
"component_zone": "Boiler, Tankheizkörper, Spülkammerwände",
"risk_in": {"f": 3, "w": 2, "p": 2, "s": 2, "r": 14},
"measures": ["Temperaturbegrenzung zugänglicher Oberflächen", "Warnhinweis heiße Oberfläche"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 2, "r": 6},
"norm_references": ["EN ISO 13732-1"],
"sufficient": true
},
{
"nr": "1.3",
"hazard_group": "Thermische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Verbrennung an heißem Spülgut",
"hazard_cause": "Geschirr und Gläser sind nach der Heißwasser-Nachspülung sehr heiß, beim Entladen kommt es zu Verbrennungen an den Händen",
"lifecycle_phases": ["Betrieb"],
"component_zone": "Spülkammer, Entnahmebereich, Korb",
"risk_in": {"f": 3, "w": 3, "p": 2, "s": 2, "r": 16},
"measures": ["Abkühl-/Trocknungszeit", "Warnhinweis heißes Spülgut"],
"measure_type": "BI",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 2, "r": 6},
"norm_references": ["EN 60335-2-58"],
"sufficient": true
},
{
"nr": "2.1",
"hazard_group": "Gefährdungen durch Materialien und Substanzen",
"hazard_group_applicable": true,
"hazard_type": "Verätzung von Haut und Augen durch Reiniger-/Klarspüler-Konzentrat",
"hazard_cause": "Direkter Kontakt mit dem ätzenden Reiniger- bzw. Klarspüler-Konzentrat beim Nachfüllen, Sauglanzenwechsel oder bei Leckage des Dosiergeräts",
"lifecycle_phases": ["Betrieb", "Instandhaltung"],
"component_zone": "Dosiergerät, Reiniger- und Klarspüler-Gebinde, Sauglanzen",
"risk_in": {"f": 3, "w": 3, "p": 2, "s": 3, "r": 24},
"measures": ["Geschlossenes Dosiersystem mit Sauglanzen", "PSA Augen-/Hautschutz", "GHS-Kennzeichnung und Sicherheitsdatenblatt"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 3, "r": 9},
"norm_references": ["Verordnung (EG) Nr. 1272/2008", "TRGS 500"],
"sufficient": true
},
{
"nr": "2.2",
"hazard_group": "Gefährdungen durch Materialien und Substanzen",
"hazard_group_applicable": true,
"hazard_type": "Reizung der Atemwege durch Reinigungs-Aerosole und Dämpfe",
"hazard_cause": "Einatmen von Aerosolen und Dämpfen der Reinigungschemie beim Öffnen kurz nach dem Spülgang oder bei der Entkalkung mit Säure",
"lifecycle_phases": ["Betrieb", "Instandhaltung"],
"component_zone": "Atemzone vor der Spülkammer, Aufstellbereich",
"risk_in": {"f": 2, "w": 2, "p": 2, "s": 2, "r": 12},
"measures": ["Be-/Entlüftung", "geschlossene Haube", "Warnung vor Vermischen von Reiniger und Säure"],
"measure_type": "BI",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 2, "r": 6},
"norm_references": ["TRGS 500"],
"sufficient": true
},
{
"nr": "3.1",
"hazard_group": "Elektrische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Elektrischer Schlag in Nassumgebung",
"hazard_cause": "Berührung spannungsführender Teile bei unzureichendem IP-Schutz, defekten Kabeldurchführungen oder Feuchtigkeit im Steuerungsgehäuse",
"lifecycle_phases": ["Betrieb", "Reinigung", "Instandhaltung"],
"component_zone": "Steuerungsgehäuse, Kabelübergänge, Antriebsgehäuse",
"risk_in": {"f": 3, "w": 2, "p": 3, "s": 4, "r": 32},
"measures": ["IP-Schutz gegen eindringendes Wasser", "Fehlerstrom-Schutzeinrichtung (RCD)"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 4, "r": 12},
"norm_references": ["IEC 60335-1"],
"sufficient": true
},
{
"nr": "3.2",
"hazard_group": "Elektrische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Kurzschluss und Brand bei Reinigung am Schaltschrank",
"hazard_cause": "Reinigung ohne vorherige Freischaltung oder mit Hochdruckreiniger am elektrisch aktiven Schaltschrank führt zu Kurzschluss und Brand",
"lifecycle_phases": ["Reinigung", "Instandhaltung"],
"component_zone": "Schaltschrank, elektrisch aktive Komponenten",
"risk_in": {"f": 2, "w": 2, "p": 2, "s": 3, "r": 18},
"measures": ["Netztrenneinrichtung", "Warnhinweis Reinigung nur spannungsfrei, kein Hochdruckreiniger"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 3, "r": 9},
"norm_references": ["IEC 60204-1"],
"sufficient": true
},
{
"nr": "3.3",
"hazard_group": "Elektrische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Motorüberlast mit Überhitzung",
"hazard_cause": "Blockierter oder überlasteter Pumpenmotor überhitzt, Wicklungsbrand und Rauchentwicklung",
"lifecycle_phases": ["Betrieb"],
"component_zone": "Motorgehäuse, Umgebung",
"risk_in": {"f": 2, "w": 2, "p": 2, "s": 2, "r": 12},
"measures": ["Überstromschutz", "Motorschutzschalter"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 2, "r": 6},
"norm_references": ["IEC 60204-1"],
"sufficient": true
},
{
"nr": "4.1",
"hazard_group": "Mechanische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Ausrutschen auf nassem Boden",
"hazard_cause": "Aus der Spülmaschine austretendes Wasser durch Leckage oder beim Öffnen macht den Boden im Aufstellbereich rutschig, Person rutscht aus und stürzt",
"lifecycle_phases": ["Betrieb", "Reinigung", "Instandhaltung"],
"component_zone": "Aufstell- und Bedienbereich der Spülmaschine",
"risk_in": {"f": 3, "w": 3, "p": 2, "s": 2, "r": 16},
"measures": ["Rutschhemmender Bodenbelag", "Bodenablauf bzw. Leckagewanne"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 2, "r": 6},
"norm_references": ["ASR A1.5/1,2"],
"sufficient": true
},
{
"nr": "4.2",
"hazard_group": "Mechanische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Quetschen der Finger an der Tür/Haube",
"hazard_cause": "Beim Schließen der Tür bzw. Absenken der Haube werden Finger zwischen Tür/Haube und Gehäuse gequetscht",
"lifecycle_phases": ["Betrieb"],
"component_zone": "Tür- und Haubenkante, Schließbereich",
"risk_in": {"f": 3, "w": 2, "p": 2, "s": 1, "r": 7},
"measures": ["Geringe Schließkraft, Einklemmschutz", "Abgerundete Türkanten"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 1, "r": 3},
"norm_references": ["EN ISO 12100"],
"sufficient": true
},
{
"nr": "4.3",
"hazard_group": "Mechanische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Kontakt mit rotierendem Spülarm bei geöffneter Tür",
"hazard_cause": "Eingreifen in die Spülkammer bei noch nachlaufendem rotierendem Spülarm/Spülfeld nach dem Öffnen der Tür",
"lifecycle_phases": ["Betrieb", "Reinigung"],
"component_zone": "Spülkammer, Spülarm und Spülfeld",
"risk_in": {"f": 2, "w": 2, "p": 2, "s": 1, "r": 6},
"measures": ["Türverriegelung stoppt Spülarm beim Öffnen"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 1, "r": 3},
"norm_references": ["EN ISO 12100"],
"sufficient": true
},
{
"nr": "5.1",
"hazard_group": "Ergonomische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Belastung des Bewegungsapparats durch wiederholte Be- und Entladung",
"hazard_cause": "Wiederholtes Heben und Bücken beim manuellen Be- und Entladen der Spülkörbe am Untertischgerät",
"lifecycle_phases": ["Betrieb"],
"component_zone": "Be- und Entladestelle, Spülkorb",
"risk_in": {"f": 4, "w": 3, "p": 2, "s": 1, "r": 9},
"measures": ["Ergonomische Arbeitshöhe", "Be-/Entladung auf günstiger Greifhöhe"],
"measure_type": "KM",
"risk_out": {"f": 2, "w": 1, "p": 1, "s": 1, "r": 4},
"norm_references": ["EN 1005-2"],
"sufficient": true
},
{
"nr": "5.2",
"hazard_group": "Ergonomische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Zwangshaltung durch ungünstige Bedienelement-Position",
"hazard_cause": "Bedienelemente am HMI außerhalb der ergonomisch günstigen Reichweite führen bei dauerhafter Bedienung zu Zwangshaltung",
"lifecycle_phases": ["Betrieb"],
"component_zone": "Bedienstand HMI, Steuerpult",
"risk_in": {"f": 3, "w": 2, "p": 1, "s": 1, "r": 6},
"measures": ["Bedienelemente in ergonomisch günstiger Höhe"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 1, "r": 3},
"norm_references": ["EN 894-3"],
"sufficient": true
},
{
"nr": "6.1",
"hazard_group": "zusätzliche Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Verlust einer Sicherheitsfunktion durch Steuerungs- oder Softwarefehler",
"hazard_cause": "Steuerungs- oder Softwarefehler der eigenen Maschinensteuerung führt zu unkontrolliertem Verhalten oder Verlust einer Sicherheitsfunktion",
"lifecycle_phases": ["Betrieb", "Instandhaltung"],
"component_zone": "Gesamte Maschine, Steuerung",
"risk_in": {"f": 2, "w": 2, "p": 2, "s": 3, "r": 18},
"measures": ["Sichere Fehlerbehandlung", "Sichere Software-Fallbacks", "Watchdog"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 3, "r": 9},
"norm_references": ["EN ISO 13849-1"],
"sufficient": true
},
{
"nr": "6.2",
"hazard_group": "zusätzliche Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Verlust der Sicherheitsfunktion nach fehlerhaftem Software-Update",
"hazard_cause": "Korrupte oder inkompatible Firmware nach fehlerhaftem Update über die USB-Schnittstelle lässt die Steuerung undefiniert verhalten oder Sicherheitsfunktion verlieren",
"lifecycle_phases": ["Instandhaltung"],
"component_zone": "Gesamte Maschine, Steuerung, Update-Schnittstelle",
"risk_in": {"f": 2, "w": 2, "p": 2, "s": 3, "r": 18},
"measures": ["Atomares Update mit Rückfall auf lauffähige Version", "Kompatibilitätsprüfung vor Update"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 3, "r": 9},
"norm_references": ["EN ISO 13849-1"],
"sufficient": true
},
{
"nr": "4.4",
"hazard_group": "Mechanische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Erfassen/Aufwickeln an rotierenden Teilen bei geöffneter Schutztür",
"hazard_cause": "Bei geöffneter Tür im Wartungs- oder Reinigungsfall können lose Kleidung oder Haare an noch zugänglichen rotierenden Wellen erfasst und aufgewickelt werden",
"lifecycle_phases": ["Instandhaltung", "Reinigung"],
"component_zone": "Rotierende Wellen, Spülarm bei geöffneter Schutztür",
"risk_in": {"f": 1, "w": 1, "p": 2, "s": 3, "r": 12},
"measures": ["Rotation stoppt bei geöffneter Tür durch Verriegelung", "Warnhinweis"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 3, "r": 6},
"norm_references": ["EN ISO 14120"],
"sufficient": true
},
{
"nr": "4.5",
"hazard_group": "Mechanische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Reibung/Hautabschürfung an rotierenden Teilen bei geöffneter Schutztür",
"hazard_cause": "Berührung rotierender Wellen oder Oberflächen bei geöffneter Tür im Wartungsfall führt zu Hautabschürfungen durch Reibung",
"lifecycle_phases": ["Instandhaltung"],
"component_zone": "Rotierende Welle bei geöffneter Schutztür",
"risk_in": {"f": 1, "w": 1, "p": 2, "s": 2, "r": 8},
"measures": ["Rotation stoppt bei geöffneter Tür durch Verriegelung"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 2, "r": 4},
"norm_references": ["EN ISO 14120"],
"sufficient": true
},
{
"nr": "1.4",
"hazard_group": "Thermische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Trockenlauf-Überhitzung von Boiler/Heizung",
"hazard_cause": "Das Heizelement bzw. der Boiler läuft bei Wassermangel trocken, überhitzt und kann einen Brand oder eine Verbrühung durch überhitztes Wasser auslösen",
"lifecycle_phases": ["Betrieb"],
"component_zone": "Boiler, Tankheizkörper, Heizelement",
"risk_in": {"f": 2, "w": 2, "p": 2, "s": 3, "r": 18},
"measures": ["Trockengehschutz / Niveauüberwachung der Heizung", "Temperaturbegrenzer (STB)"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 3, "r": 9},
"norm_references": ["EN 60335-2-58", "EN 60335-1"],
"sufficient": true
},
{
"nr": "3.4",
"hazard_group": "Elektrische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Restspannung / gespeicherte elektrische Energie nach Abschalten",
"hazard_cause": "Nach dem Abschalten der Spannungsversorgung stehen durch Kondensatoren im Frequenzumrichter oder Netzfilter noch gefährliche Berührungsspannungen an",
"lifecycle_phases": ["Instandhaltung", "Fehlersuche und -beseitigung"],
"component_zone": "Frequenzumrichter, Netzfilter, Schaltschrank",
"risk_in": {"f": 1, "w": 2, "p": 3, "s": 4, "r": 24},
"measures": ["Sichere Energieentladung nach Abschalten", "Warnhinweis Restspannung, Entladezeit abwarten"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 4, "r": 12},
"norm_references": ["IEC 60204-1"],
"sufficient": true
},
{
"nr": "4.6",
"hazard_group": "Mechanische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Schnittverletzung an scharfen Kanten",
"hazard_cause": "Schneiden an scharfen Blechkanten, Sieben oder dem Ablaufpumpen-Laufrad beim Reinigen oder Eingreifen in die Spülkammer",
"lifecycle_phases": ["Reinigung", "Instandhaltung"],
"component_zone": "Zugängliche Kanten, Siebe, Spülkammer, Ablaufpumpe",
"risk_in": {"f": 3, "w": 2, "p": 2, "s": 1, "r": 7},
"measures": ["Brechen oder Runden aller zugänglichen Kanten"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 1, "r": 3},
"norm_references": ["EN ISO 12100"],
"sufficient": true
},
{
"nr": "4.7",
"hazard_group": "Mechanische Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Kippen / mangelnde Standsicherheit",
"hazard_cause": "Unzureichende Standsicherheit bei Untertischmontage, Transport oder Installation führt zum Kippen oder Umstürzen der Maschine",
"lifecycle_phases": ["Transport", "Montage und Installation"],
"component_zone": "Gesamte Maschine, Aufstellbereich",
"risk_in": {"f": 1, "w": 1, "p": 2, "s": 2, "r": 8},
"measures": ["Standsichere Aufstellung / Befestigung", "Kippsichere Konstruktion"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 2, "r": 4},
"norm_references": ["EN ISO 12100"],
"sufficient": true
},
{
"nr": "2.3",
"hazard_group": "Gefährdungen durch Materialien und Substanzen",
"hazard_group_applicable": true,
"hazard_type": "Rückfluss / Kontamination des Trinkwassers",
"hazard_cause": "Verschmutztes Spül- oder Chemiewasser wird ohne Rückflussverhinderer in das Trinkwassernetz zurückgesaugt und kontaminiert es",
"lifecycle_phases": ["Betrieb"],
"component_zone": "Frischwasseranschluss, Wasserzulauf",
"risk_in": {"f": 2, "w": 2, "p": 2, "s": 3, "r": 18},
"measures": ["Rückflussverhinderer / Systemtrenner nach EN 1717", "Freier Auslauf"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 3, "r": 9},
"norm_references": ["EN 1717", "EN 60335-2-58"],
"sufficient": true
},
{
"nr": "2.4",
"hazard_group": "Gefährdungen durch Materialien und Substanzen",
"hazard_group_applicable": true,
"hazard_type": "Mikrobielle Belastung / Legionellen im Stehwasser",
"hazard_cause": "Stehwasser im Boiler oder Tank bei niedrigen Temperaturen begünstigt mikrobielles Wachstum und Legionellen, die über Aerosole eingeatmet werden",
"lifecycle_phases": ["Betrieb", "Instandhaltung"],
"component_zone": "Boiler, Tank, Stehwasser",
"risk_in": {"f": 1, "w": 1, "p": 2, "s": 3, "r": 12},
"measures": ["Thermische Desinfektion / ausreichende Wassertemperatur", "Regelmäßiger Wasserwechsel"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 3, "r": 9},
"norm_references": ["EN 60335-2-58"],
"sufficient": true
},
{
"nr": "6.3",
"hazard_group": "zusätzliche Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Versagen der Tür-/Schutzeinrichtungs-Verriegelung",
"hazard_cause": "Die Verriegelung des Tür-Sicherheitsschalters versagt oder wird überbrückt, sodass der Zugriff in die Spülkammer bei laufendem Spülgang (Heißwasser, rotierender Spülarm) möglich wird",
"lifecycle_phases": ["Betrieb", "Instandhaltung"],
"component_zone": "Tür-Sicherheitsschalter, Verriegelung, Spülkammer",
"risk_in": {"f": 3, "w": 2, "p": 2, "s": 3, "r": 21},
"measures": ["Sichere Verriegelung mit Fehlerüberwachung (PL nach ISO 13849)", "Zwangsöffnende Kontakte"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 3, "r": 9},
"norm_references": ["EN ISO 14119", "EN ISO 13849-1"],
"sufficient": true
},
{
"nr": "6.4",
"hazard_group": "zusätzliche Gefährdungen",
"hazard_group_applicable": true,
"hazard_type": "Unerwarteter Wiederanlauf bei Wartung",
"hazard_cause": "Während Wartung oder Reinigung läuft die Maschine durch fehlende Freischaltung (LOTO) oder automatischen Wiederanlauf unerwartet an",
"lifecycle_phases": ["Instandhaltung", "Reinigung"],
"component_zone": "Gesamte Maschine, Antriebe, Pumpe",
"risk_in": {"f": 2, "w": 2, "p": 2, "s": 3, "r": 18},
"measures": ["Freischalten und gegen Wiedereinschalten sichern (LOTO)", "Kein automatischer Wiederanlauf"],
"measure_type": "KM",
"risk_out": {"f": 1, "w": 1, "p": 1, "s": 3, "r": 9},
"norm_references": ["IEC 60204-1", "EN ISO 12100"],
"sufficient": true
}
]
}
@@ -0,0 +1,237 @@
package ucca
import (
"regexp"
"strconv"
"strings"
)
// authorityInfo is the normative classification of a search result, used internally
// for re-ranking only (Phase 1 changes ordering, not the response contract).
type authorityInfo struct {
weight int // 100 binding, 80 technical_standard, 70 guidance, 0 foreign, 50 unknown
sourceClass string // binding_law | technical_standard | supervisory_guidance | foreign_law | unknown
jurisdiction string // DE | EU | CH
}
var (
guidanceMarkers = []string{
"DSK", "EDPB", "BfDI", "BFDI", "BayLfD", "Baylfb", "ENISA", "BSI", "EUCC",
"Standards Mapping", "Kpnr", "Orientierungshilfe", "Handreichung", "Beschluss",
"Leitlinie", "Guidance", "Empfehlung", "OECD", "CISA", "Blue Guide",
}
// Technical standards / control frameworks (best-practice controls). Checked BEFORE
// guidanceMarkers so a "BSI Grundschutz" chunk classifies as a standard, not BSI guidance.
standardMarkers = []string{
"NIST", "OWASP", "Grundschutz", "ISO 27001", "ISO/IEC 27001",
"CSA CCM", "Cloud Controls Matrix", "CIS Benchmark", "CIS Control",
}
foreignMarkers = []string{"RevDSG", "fedlex", "(CH)"}
deMarkers = []string{"BDSG", "DSK", "BfDI", "BFDI", "BayLfD", "Baylfb", "BSI"}
normPattern = regexp.MustCompile(`(§|Art\.?)\s*\d`)
bdsgParagraph = regexp.MustCompile(`§\s*(\d+)`)
)
// classifyAuthority derives weight/source-class/jurisdiction. Explicitly tagged payload
// values win; otherwise it falls back to the curated category + name markers, so the
// not-yet-re-ingested (untagged) corpus is still classified deterministically.
func classifyAuthority(r LegalSearchResult) authorityInfo {
jur := r.Jurisdiction
if jur == "" {
jur = inferJurisdiction(r)
}
hay := r.ArticleLabel + " " + r.RegulationShort + " " + r.RegulationName + " " + r.RegulationCode
// A recognised standard NAME (NIST/OWASP/ISO 27001/CIS/CSA CCM/Grundschutz) is authoritative
// even when the corpus mis-tagged the chunk as supervisory_guidance (weight 70) — many
// standards were ingested with a generic guidance source_class. The name wins, so they
// classify (and rank) as technical_standard / control_standard. binding_law is preserved.
if r.SourceClass != "binding_law" && containsAny(hay, standardMarkers) {
return authorityInfo{weight: 80, sourceClass: "technical_standard", jurisdiction: jur}
}
if r.SourceClass != "" {
w := r.AuthorityWeight
if w == 0 && r.SourceClass == "binding_law" {
w = 100
}
return authorityInfo{weight: w, sourceClass: r.SourceClass, jurisdiction: jur}
}
if r.AuthorityWeight > 0 {
return authorityInfo{weight: r.AuthorityWeight, sourceClass: sourceClassFromWeight(r.AuthorityWeight), jurisdiction: jur}
}
switch {
case containsAny(hay, foreignMarkers):
return authorityInfo{weight: 0, sourceClass: "foreign_law", jurisdiction: "CH"}
case r.Category == "standard" || containsAny(hay, standardMarkers):
return authorityInfo{weight: 80, sourceClass: "technical_standard", jurisdiction: jur}
case r.Category == "guidance" || containsAny(hay, guidanceMarkers):
return authorityInfo{weight: 70, sourceClass: "supervisory_guidance", jurisdiction: jur}
case r.Category == "regulation" || r.Category == "eu_recht" || normPattern.MatchString(r.ArticleLabel):
return authorityInfo{weight: 100, sourceClass: "binding_law", jurisdiction: jur}
default:
return authorityInfo{weight: 50, sourceClass: "unknown", jurisdiction: jur}
}
}
func sourceClassFromWeight(w int) string {
switch {
case w >= 100:
return "binding_law"
case w >= 80:
return "technical_standard"
case w >= 70:
return "supervisory_guidance"
case w <= 0:
return "foreign_law"
default:
return "unknown"
}
}
func inferJurisdiction(r LegalSearchResult) string {
hay := r.ArticleLabel + " " + r.RegulationShort + " " + r.RegulationName
switch {
case containsAny(hay, foreignMarkers):
return "CH"
case strings.Contains(hay, "§") || containsAny(hay, deMarkers):
return "DE"
default:
return "EU"
}
}
// --- Domain routing: separates same-authority but topically foreign norms ---
type domainDef struct {
name string
regs []string // regulation markers found in a chunk
keywords []string // query keywords that signal this domain
}
// Deterministic order (slice, not map) — important for stable classification + tests.
var domains = []domainDef{
{"data_protection",
[]string{"DSGVO", "GDPR", "BDSG", "EDPB", "DSK", "BfDI", "BayLfD", "DPF"},
[]string{"personenbezogen", "betroffene", "datenschutz", "datenschutzbeauftrag", "dsb",
"datenpanne", "auskunft", "loesch", "lösch", "einwilligung", "besondere kategorien", "auftragsverarbeiter"}},
{"cyber",
[]string{"CRA", "NIS2", "NIS-2", "ENISA", "DORA", "EUCC"},
[]string{"security update", "sicherheitsupdate", "sicherheitsaktualisierung", "schwachstelle", "sbom",
"cybersicherheit", "konformit", "hersteller", "importeur", "haendler", "händler", "ikt-",
"resilienz", "sicherheitsvorfall", "digitalen elementen"}},
{"ai",
[]string{"AI Act", "KI-VO", "KI-Verordnung"},
[]string{"ki-system", "ki-modell", "hochrisiko", "kuenstliche intelligenz", "künstliche intelligenz"}},
{"product_safety",
[]string{"Maschinenverordnung", "MaschinenVO", "GPSR", "RED", "MDR"},
nil},
}
func queryDomain(query string) string {
ql := strings.ToLower(query)
for _, d := range domains {
for _, kw := range d.keywords {
if strings.Contains(ql, kw) {
return d.name
}
}
}
return ""
}
func chunkDomain(r LegalSearchResult) string {
hay := r.ArticleLabel + " " + r.RegulationShort + " " + r.RegulationCode + " " + r.RegulationName
for _, d := range domains {
if containsAny(hay, d.regs) {
return d.name
}
}
return ""
}
// scopeClass flags special sub-regimes that must not win general questions —
// BDSG Teil 3 (§§ 45-84) implements the JI directive (law enforcement), not the general regime.
func scopeClass(r LegalSearchResult) string {
hay := r.ArticleLabel + " " + r.RegulationShort
if strings.Contains(hay, "BDSG") {
if m := bdsgParagraph.FindStringSubmatch(hay); m != nil {
if n, err := strconv.Atoi(m[1]); err == nil && n >= 45 && n <= 84 {
return "law_enforcement"
}
}
}
return "general"
}
// --- Topic ontology: amplifier only (boost), never an override ---
type topicDef struct {
keywords []string
norms []string // preferred canonical citation fragments
}
var topics = []topicDef{
{[]string{"datenschutzbeauftrag", "dsb", "benennung"}, []string{"Art. 37", "§ 38 BDSG"}},
{[]string{"stellung des"}, []string{"Art. 38"}},
{[]string{"aufgaben des"}, []string{"Art. 39"}},
{[]string{"folgenabsch", "dsfa"}, []string{"Art. 35"}},
{[]string{"besondere kategorien"}, []string{"Art. 9", "§ 22 BDSG"}},
{[]string{"auskunft"}, []string{"Art. 15", "§ 34 BDSG"}},
{[]string{"loesch", "lösch"}, []string{"Art. 17", "§ 35 BDSG"}},
{[]string{"bussgeld", "geldbusse"}, []string{"Art. 83"}},
{[]string{"security update", "sicherheitsupdate", "schwachstelle", "sbom", "cybersicherheitsanforderung"}, []string{"CRA Anhang I"}},
{[]string{"meldepflicht", "sicherheitsvorfall"}, []string{"Art. 14 CRA"}},
}
// resultMatchesTopic reports whether the result is a preferred norm of a topic the query hits.
func resultMatchesTopic(query string, r LegalSearchResult) bool {
ql := strings.ToLower(query)
hay := r.ArticleLabel + " " + r.RegulationShort
for _, t := range topics {
if !containsAnyLower(ql, t.keywords) {
continue
}
for _, n := range t.norms {
if normMatches(hay, n) {
return true
}
}
}
return false
}
// normMatches checks that norm appears in hay with a non-digit boundary, so "Art. 9"
// matches "Art. 9 DSGVO" but not "Art. 90".
func normMatches(hay, norm string) bool {
idx := strings.Index(hay, norm)
if idx < 0 {
return false
}
end := idx + len(norm)
if end < len(hay) && hay[end] >= '0' && hay[end] <= '9' {
return false
}
return true
}
func queryIsForeign(query string) bool {
return containsAnyLower(strings.ToLower(query),
[]string{"schweiz", "revdsg", "fedlex", " ch ", "oesterreich", "österreich"})
}
func containsAny(hay string, markers []string) bool {
for _, m := range markers {
if strings.Contains(hay, m) {
return true
}
}
return false
}
func containsAnyLower(haylower string, markers []string) bool {
for _, m := range markers {
if strings.Contains(haylower, strings.ToLower(m)) {
return true
}
}
return false
}
@@ -0,0 +1,171 @@
package ucca
import (
"sort"
"strings"
)
// Re-ranking coefficients (validated in the offline golden harness; Phase A — conservative).
const (
authorityCoef = 0.40 // * weight/100
jurisdictionGain = 0.05 // binding/guidance from DE or EU
foreignPenalty = 0.60 // foreign law on a DE/EU question (demoted, not removed)
unknownPenalty = 0.08
domainMatchGain = 0.15
offDomainPenalty = 0.10 // off-domain binding (demoted, not removed)
scopePenalty = 0.25 // BDSG Teil 3 (law enforcement) on a general DP question
topicGain = 0.18 // amplifier only
supersededPenalty = 0.50 // superseded Alt-Quelle (pre-eu-v1): demoted, nicht versteckt
intentLiftGain = 0.10 // epsilon a qualifying interpretative source is lifted ABOVE the best binding
intentLiftMargin = 0.05 // ...only if that source is semantically competitive with binding
)
// guidanceIntentSignals mark a query that EXPLICITLY asks for an interpretation /
// recommendation by a guidance body, rather than for the binding obligation. Only
// then may a (semantically competitive) guideline outrank the binding norm.
var guidanceIntentSignals = []string{
"edpb", "europäischer datenschutzausschuss", "europaeischer datenschutzausschuss",
"dsk", "enisa", "bsi", "leitlinie", "guideline", "orientierungshilfe",
"auslegung", "empfiehlt", "empfehlung", "sagt", "laut",
}
// controlIntentSignals mark a query that asks HOW to implement / which controls or
// measures fit — rather than WHAT the binding obligation is. Only then may a
// (semantically competitive) technical_standard outrank the binding norm.
var controlIntentSignals = []string{
"control", "controls", "maßnahme", "massnahme", "schutzmaßnahme",
"best practice", "best-practice", "umsetzen", "implementier", "absicher",
"härt", "haert", "hardening", "nist", "owasp", "grundschutz",
"ccm", "iso 27001", "isms",
}
func queryMatchesAny(query string, signals []string) bool {
q := strings.ToLower(query)
for _, sig := range signals {
if strings.Contains(q, sig) {
return true
}
}
return false
}
// queryWantsGuidance reports whether the query explicitly asks for guidance/interpretation.
func queryWantsGuidance(query string) bool { return queryMatchesAny(query, guidanceIntentSignals) }
// queryWantsControls reports whether the query asks for implementation controls/measures.
func queryWantsControls(query string) bool { return queryMatchesAny(query, controlIntentSignals) }
// bestBindingSemantic returns the highest RAW semantic score among binding-law
// results (0 if none / no intent). Used as the guard threshold so an off-topic
// interpretative source cannot ride the intent boost.
func bestBindingSemantic(results []LegalSearchResult, wantsIntent bool) float64 {
if !wantsIntent {
return 0
}
best := 0.0
for _, r := range results {
if classifyAuthority(r).sourceClass == "binding_law" && r.Score > best {
best = r.Score
}
}
return best
}
// authorityScore computes the normative relevance of a result for a query. It augments the
// semantic score with authority/jurisdiction/domain/scope/topic signals. Exposed for tests.
func authorityScore(query string, r LegalSearchResult, qDomain string, qForeign bool) float64 {
info := classifyAuthority(r)
score := r.Score + authorityCoef*float64(info.weight)/100.0
if r.Superseded {
// Alt-Quelle (pre-eu-v1): Default-Fragen sollen die eu-v1-Norm sehen. Demoted,
// nicht entfernt — fuer Historie/Uebergangsfragen bleibt sie auffindbar.
score -= supersededPenalty
}
if info.jurisdiction == "CH" && !qForeign {
score -= foreignPenalty // Fremdrecht bei DE/EU-Frage: demoted, nicht geloescht
} else {
score += jurisdictionGain
}
if info.sourceClass == "unknown" {
score -= unknownPenalty
}
if qDomain != "" {
switch cd := chunkDomain(r); {
case cd == qDomain:
score += domainMatchGain
case cd != "":
score -= offDomainPenalty // off-domain binding: demoted, nicht geloescht
}
}
if qDomain == "data_protection" && scopeClass(r) == "law_enforcement" {
score -= scopePenalty
}
if resultMatchesTopic(query, r) {
score += topicGain // Verstaerker, kein Override
}
return score
}
// rerankByAuthority re-orders results so binding law from the matching jurisdiction/domain
// ranks above guidance, foreign and off-domain law — WITHOUT dropping anything (guidance is
// kept as interpretation context). The computed score is written back to Score so downstream
// merges (e.g. the multi-collection advisor) preserve this order. Pure + deterministic.
func rerankByAuthority(query string, results []LegalSearchResult) []LegalSearchResult {
if len(results) < 2 {
return results
}
qDomain := queryDomain(query)
qForeign := queryIsForeign(query)
wantsGuidance := queryWantsGuidance(query)
wantsControls := queryWantsControls(query)
bestBindingSem := bestBindingSemantic(results, wantsGuidance)
out := make([]LegalSearchResult, len(results))
copy(out, results)
for i := range out {
out[i].Score = authorityScore(query, out[i], qDomain, qForeign)
}
// Explicit interpretation intent → a competitive guideline may outrank binding (lift
// above the best binding FINAL). Explicit implementation intent → boost the CONTROL-POOL
// (operational/procedural requirement, control standard, implementation guidance) over
// the abstract obligation, soft-ordered by role. Norm questions (neither) stay untouched.
if wantsGuidance {
liftAboveBinding(out, results, bestBindingSem, "supervisory_guidance")
}
if wantsControls {
applyControlRoles(out)
}
sort.SliceStable(out, func(a, b int) bool {
return out[a].Score > out[b].Score
})
return out
}
// liftAboveBinding lifts a semantically-competitive interpretative source (the given
// sourceClass — supervisory_guidance or technical_standard) just ABOVE the best binding
// hit, ordered by semantic, so an EXPLICIT guidance/implementation question can return
// that source Top-1. A pure norm question (no intent → not called) keeps binding on top.
// Sources below the semantic margin are left untouched, so an off-topic source can never
// ride the override — and the lift is from the binding FINAL score, so authority/topic/
// domain bonuses cannot edge it out.
func liftAboveBinding(out, raw []LegalSearchResult, bestBindingSem float64, sourceClass string) {
bestBindingFinal := 0.0
for i := range out {
if classifyAuthority(out[i]).sourceClass == "binding_law" && out[i].Score > bestBindingFinal {
bestBindingFinal = out[i].Score
}
}
for i := range out {
// Classify (not raw payload) so the untagged legacy corpus — e.g. NIST ingested
// before source_class tagging — is still recognized as its interpretative class.
if classifyAuthority(out[i]).sourceClass != sourceClass || raw[i].Score < bestBindingSem-intentLiftMargin {
continue
}
lifted := bestBindingFinal + intentLiftGain + (raw[i].Score - bestBindingSem)
if lifted > out[i].Score {
out[i].Score = lifted
}
}
}
@@ -0,0 +1,96 @@
package ucca
import "testing"
func bindingRes(label, reg, jur string, score float64) LegalSearchResult {
return LegalSearchResult{ArticleLabel: label, RegulationShort: reg, SourceClass: "binding_law", AuthorityWeight: 100, Jurisdiction: jur, Score: score}
}
func guidanceRes(label, reg string, score float64) LegalSearchResult {
return LegalSearchResult{ArticleLabel: label, RegulationShort: reg, SourceClass: "supervisory_guidance", AuthorityWeight: 70, Jurisdiction: "EU", Score: score}
}
func foreignRes(label string, score float64) LegalSearchResult {
return LegalSearchResult{ArticleLabel: label, RegulationShort: "RevDSG", SourceClass: "foreign_law", AuthorityWeight: 0, Jurisdiction: "CH", Score: score}
}
// Acceptance criteria (Phase 1) expressed as ordering tests.
func TestRerankByAuthority_Acceptance(t *testing.T) {
t.Run("guidance does not overtake semantically competitive binding", func(t *testing.T) {
out := rerankByAuthority("Was gilt hier?", []LegalSearchResult{
guidanceRes("ENISA Mapping", "ENISA", 0.72),
bindingRes("CRA Anhang I", "CRA", "EU", 0.66),
})
if out[0].RegulationShort != "CRA" {
t.Fatalf("binding must rank first over competitive guidance, got %q", out[0].RegulationShort)
}
})
t.Run("foreign law demoted on DE/EU question but kept", func(t *testing.T) {
in := []LegalSearchResult{foreignRes("RevDSG Art 1", 0.85), bindingRes("Art. 9 DSGVO", "DSGVO", "EU", 0.62)}
out := rerankByAuthority("Welche Daten sind besonders geschuetzt?", in)
if out[0].RegulationShort != "DSGVO" {
t.Fatalf("binding EU must beat foreign on a DE/EU query, got %q", out[0].RegulationShort)
}
if len(out) != 2 {
t.Fatalf("foreign law must be kept, got len=%d", len(out))
}
})
t.Run("off-domain binding demoted but not removed", func(t *testing.T) {
in := []LegalSearchResult{
bindingRes("Art. 13 EU MDR", "MDR", "EU", 0.70),
bindingRes("Art. 13 CRA", "CRA", "EU", 0.60),
}
out := rerankByAuthority("Welche Pflichten hat der Hersteller von Produkten mit digitalen Elementen?", in)
if out[0].RegulationShort != "CRA" {
t.Fatalf("on-domain CRA must beat off-domain MDR, got %q", out[0].RegulationShort)
}
if len(out) != 2 {
t.Fatalf("off-domain MDR must be kept, got len=%d", len(out))
}
})
t.Run("same-regime binding wins over guidance", func(t *testing.T) {
out := rerankByAuthority("Was gilt hier?", []LegalSearchResult{
bindingRes("Art. 13 CRA", "CRA", "EU", 0.70),
guidanceRes("ENISA Mapping", "ENISA", 0.60),
})
if out[0].RegulationShort != "CRA" {
t.Fatalf("binding must win, got %q", out[0].RegulationShort)
}
})
t.Run("BDSG Teil 3 demoted below DSGVO on general DP question", func(t *testing.T) {
in := []LegalSearchResult{
bindingRes("§ 48 BDSG", "BDSG", "DE", 0.70), // Teil 3 (law enforcement)
bindingRes("Art. 9 DSGVO", "DSGVO", "EU", 0.62),
}
out := rerankByAuthority("Was sind besondere Kategorien personenbezogener Daten?", in)
if out[0].RegulationShort != "DSGVO" {
t.Fatalf("DSGVO must beat BDSG Teil 3 on a general DP question, got %q", out[0].RegulationShort)
}
})
t.Run("nothing is dropped and topic amplifies", func(t *testing.T) {
in := []LegalSearchResult{
guidanceRes("ENISA", "ENISA", 0.72),
bindingRes("CRA Anhang I", "CRA", "EU", 0.66),
foreignRes("RevDSG", 0.5),
}
out := rerankByAuthority("Anforderungen an Security Updates?", in)
if len(out) != len(in) {
t.Fatalf("rerank must preserve all results, got %d want %d", len(out), len(in))
}
if out[0].ArticleLabel != "CRA Anhang I" {
t.Fatalf("topic+authority must lift CRA Anhang I to top, got %q", out[0].ArticleLabel)
}
})
t.Run("single result returned unchanged", func(t *testing.T) {
in := []LegalSearchResult{bindingRes("Art. 1 CRA", "CRA", "EU", 0.5)}
if out := rerankByAuthority("x", in); len(out) != 1 {
t.Fatalf("len=%d", len(out))
}
})
}
@@ -0,0 +1,130 @@
package ucca
import "testing"
func TestClassifyAuthority(t *testing.T) {
tests := []struct {
name string
result LegalSearchResult
wantW int
wantSC string
wantJur string
}{
{"tagged binding EU", LegalSearchResult{AuthorityWeight: 100, SourceClass: "binding_law", Jurisdiction: "EU"}, 100, "binding_law", "EU"},
{"tagged guidance DE", LegalSearchResult{AuthorityWeight: 70, SourceClass: "supervisory_guidance", Jurisdiction: "DE"}, 70, "supervisory_guidance", "DE"},
{"tagged foreign CH", LegalSearchResult{AuthorityWeight: 0, SourceClass: "foreign_law", Jurisdiction: "CH"}, 0, "foreign_law", "CH"},
{"untagged ENISA guidance", LegalSearchResult{RegulationShort: "ENISA", ArticleLabel: "ENISA CRA Standards Mapping"}, 70, "supervisory_guidance", "EU"},
{"untagged NIST standard", LegalSearchResult{RegulationShort: "NIST SP 800-82r3", ArticleLabel: "AU-8"}, 80, "technical_standard", "EU"},
{"mis-tagged NIST guidance -> standard by name", LegalSearchResult{SourceClass: "supervisory_guidance", AuthorityWeight: 70, RegulationShort: "NIST SP 800-82r3", ArticleLabel: "NIST SP 800-82r3"}, 80, "technical_standard", "EU"},
{"BSI Grundschutz standard beats BSI guidance", LegalSearchResult{RegulationShort: "BSI Grundschutz", ArticleLabel: "BSI Grundschutz Baustein"}, 80, "technical_standard", "DE"},
{"weight-only 85 TRGS standard", LegalSearchResult{AuthorityWeight: 85, RegulationShort: "TRGS 529"}, 85, "technical_standard", "EU"},
{"tagged technical_standard", LegalSearchResult{AuthorityWeight: 80, SourceClass: "technical_standard", Jurisdiction: "EU"}, 80, "technical_standard", "EU"},
{"untagged CRA binding", LegalSearchResult{RegulationShort: "CRA", ArticleLabel: "Art. 13 CRA", Category: "regulation"}, 100, "binding_law", "EU"},
{"untagged BDSG binding DE", LegalSearchResult{RegulationShort: "BDSG", ArticleLabel: "§ 38 BDSG"}, 100, "binding_law", "DE"},
{"untagged RevDSG foreign", LegalSearchResult{RegulationShort: "RevDSG", ArticleLabel: "RevDSG (CH)"}, 0, "foreign_law", "CH"},
{"untagged unknown", LegalSearchResult{RegulationShort: "", ArticleLabel: ""}, 50, "unknown", "EU"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := classifyAuthority(tt.result)
if got.weight != tt.wantW || got.sourceClass != tt.wantSC || got.jurisdiction != tt.wantJur {
t.Errorf("classifyAuthority() = {%d %s %s}, want {%d %s %s}",
got.weight, got.sourceClass, got.jurisdiction, tt.wantW, tt.wantSC, tt.wantJur)
}
})
}
}
func TestQueryDomain(t *testing.T) {
tests := []struct{ q, want string }{
{"Welche Anforderungen an Security Updates?", "cyber"},
{"Wer braucht einen Datenschutzbeauftragten?", "data_protection"},
{"Was sind besondere Kategorien personenbezogener Daten?", "data_protection"},
{"Welche Pflichten beim Hochrisiko-KI-System?", "ai"},
{"Wie spaet ist es?", ""},
}
for _, tt := range tests {
if got := queryDomain(tt.q); got != tt.want {
t.Errorf("queryDomain(%q) = %q, want %q", tt.q, got, tt.want)
}
}
}
func TestChunkDomain(t *testing.T) {
tests := []struct {
name string
r LegalSearchResult
want string
}{
{"CRA cyber", LegalSearchResult{RegulationShort: "CRA", ArticleLabel: "Art. 13 CRA"}, "cyber"},
{"DSGVO dp", LegalSearchResult{RegulationShort: "DSGVO", ArticleLabel: "Art. 9 DSGVO"}, "data_protection"},
{"AI Act ai", LegalSearchResult{RegulationShort: "AI Act", ArticleLabel: "Art. 10 AI Act"}, "ai"},
{"MDR product", LegalSearchResult{RegulationShort: "MDR", ArticleLabel: "Art. 13 EU MDR"}, "product_safety"},
{"unknown", LegalSearchResult{RegulationShort: "XYZ"}, ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := chunkDomain(tt.r); got != tt.want {
t.Errorf("chunkDomain() = %q, want %q", got, tt.want)
}
})
}
}
func TestScopeClass(t *testing.T) {
tests := []struct {
name string
r LegalSearchResult
want string
}{
{"BDSG Teil 3 law enforcement", LegalSearchResult{RegulationShort: "BDSG", ArticleLabel: "§ 48 BDSG"}, "law_enforcement"},
{"BDSG general part", LegalSearchResult{RegulationShort: "BDSG", ArticleLabel: "§ 38 BDSG"}, "general"},
{"DSGVO general", LegalSearchResult{RegulationShort: "DSGVO", ArticleLabel: "Art. 9 DSGVO"}, "general"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := scopeClass(tt.r); got != tt.want {
t.Errorf("scopeClass() = %q, want %q", got, tt.want)
}
})
}
}
func TestResultMatchesTopic(t *testing.T) {
tests := []struct {
name string
query string
r LegalSearchResult
want bool
}{
{"besondere Kategorien -> Art 9 match", "Was sind besondere Kategorien?", LegalSearchResult{ArticleLabel: "Art. 9 DSGVO"}, true},
{"besondere Kategorien -> Art 90 no match", "Was sind besondere Kategorien?", LegalSearchResult{ArticleLabel: "Art. 90 DSGVO"}, false},
{"security updates -> CRA Anhang I", "Anforderungen an Security Updates?", LegalSearchResult{ArticleLabel: "CRA Anhang I"}, true},
{"no topic keyword", "Wie spaet ist es?", LegalSearchResult{ArticleLabel: "Art. 9 DSGVO"}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := resultMatchesTopic(tt.query, tt.r); got != tt.want {
t.Errorf("resultMatchesTopic() = %v, want %v", got, tt.want)
}
})
}
}
func TestNormMatches(t *testing.T) {
tests := []struct {
hay, norm string
want bool
}{
{"Art. 9 DSGVO", "Art. 9", true},
{"Art. 90 DSGVO", "Art. 9", false},
{"§ 38 BDSG", "§ 38 BDSG", true},
{"§ 380 BDSG", "§ 38", false},
{"Art. 14 CRA", "Art. 14 CRA", true},
}
for _, tt := range tests {
if got := normMatches(tt.hay, tt.norm); got != tt.want {
t.Errorf("normMatches(%q,%q) = %v, want %v", tt.hay, tt.norm, got, tt.want)
}
}
}
@@ -0,0 +1,151 @@
package ucca
import (
"bufio"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
// ControlMapping is one persisted, versioned, REVIEWABLE link from a legal
// obligation/requirement to a concrete framework control — a node in the curated
// compliance graph (Regulation -> Obligation -> Control -> Evidence). The retriever only
// PROPOSES candidates (mapping_status=candidate); a human/rule decision turns the good ones
// into mapping_status=accepted, which is the audited truth the Advisor uses at runtime.
//
// There is intentionally NO probabilistic "confidence" field: once curated, a mapping is a
// professional statement, not an AI guess. The retriever's score lives only in the rationale
// of a candidate, never as structured truth.
type ControlMapping struct {
SourceNorm string `json:"source_norm"` // e.g. "CRA Annex I Part I (2)(c)"
SourceRole string `json:"source_role"` // source_role of the norm (operational_requirement, ...)
TargetFramework string `json:"target_framework"` // e.g. "OWASP ASVS"
TargetControl string `json:"target_control"` // e.g. "V6.3.1"
MappingType string `json:"mapping_type"` // supports | partially_supports | implements | related | contradicts
MappingStatus string `json:"mapping_status"` // candidate | accepted | rejected | superseded
Provenance string `json:"provenance"` // retriever_candidate | human_curated | rule_based
Rationale string `json:"rationale"`
ReviewedBy string `json:"reviewed_by,omitempty"` // who decided (human or rule id)
ReviewDate string `json:"review_date,omitempty"` // YYYY-MM-DD
ReviewReason string `json:"review_reason,omitempty"`
Version string `json:"version"`
}
// Allowed enum values — the deterministic "rule" layer that keeps the curated store clean.
var (
mappingTypeValues = map[string]bool{"supports": true, "partially_supports": true, "implements": true, "related": true, "contradicts": true}
mappingStatusValues = map[string]bool{"candidate": true, "accepted": true, "rejected": true, "superseded": true}
provenanceValues = map[string]bool{"retriever_candidate": true, "human_curated": true, "rule_based": true}
)
// Validate checks required fields + enum membership, and enforces the audit trail: any
// human/rule DECISION (accepted/rejected) must carry who/when/why. Fail-closed at load.
func (m ControlMapping) Validate() error {
switch {
case m.SourceNorm == "":
return fmt.Errorf("control mapping: source_norm required")
case m.TargetFramework == "":
return fmt.Errorf("control mapping: target_framework required")
case m.TargetControl == "":
return fmt.Errorf("control mapping: target_control required")
case !mappingTypeValues[m.MappingType]:
return fmt.Errorf("control mapping: invalid mapping_type %q", m.MappingType)
case !mappingStatusValues[m.MappingStatus]:
return fmt.Errorf("control mapping: invalid mapping_status %q", m.MappingStatus)
case !provenanceValues[m.Provenance]:
return fmt.Errorf("control mapping: invalid provenance %q", m.Provenance)
}
if m.MappingStatus == "accepted" || m.MappingStatus == "rejected" {
if m.ReviewedBy == "" || m.ReviewDate == "" || m.ReviewReason == "" {
return fmt.Errorf("control mapping %s->%s: status %q requires reviewed_by + review_date + review_reason (audit trail)",
m.SourceNorm, m.TargetControl, m.MappingStatus)
}
}
return nil
}
// IsAccepted reports whether this mapping is the active audited truth.
func (m ControlMapping) IsAccepted() bool { return m.MappingStatus == "accepted" }
// ControlMappingSet is the loaded, indexed mapping store (forward + reverse lookup).
type ControlMappingSet struct {
All []ControlMapping
bySourceNorm map[string][]ControlMapping
byControl map[string][]ControlMapping
}
func controlKey(framework, control string) string { return framework + ":" + control }
// ControlsFor returns the controls mapped to a source norm. acceptedOnly restricts to the
// audited truth (what the Advisor may treat as fact).
func (s *ControlMappingSet) ControlsFor(sourceNorm string, acceptedOnly bool) []ControlMapping {
return filterAccepted(s.bySourceNorm[sourceNorm], acceptedOnly)
}
// ObligationsFor returns the norms mapped to a framework control (reverse lookup).
func (s *ControlMappingSet) ObligationsFor(framework, control string, acceptedOnly bool) []ControlMapping {
return filterAccepted(s.byControl[controlKey(framework, control)], acceptedOnly)
}
func filterAccepted(in []ControlMapping, acceptedOnly bool) []ControlMapping {
if !acceptedOnly {
return in
}
out := make([]ControlMapping, 0, len(in))
for _, m := range in {
if m.IsAccepted() {
out = append(out, m)
}
}
return out
}
// LoadControlMappings reads every *.jsonl file under dir (one mapping per line; blank and
// //-prefixed lines ignored), validates each row, and builds the index. An invalid row
// aborts the whole load — fail-closed, because this is the audit truth, not best-effort.
func LoadControlMappings(dir string) (*ControlMappingSet, error) {
files, err := filepath.Glob(filepath.Join(dir, "*.jsonl"))
if err != nil {
return nil, err
}
set := &ControlMappingSet{
bySourceNorm: map[string][]ControlMapping{},
byControl: map[string][]ControlMapping{},
}
for _, f := range files {
fh, err := os.Open(f)
if err != nil {
return nil, err
}
sc := bufio.NewScanner(fh)
sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)
line := 0
for sc.Scan() {
line++
raw := strings.TrimSpace(sc.Text())
if raw == "" || strings.HasPrefix(raw, "//") {
continue
}
var m ControlMapping
if err := json.Unmarshal([]byte(raw), &m); err != nil {
fh.Close()
return nil, fmt.Errorf("%s:%d: %w", f, line, err)
}
if err := m.Validate(); err != nil {
fh.Close()
return nil, fmt.Errorf("%s:%d: %w", f, line, err)
}
set.All = append(set.All, m)
set.bySourceNorm[m.SourceNorm] = append(set.bySourceNorm[m.SourceNorm], m)
k := controlKey(m.TargetFramework, m.TargetControl)
set.byControl[k] = append(set.byControl[k], m)
}
fh.Close()
if err := sc.Err(); err != nil {
return nil, err
}
}
return set, nil
}
@@ -0,0 +1,85 @@
package ucca
import (
"os"
"path/filepath"
"testing"
)
func TestControlMapping_Validate(t *testing.T) {
candidate := ControlMapping{SourceNorm: "CRA Annex I", TargetFramework: "OWASP ASVS", TargetControl: "V6.3.1", MappingType: "supports", MappingStatus: "candidate", Provenance: "retriever_candidate"}
if err := candidate.Validate(); err != nil {
t.Fatalf("valid candidate rejected: %v", err)
}
accepted := ControlMapping{SourceNorm: "A", TargetFramework: "X", TargetControl: "Y", MappingType: "implements", MappingStatus: "accepted", Provenance: "human_curated", ReviewedBy: "benjamin", ReviewDate: "2026-06-25", ReviewReason: "passt"}
if err := accepted.Validate(); err != nil {
t.Fatalf("valid accepted rejected: %v", err)
}
bad := []struct {
name string
m ControlMapping
}{
{"no source_norm", ControlMapping{TargetFramework: "X", TargetControl: "Y", MappingType: "supports", MappingStatus: "candidate", Provenance: "retriever_candidate"}},
{"bad mapping_type", ControlMapping{SourceNorm: "A", TargetFramework: "X", TargetControl: "Y", MappingType: "nope", MappingStatus: "candidate", Provenance: "retriever_candidate"}},
{"bad mapping_status", ControlMapping{SourceNorm: "A", TargetFramework: "X", TargetControl: "Y", MappingType: "supports", MappingStatus: "maybe", Provenance: "retriever_candidate"}},
{"bad provenance", ControlMapping{SourceNorm: "A", TargetFramework: "X", TargetControl: "Y", MappingType: "supports", MappingStatus: "candidate", Provenance: "guessed"}},
{"accepted without audit trail", ControlMapping{SourceNorm: "A", TargetFramework: "X", TargetControl: "Y", MappingType: "supports", MappingStatus: "accepted", Provenance: "human_curated"}},
{"rejected without reason", ControlMapping{SourceNorm: "A", TargetFramework: "X", TargetControl: "Y", MappingType: "supports", MappingStatus: "rejected", Provenance: "human_curated", ReviewedBy: "b", ReviewDate: "2026-06-25"}},
}
for _, tt := range bad {
if err := tt.m.Validate(); err == nil {
t.Errorf("%s: expected rejection", tt.name)
}
}
}
func TestLoadControlMappings(t *testing.T) {
dir := t.TempDir()
content := `// header comment, ignored
{"source_norm":"CRA Annex I","source_role":"operational_requirement","target_framework":"OWASP ASVS","target_control":"V6.3.1","mapping_type":"supports","mapping_status":"accepted","provenance":"human_curated","reviewed_by":"benjamin","review_date":"2026-06-25","review_reason":"V6=Auth passt","rationale":"r","version":"2026-06-25"}
{"source_norm":"CRA Annex I","source_role":"operational_requirement","target_framework":"OWASP ASVS","target_control":"V14.2.4","mapping_type":"related","mapping_status":"candidate","provenance":"retriever_candidate","rationale":"r","version":"2026-06-25"}
`
if err := os.WriteFile(filepath.Join(dir, "m.jsonl"), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
set, err := LoadControlMappings(dir)
if err != nil {
t.Fatalf("load: %v", err)
}
if len(set.All) != 2 {
t.Fatalf("want 2 mappings, got %d", len(set.All))
}
if got := set.ControlsFor("CRA Annex I", false); len(got) != 2 {
t.Errorf("ControlsFor(all): want 2, got %d", len(got))
}
if got := set.ControlsFor("CRA Annex I", true); len(got) != 1 {
t.Errorf("ControlsFor(acceptedOnly): want 1 (only accepted), got %d", len(got))
}
if got := set.ObligationsFor("OWASP ASVS", "V6.3.1", true); len(got) != 1 {
t.Errorf("ObligationsFor accepted reverse lookup: want 1, got %d", len(got))
}
}
func TestLoadControlMappings_RejectsInvalid(t *testing.T) {
dir := t.TempDir()
// accepted without the who/when/why audit trail must fail-closed.
if err := os.WriteFile(filepath.Join(dir, "bad.jsonl"), []byte(`{"source_norm":"A","target_framework":"X","target_control":"Y","mapping_type":"supports","mapping_status":"accepted","provenance":"human_curated","rationale":"r","version":"v"}`), 0o644); err != nil {
t.Fatal(err)
}
if _, err := LoadControlMappings(dir); err == nil {
t.Error("accepted mapping without audit trail must fail the load (fail-closed)")
}
}
func TestControlMappings_SeedFileValid(t *testing.T) {
// The committed seed store must always load + validate.
set, err := LoadControlMappings("../../data/control_mappings")
if err != nil {
t.Fatalf("seed control_mappings failed to load: %v", err)
}
if len(set.All) == 0 {
t.Fatal("seed control_mappings is empty")
}
}
@@ -0,0 +1,174 @@
package ucca
import "strings"
// source_role is the FUNCTIONAL role of a chunk — WHAT must be done (obligation),
// HOW to implement it (operational/procedural requirement, control standard,
// implementation guidance), or how to READ the norm (interpretation/definition).
// It is ORTHOGONAL to source_class (legal authority): source_class decides RANK,
// source_role decides CONTROL-POOL membership for implementation questions.
// Derived deterministically from markers, so the untagged corpus needs no re-tag.
const (
roleObligation = "obligation" // the abstract duty (the WHAT)
roleOperationalReq = "operational_requirement" // concrete binding requirement (CRA Annex I)
roleProceduralReq = "procedural_requirement" // a process: notification/registration/DPIA/incident report
roleControlStandard = "control_standard" // best-practice control catalog (NIST/OWASP/ISO/CIS)
roleImplGuidance = "implementation_guidance" // advisory how-to (ENISA good practices, BSI)
roleInterpretation = "interpretation" // interprets the norm's MEANING (EDPB guideline)
roleDefinition = "definition" // definitions / scope / recitals
)
var (
proceduralMarkers = []string{
"Meldung", "Meldepflicht", "Notification", "Notifizierung", "Registrierung",
"Registration", "Konformitätserklärung", "Declaration of Conformity", "Incident",
"Berichterstattung", "Reporting", "Folgenabschätzung", "DSFA", "DPIA", "Anzeigepflicht",
}
annexMarkers = []string{"Anhang", "Annex", "Appendix", "Anlage"}
operationalMarkers = []string{"Anforderung", "Requirement", "essential", "wesentliche"}
implMarkers = []string{
"Good Practice", "Best Practice", "Standards Mapping", "Umsetzung", "Implementation",
"Handreichung", "Maßnahmenkatalog", "ICS", "SCADA", "Technical Guideline", "TIG",
}
definitionMarkers = []string{"Begriffsbestimmung", "Definition"}
)
// classifyRole derives the functional source_role from chunk metadata + the authority
// class. technical_standard is always a control_standard; guidance splits into
// implementation_guidance (how-to) vs interpretation (meaning); binding splits into
// procedural / operational requirement / definition / plain obligation.
func classifyRole(r LegalSearchResult) string {
cls := classifyAuthority(r).sourceClass
hay := strings.ToLower(r.ArticleLabel + " " + r.RegulationShort + " " + r.RegulationName + " " + r.Article)
switch {
case r.IsRecital:
return roleDefinition
case cls == "technical_standard":
return roleControlStandard
case cls == "supervisory_guidance":
if containsAnyLower(hay, implMarkers) {
return roleImplGuidance
}
return roleInterpretation
case cls == "binding_law":
switch {
case containsAnyLower(hay, definitionMarkers):
return roleDefinition
case containsAnyLower(hay, proceduralMarkers):
return roleProceduralReq
case containsAnyLower(hay, annexMarkers) || containsAnyLower(hay, operationalMarkers):
return roleOperationalReq
default:
return roleObligation
}
default:
return roleObligation
}
}
// controlRoleBonus is the soft intra-pool preference (User 2026-06-24):
// operational_requirement > procedural_requirement > control_standard > implementation_guidance.
var controlRoleBonus = map[string]float64{
roleOperationalReq: 0.100,
roleProceduralReq: 0.075,
roleControlStandard: 0.050,
roleImplGuidance: 0.000,
}
// controlPoolGain lifts EVERY control-pool role over the non-control roles (obligation/
// interpretation/definition) on an implementation question, so the binding abstract
// obligation does not dominate by authority alone. The obligation is not removed — it
// stays visible as "Rechtsgrundlage" context below the recommended measures.
const controlPoolGain = 0.15
// applyControlRoles boosts the control-pool (the four implementation roles) for an
// EXPLICIT implementation question, soft-ordered op_req > procedural > standard > guidance.
// Replaces the earlier "lift technical_standard above binding" — controls are not only
// technical_standard, and the binding operational_requirement (e.g. CRA Annex I) should win.
func applyControlRoles(out []LegalSearchResult) {
for i := range out {
if bonus, ok := controlRoleBonus[classifyRole(out[i])]; ok {
out[i].Score += controlPoolGain + bonus
}
}
}
// isControlPoolRole reports whether a role belongs to the control-pool surfaced on
// implementation questions (the four "how to implement" roles).
func isControlPoolRole(role string) bool {
switch role {
case roleOperationalReq, roleProceduralReq, roleControlStandard, roleImplGuidance:
return true
}
return false
}
// controlRoleOf classifies a raw Qdrant payload into a source_role, so searchControls can
// filter its deep dense pull to the control-pool BEFORE hits are mapped to LegalSearchResult.
func controlRoleOf(payload map[string]interface{}) string {
article := getString(payload, "article")
if article == "" {
article = getString(payload, "section")
}
return classifyRole(LegalSearchResult{
RegulationShort: getString(payload, "regulation_short"),
RegulationName: getString(payload, "regulation_name_de"),
ArticleLabel: getString(payload, "article_label"),
Article: article,
Category: getString(payload, "category"),
SourceClass: getString(payload, "source_class"),
AuthorityWeight: getInt(payload, "authority_weight"),
IsRecital: getBool(payload, "is_recital"),
})
}
// ensureControlDiversity guarantees that the returned top-K of a control question surfaces at
// least one operational_requirement and one control_standard WHEN the pool contains them —
// without forcing them to Top-1. implementation_guidance (e.g. ENISA good practices) keeps its
// earned semantic lead; the rule only promotes the best hit of a missing control role into the
// top-K by overwriting the lowest-ranked redundant guidance slot. So an implementation question
// shows the relevant source ROLES (binding requirement + standard + guidance) side by side
// instead of one role flooding the list. The promoted hit's original (now duplicate) position
// stays in the tail and is dropped by the caller's truncation to topK.
func ensureControlDiversity(results []LegalSearchResult, topK int) []LegalSearchResult {
if topK <= 0 || topK >= len(results) {
return results // everything is already returned — nothing to promote
}
roleAt := make([]string, len(results))
for i := range results {
roleAt[i] = classifyRole(results[i])
}
present := make(map[string]bool, topK)
for i := 0; i < topK; i++ {
present[roleAt[i]] = true
}
for _, want := range []string{roleOperationalReq, roleControlStandard} {
if present[want] {
continue
}
src := -1
for i := topK; i < len(results); i++ {
if roleAt[i] == want {
src = i
break
}
}
if src < 0 {
continue // role absent from the whole pool — nothing to promote
}
dst := -1
for j := topK - 1; j >= 0; j-- {
if roleAt[j] == roleImplGuidance {
dst = j
break
}
}
if dst < 0 {
continue // no redundant guidance to sacrifice — leave the head untouched
}
results[dst] = results[src]
roleAt[dst] = want
present[want] = true
}
return results
}
@@ -0,0 +1,134 @@
package ucca
import "testing"
func TestClassifyRole(t *testing.T) {
tests := []struct {
name string
r LegalSearchResult
want string
}{
{"NIST -> control_standard", LegalSearchResult{RegulationShort: "NIST SP 800-82r3", ArticleLabel: "AU-8"}, roleControlStandard},
{"OWASP -> control_standard", LegalSearchResult{RegulationShort: "OWASP ASVS"}, roleControlStandard},
{"CRA Anhang -> operational_requirement", LegalSearchResult{RegulationShort: "CRA", ArticleLabel: "CRA Anhang I", Category: "regulation"}, roleOperationalReq},
{"CRA Meldepflicht -> procedural_requirement", LegalSearchResult{RegulationShort: "CRA", ArticleLabel: "Art. 14 CRA Meldepflicht", Category: "regulation"}, roleProceduralReq},
{"ENISA Good Practices -> implementation_guidance", LegalSearchResult{RegulationShort: "ENISA Supply Chain Good Practices"}, roleImplGuidance},
{"EDPB Leitlinie -> interpretation", LegalSearchResult{RegulationShort: "EDPB DPO", ArticleLabel: "WP243 Leitlinien Datenschutzbeauftragte"}, roleInterpretation},
{"DORA article -> obligation", LegalSearchResult{RegulationShort: "DORA", ArticleLabel: "Art. 5 DORA", Category: "regulation"}, roleObligation},
{"DSGVO Begriffsbestimmungen -> definition", LegalSearchResult{RegulationShort: "DSGVO", ArticleLabel: "Art. 4 DSGVO Begriffsbestimmungen", Category: "regulation"}, roleDefinition},
{"recital -> definition", LegalSearchResult{RegulationShort: "CRA", IsRecital: true}, roleDefinition},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := classifyRole(tt.r); got != tt.want {
t.Errorf("classifyRole() = %q, want %q", got, tt.want)
}
})
}
}
func TestApplyControlRoles_PoolPreference(t *testing.T) {
// op_req > procedural > control_standard > impl_guidance; non-control roles get no boost.
roles := []struct {
r LegalSearchResult
wantGain float64
}{
{LegalSearchResult{ArticleLabel: "CRA Anhang I", Category: "regulation"}, controlPoolGain + 0.100},
{LegalSearchResult{ArticleLabel: "Art. 14 CRA Meldepflicht", Category: "regulation"}, controlPoolGain + 0.075},
{LegalSearchResult{RegulationShort: "NIST SP 800-53"}, controlPoolGain + 0.050},
{LegalSearchResult{RegulationShort: "ENISA Good Practices"}, controlPoolGain + 0.000},
{LegalSearchResult{ArticleLabel: "Art. 5 DORA", Category: "regulation"}, 0.0}, // obligation: no boost
}
for _, rc := range roles {
out := []LegalSearchResult{rc.r}
out[0].Score = 1.0
applyControlRoles(out)
if got := out[0].Score - 1.0; got < rc.wantGain-1e-9 || got > rc.wantGain+1e-9 {
t.Errorf("role %q: gain %.3f, want %.3f", classifyRole(rc.r), got, rc.wantGain)
}
}
}
func TestIsControlPoolRole(t *testing.T) {
for _, r := range []string{roleOperationalReq, roleProceduralReq, roleControlStandard, roleImplGuidance} {
if !isControlPoolRole(r) {
t.Errorf("%q should be in the control-pool", r)
}
}
for _, r := range []string{roleObligation, roleInterpretation, roleDefinition} {
if isControlPoolRole(r) {
t.Errorf("%q should NOT be in the control-pool", r)
}
}
}
func TestControlRoleOf_Payload(t *testing.T) {
// searchControls filters its deep dense pull by classifying the raw Qdrant payload.
nist := map[string]interface{}{"regulation_short": "NIST SP 800-82r3", "article": "AU-8"}
if got := controlRoleOf(nist); got != roleControlStandard {
t.Errorf("untagged NIST payload role = %q, want control_standard", got)
}
craAnnex := map[string]interface{}{"regulation_short": "CRA", "article": "Anhang-I", "category": "regulation"}
if got := controlRoleOf(craAnnex); got != roleOperationalReq {
t.Errorf("CRA Anhang payload role = %q, want operational_requirement", got)
}
dora := map[string]interface{}{"regulation_short": "DORA", "article_label": "Art. 5 DORA", "category": "regulation"}
if got := controlRoleOf(dora); isControlPoolRole(got) {
t.Errorf("DORA abstract article role = %q must be excluded from the control-pool", got)
}
}
func headHasRole(head []LegalSearchResult, role string) bool {
for _, r := range head {
if classifyRole(r) == role {
return true
}
}
return false
}
func TestEnsureControlDiversity(t *testing.T) {
ig := func(n string) LegalSearchResult {
return LegalSearchResult{RegulationShort: "ENISA " + n + " Good Practices"}
}
opReq := LegalSearchResult{RegulationShort: "CRA", ArticleLabel: "CRA Anhang I", Category: "regulation"}
std := LegalSearchResult{RegulationShort: "NIST SP 800-53"}
t.Run("injects missing op_req + control_standard, guidance keeps Top-1", func(t *testing.T) {
out := ensureControlDiversity([]LegalSearchResult{ig("A"), ig("B"), ig("C"), std, opReq}, 3)
head := out[:3]
if classifyRole(head[0]) != roleImplGuidance {
t.Errorf("Top-1 should stay implementation_guidance, got %q", classifyRole(head[0]))
}
if !headHasRole(head, roleOperationalReq) {
t.Error("top-K must contain an operational_requirement after diversity")
}
if !headHasRole(head, roleControlStandard) {
t.Error("top-K must contain a control_standard after diversity")
}
})
t.Run("no-op when both roles already present", func(t *testing.T) {
out := ensureControlDiversity([]LegalSearchResult{opReq, std, ig("A"), ig("B")}, 3)
if classifyRole(out[0]) != roleOperationalReq || classifyRole(out[1]) != roleControlStandard {
t.Error("already-diverse top-K must be left untouched")
}
})
t.Run("absent role is not forced (no panic)", func(t *testing.T) {
out := ensureControlDiversity([]LegalSearchResult{ig("A"), ig("B"), ig("C"), std}, 3)
if !headHasRole(out[:3], roleControlStandard) {
t.Error("present control_standard should be injected")
}
if headHasRole(out[:3], roleOperationalReq) {
t.Error("operational_requirement absent from the pool must NOT appear")
}
})
t.Run("topK covering the whole pool is unchanged", func(t *testing.T) {
out := ensureControlDiversity([]LegalSearchResult{ig("A"), opReq}, 5)
if len(out) != 2 || classifyRole(out[0]) != roleImplGuidance {
t.Error("topK >= len must return results unchanged")
}
})
}
@@ -0,0 +1,117 @@
package ucca
import (
"bufio"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
// EvidenceRequirement is the last edge of the compliance graph: it says WHAT concrete
// evidence proves a framework control is met, and how fresh that evidence must be. This is
// what lets the Advisor eventually state "the CRA requirement is fulfilled" — not because a
// document exists, but because the required, current evidence is present. Authored/curated,
// not retriever-generated.
type EvidenceRequirement struct {
Framework string `json:"framework"` // e.g. "OWASP ASVS"
Control string `json:"control"` // e.g. "V6.3.1"
EvidenceType string `json:"evidence_type"` // sbom|test_report|config_export|repo_scan|policy|ticket|audit_log|pentest
EvidenceSource string `json:"evidence_source"` // github|ci|scanner|manual_upload
FreshnessRequirement string `json:"freshness_requirement"` // per_release|quarterly|annually|continuous
Required bool `json:"required"`
Rationale string `json:"rationale"`
Version string `json:"version"`
}
// Allowed enum values — the rule layer that keeps the evidence catalog clean.
var (
evidenceTypeValues = map[string]bool{"sbom": true, "test_report": true, "config_export": true, "repo_scan": true, "policy": true, "ticket": true, "audit_log": true, "pentest": true}
evidenceSourceValues = map[string]bool{"github": true, "ci": true, "scanner": true, "manual_upload": true}
freshnessValues = map[string]bool{"per_release": true, "quarterly": true, "annually": true, "continuous": true}
)
// Validate checks required fields + enum membership. Fail-closed at load.
func (e EvidenceRequirement) Validate() error {
switch {
case e.Framework == "":
return fmt.Errorf("evidence requirement: framework required")
case e.Control == "":
return fmt.Errorf("evidence requirement: control required")
case !evidenceTypeValues[e.EvidenceType]:
return fmt.Errorf("evidence requirement: invalid evidence_type %q", e.EvidenceType)
case !evidenceSourceValues[e.EvidenceSource]:
return fmt.Errorf("evidence requirement: invalid evidence_source %q", e.EvidenceSource)
case !freshnessValues[e.FreshnessRequirement]:
return fmt.Errorf("evidence requirement: invalid freshness_requirement %q", e.FreshnessRequirement)
}
return nil
}
// EvidenceRequirementSet is the loaded, indexed evidence catalog.
type EvidenceRequirementSet struct {
All []EvidenceRequirement
byControl map[string][]EvidenceRequirement
}
// For returns all evidence requirements declared for a framework control.
func (s *EvidenceRequirementSet) For(framework, control string) []EvidenceRequirement {
return s.byControl[controlKey(framework, control)]
}
// RequiredFor returns only the required evidence for a control — the minimum that must be
// present before the control may be treated as met.
func (s *EvidenceRequirementSet) RequiredFor(framework, control string) []EvidenceRequirement {
out := make([]EvidenceRequirement, 0)
for _, e := range s.byControl[controlKey(framework, control)] {
if e.Required {
out = append(out, e)
}
}
return out
}
// LoadEvidenceRequirements reads every *.jsonl file under dir (one requirement per line;
// blank and //-prefixed lines ignored), validates each, and builds the per-control index.
// An invalid row aborts the load — fail-closed.
func LoadEvidenceRequirements(dir string) (*EvidenceRequirementSet, error) {
files, err := filepath.Glob(filepath.Join(dir, "*.jsonl"))
if err != nil {
return nil, err
}
set := &EvidenceRequirementSet{byControl: map[string][]EvidenceRequirement{}}
for _, f := range files {
fh, err := os.Open(f)
if err != nil {
return nil, err
}
sc := bufio.NewScanner(fh)
sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)
line := 0
for sc.Scan() {
line++
raw := strings.TrimSpace(sc.Text())
if raw == "" || strings.HasPrefix(raw, "//") {
continue
}
var e EvidenceRequirement
if err := json.Unmarshal([]byte(raw), &e); err != nil {
fh.Close()
return nil, fmt.Errorf("%s:%d: %w", f, line, err)
}
if err := e.Validate(); err != nil {
fh.Close()
return nil, fmt.Errorf("%s:%d: %w", f, line, err)
}
set.All = append(set.All, e)
k := controlKey(e.Framework, e.Control)
set.byControl[k] = append(set.byControl[k], e)
}
fh.Close()
if err := sc.Err(); err != nil {
return nil, err
}
}
return set, nil
}
@@ -0,0 +1,84 @@
package ucca
import (
"os"
"path/filepath"
"testing"
)
func TestEvidenceRequirement_Validate(t *testing.T) {
valid := EvidenceRequirement{Framework: "OWASP ASVS", Control: "V6.3.1", EvidenceType: "config_export", EvidenceSource: "github", FreshnessRequirement: "per_release", Required: true}
if err := valid.Validate(); err != nil {
t.Fatalf("valid rejected: %v", err)
}
bad := []struct {
name string
e EvidenceRequirement
}{
{"no control", EvidenceRequirement{Framework: "X", EvidenceType: "sbom", EvidenceSource: "ci", FreshnessRequirement: "per_release"}},
{"bad evidence_type", EvidenceRequirement{Framework: "X", Control: "Y", EvidenceType: "screenshot", EvidenceSource: "ci", FreshnessRequirement: "per_release"}},
{"bad evidence_source", EvidenceRequirement{Framework: "X", Control: "Y", EvidenceType: "sbom", EvidenceSource: "email", FreshnessRequirement: "per_release"}},
{"bad freshness", EvidenceRequirement{Framework: "X", Control: "Y", EvidenceType: "sbom", EvidenceSource: "ci", FreshnessRequirement: "weekly"}},
}
for _, tt := range bad {
if err := tt.e.Validate(); err == nil {
t.Errorf("%s: expected rejection", tt.name)
}
}
}
func TestLoadEvidenceRequirements(t *testing.T) {
dir := t.TempDir()
content := `// header
{"framework":"OWASP ASVS","control":"V6.3.1","evidence_type":"config_export","evidence_source":"github","freshness_requirement":"per_release","required":true,"version":"2026-06-25"}
{"framework":"OWASP ASVS","control":"V6.3.1","evidence_type":"pentest","evidence_source":"manual_upload","freshness_requirement":"annually","required":false,"version":"2026-06-25"}
`
if err := os.WriteFile(filepath.Join(dir, "e.jsonl"), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
set, err := LoadEvidenceRequirements(dir)
if err != nil {
t.Fatalf("load: %v", err)
}
if len(set.All) != 2 {
t.Fatalf("want 2, got %d", len(set.All))
}
if got := set.For("OWASP ASVS", "V6.3.1"); len(got) != 2 {
t.Errorf("For: want 2, got %d", len(got))
}
if got := set.RequiredFor("OWASP ASVS", "V6.3.1"); len(got) != 1 {
t.Errorf("RequiredFor: want 1 (pentest is optional), got %d", len(got))
}
}
func TestEvidenceRequirements_SeedFileValid(t *testing.T) {
set, err := LoadEvidenceRequirements("../../data/evidence_requirements")
if err != nil {
t.Fatalf("seed evidence_requirements failed to load: %v", err)
}
if len(set.All) == 0 {
t.Fatal("seed evidence_requirements is empty")
}
}
// TestGraph_AcceptedControlsHaveEvidence wires the two layers: every control an accepted
// CRA->OWASP mapping points to must have >=1 required evidence — the Obligation -> Control ->
// Evidence chain must be connected, no dangling control nodes.
func TestGraph_AcceptedControlsHaveEvidence(t *testing.T) {
maps, err := LoadControlMappings("../../data/control_mappings")
if err != nil {
t.Fatal(err)
}
ev, err := LoadEvidenceRequirements("../../data/evidence_requirements")
if err != nil {
t.Fatal(err)
}
for _, m := range maps.All {
if !m.IsAccepted() {
continue
}
if len(ev.RequiredFor(m.TargetFramework, m.TargetControl)) == 0 {
t.Errorf("accepted control %s %s has no required evidence (dangling graph node)", m.TargetFramework, m.TargetControl)
}
}
}
@@ -0,0 +1,167 @@
package ucca
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sort"
)
// LegalActStructure is the composition of one ingested eur-lex legal act — how
// many distinct articles, annexes and recitals it consists of (plus the raw
// chunk count). Backs the coverage page so the ingested corpus is not a black
// box: a developer SEES what each act actually contains, not only its name.
type LegalActStructure struct {
RegulationShort string `json:"regulation_short"`
RegulationName string `json:"regulation_name"`
Articles int `json:"articles"`
Annexes int `json:"annexes"`
Recitals int `json:"recitals"`
Chunks int `json:"chunks"`
}
const eurlexSource = "eur-lex.europa.eu"
// legalStructureCollections hold the clean eur-lex legal corpus (chunks tagged
// with chunk_scope = section | annex | recital).
var legalStructureCollections = []string{"bp_compliance_ce", "bp_compliance_datenschutz"}
// chunkScopeBucket maps a Qdrant chunk_scope to the structure field it feeds.
var chunkScopeBucket = map[string]string{"section": "articles", "annex": "annexes", "recital": "recitals"}
// CorpusStructure scrolls the eur-lex legal corpus across the legal collections
// and aggregates the per-act composition. The source filter keeps it to a few
// hundred points regardless of total corpus size. Read-only; a collection that
// fails to scroll is skipped rather than failing the whole call.
func (c *LegalRAGClient) CorpusStructure(ctx context.Context) ([]LegalActStructure, error) {
var all []qdrantScrollPoint
for _, coll := range legalStructureCollections {
pts, err := c.scrollLegalCorpus(ctx, coll)
if err != nil {
continue
}
all = append(all, pts...)
}
return aggregateStructure(all), nil
}
// aggregateStructure counts distinct article labels per (regulation, scope).
// Pure → unit-testable without a vector store.
func aggregateStructure(points []qdrantScrollPoint) []LegalActStructure {
distinct := map[string]map[string]map[string]struct{}{}
names := map[string]string{}
chunks := map[string]int{}
order := []string{}
for _, pt := range points {
reg := getString(pt.Payload, "regulation_short")
if reg == "" {
continue
}
if _, seen := names[reg]; !seen {
name := getString(pt.Payload, "regulation_name_de")
if name == "" {
name = reg
}
names[reg] = name
distinct[reg] = map[string]map[string]struct{}{}
order = append(order, reg)
}
chunks[reg]++
bucket, ok := chunkScopeBucket[getString(pt.Payload, "chunk_scope")]
article := getString(pt.Payload, "article")
if !ok || article == "" {
continue
}
if distinct[reg][bucket] == nil {
distinct[reg][bucket] = map[string]struct{}{}
}
distinct[reg][bucket][article] = struct{}{}
}
out := make([]LegalActStructure, 0, len(order))
for _, reg := range order {
out = append(out, LegalActStructure{
RegulationShort: reg,
RegulationName: names[reg],
Articles: len(distinct[reg]["articles"]),
Annexes: len(distinct[reg]["annexes"]),
Recitals: len(distinct[reg]["recitals"]),
Chunks: chunks[reg],
})
}
sort.SliceStable(out, func(i, j int) bool {
if out[i].Articles != out[j].Articles {
return out[i].Articles > out[j].Articles
}
return out[i].RegulationShort < out[j].RegulationShort
})
return out
}
// scrollLegalCorpus pages through one collection, filtered to the eur-lex legal
// corpus, returning minimal-payload points (no text/vectors).
func (c *LegalRAGClient) scrollLegalCorpus(ctx context.Context, collection string) ([]qdrantScrollPoint, error) {
var all []qdrantScrollPoint
var offset interface{}
for {
points, next, err := c.scrollLegalPage(ctx, collection, offset)
if err != nil {
return nil, err
}
all = append(all, points...)
if next == nil {
break
}
offset = next
}
return all, nil
}
// scrollLegalPage fetches one page of the filtered scroll and returns the
// points plus the next-page offset (nil when exhausted).
func (c *LegalRAGClient) scrollLegalPage(ctx context.Context, collection string, offset interface{}) ([]qdrantScrollPoint, interface{}, error) {
reqBody := map[string]interface{}{
"limit": 500,
"with_payload": map[string]interface{}{"include": []string{"regulation_short", "regulation_name_de", "chunk_scope", "article"}},
"with_vectors": false,
"filter": map[string]interface{}{
"must": []map[string]interface{}{
{"key": "source", "match": map[string]interface{}{"value": eurlexSource}},
},
},
}
if offset != nil {
reqBody["offset"] = offset
}
jsonBody, err := json.Marshal(reqBody)
if err != nil {
return nil, nil, err
}
url := fmt.Sprintf("%s/collections/%s/points/scroll", c.qdrantURL, collection)
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonBody))
if err != nil {
return nil, nil, err
}
req.Header.Set("Content-Type", "application/json")
if c.qdrantAPIKey != "" {
req.Header.Set("api-key", c.qdrantAPIKey)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, nil, fmt.Errorf("qdrant returned %d: %s", resp.StatusCode, string(body))
}
var scrollResp qdrantScrollResponse
if err := json.NewDecoder(resp.Body).Decode(&scrollResp); err != nil {
return nil, nil, err
}
return scrollResp.Result.Points, scrollResp.Result.NextPageOffset, nil
}
@@ -0,0 +1,50 @@
package ucca
import "testing"
func structPoint(reg, name, scope, article string) qdrantScrollPoint {
return qdrantScrollPoint{Payload: map[string]interface{}{
"regulation_short": reg,
"regulation_name_de": name,
"chunk_scope": scope,
"article": article,
}}
}
func TestAggregateStructure_CountsDistinctPerScope(t *testing.T) {
points := []qdrantScrollPoint{
structPoint("CRA", "Cyber Resilience Act", "section", "13"),
structPoint("CRA", "Cyber Resilience Act", "section", "13"), // duplicate article → still 1
structPoint("CRA", "Cyber Resilience Act", "section", "14"),
structPoint("CRA", "Cyber Resilience Act", "annex", "Anhang-I"),
structPoint("CRA", "Cyber Resilience Act", "annex", "Anhang-VII"),
structPoint("DORA", "", "section", "6"), // first sighting has no name →
structPoint("DORA", "", "section", "19"), // regulation_name falls back to short
structPoint("DORA", "", "recital", ""), // empty article → ignored for distinct
structPoint("", "x", "section", "1"), // missing regulation → skipped entirely
}
got := aggregateStructure(points)
if len(got) != 2 {
t.Fatalf("want 2 acts, got %d (%+v)", len(got), got)
}
// CRA has more articles → sorts first.
cra := got[0]
if cra.RegulationShort != "CRA" || cra.Articles != 2 || cra.Annexes != 2 || cra.Recitals != 0 || cra.Chunks != 5 {
t.Errorf("CRA wrong: %+v", cra)
}
dora := got[1]
if dora.RegulationShort != "DORA" || dora.Articles != 2 || dora.Chunks != 3 {
t.Errorf("DORA wrong: %+v", dora)
}
if dora.RegulationName != "DORA" {
t.Errorf("DORA name fallback failed: %q", dora.RegulationName)
}
}
func TestAggregateStructure_Empty(t *testing.T) {
if got := aggregateStructure(nil); len(got) != 0 {
t.Errorf("want empty, got %+v", got)
}
}
@@ -0,0 +1,134 @@
package ucca
import (
"fmt"
"strings"
)
const (
assessConnectedCap = 12 // cap connected norms surfaced in the assessment
assessCrossRegimeTopN = 5 // window over which "cross regime" is judged
assessReviewMargin = 0.05 // a tighter winner gap → recommend human review
)
// Assess builds the auditable explanation layer over a ranked result set:
// primary norm, the norms it connects to (citation graph), cross-regime, a
// human-review flag, the winner margin and a short reasoning string. Pure →
// unit-testable. It EXPLAINS the ranking, it does not change it. Returns nil for
// an empty result set.
func Assess(results []LegalSearchResult) *LegalAssessment {
if len(results) == 0 {
return nil
}
// Norm-level view: collapse multiple chunks of the same article/annex so the
// margin and cross-regime are judged between DISTINCT norms, not near-identical
// chunks of one norm (which would make every winner margin ~0).
norms := distinctNorms(results)
p := norms[0]
primary := primaryLabel(p)
connected := dedupStrings(p.ReferencesOut, p.ReferencesIn, p.CitationUnit)
if len(connected) > assessConnectedCap {
connected = connected[:assessConnectedCap]
}
window := norms
if len(window) > assessCrossRegimeTopN {
window = window[:assessCrossRegimeTopN]
}
regimes := make(map[string]bool)
for _, r := range window {
if r.RegulationShort != "" {
regimes[r.RegulationShort] = true
}
}
crossRegime := len(regimes) > 1
margin := 0.0
if len(norms) > 1 {
margin = norms[0].Score - norms[1].Score
}
primaryBinding := p.SourceClass == "binding_law"
humanReview := margin < assessReviewMargin || crossRegime || !primaryBinding
return &LegalAssessment{
PrimaryNorm: primary,
PrimaryRegulation: p.RegulationShort,
ConnectedNorms: connected,
CrossRegime: crossRegime,
HumanReviewFlag: humanReview,
WinnerMargin: margin,
ScoreReasoning: assessReasoning(p, margin, crossRegime, primaryBinding),
}
}
func primaryLabel(p LegalSearchResult) string {
if p.CitationUnit != "" {
return p.CitationUnit
}
if p.ArticleLabel != "" {
return p.ArticleLabel
}
return strings.TrimSpace(p.RegulationShort + " " + p.Article)
}
// assessReasoning renders a short, human-readable justification (German).
func assessReasoning(p LegalSearchResult, margin float64, crossRegime, primaryBinding bool) string {
label := primaryLabel(p)
parts := make([]string, 0, 4)
if primaryBinding {
parts = append(parts, fmt.Sprintf("Primärtreffer %s: bindendes Recht (Autorität %d).", label, p.AuthorityWeight))
} else {
parts = append(parts, fmt.Sprintf("Primärtreffer %s ist keine bindende Norm (Leitlinie/Standard) — Quelle prüfen.", label))
}
if margin > 0 {
parts = append(parts, fmt.Sprintf("Vorsprung %.2f vor #2.", margin))
}
if margin < assessReviewMargin {
parts = append(parts, "Knapper Vorsprung — Alternativtreffer prüfen.")
}
if crossRegime {
parts = append(parts, "Mehrere Regime betroffen — Querbezug prüfen.")
}
return strings.Join(parts, " ")
}
// distinctNorms collapses results that share a citation (multiple chunks of the
// same article/annex) to the first — i.e. highest-ranked — occurrence. Results
// without any citation identity are each kept, since they cannot be matched.
func distinctNorms(results []LegalSearchResult) []LegalSearchResult {
seen := make(map[string]bool, len(results))
out := make([]LegalSearchResult, 0, len(results))
for _, r := range results {
key := r.CitationUnit
if key == "" {
key = r.ArticleLabel
}
if key != "" {
if seen[key] {
continue
}
seen[key] = true
}
out = append(out, r)
}
return out
}
// dedupStrings concatenates out+in, drops empties and the excluded value, and
// returns a stable de-duplicated slice (insertion order preserved).
func dedupStrings(out, in []string, exclude string) []string {
seen := map[string]bool{exclude: true}
res := make([]string, 0, len(out)+len(in))
for _, list := range [][]string{out, in} {
for _, s := range list {
if s == "" || seen[s] {
continue
}
seen[s] = true
res = append(res, s)
}
}
return res
}
@@ -0,0 +1,112 @@
package ucca
import "testing"
func ares(reg, cu, sc string, score float64, weight int, out, in []string) LegalSearchResult {
return LegalSearchResult{
RegulationShort: reg, CitationUnit: cu, SourceClass: sc, Score: score,
AuthorityWeight: weight, ReferencesOut: out, ReferencesIn: in,
}
}
func TestAssess_Empty(t *testing.T) {
if Assess(nil) != nil {
t.Error("empty results → nil assessment")
}
}
func TestAssess_BindingPrimary_NoReview(t *testing.T) {
results := []LegalSearchResult{
ares("CRA", "Art. 13 CRA", "binding_law", 1.05, 100,
[]string{"CRA Anhang I", "Art. 14 CRA"}, []string{"Art. 12 CRA"}),
ares("CRA", "Art. 14 CRA", "binding_law", 0.80, 100, nil, nil),
}
a := Assess(results)
if a == nil {
t.Fatal("nil assessment")
}
if a.PrimaryNorm != "Art. 13 CRA" || a.PrimaryRegulation != "CRA" {
t.Errorf("primary wrong: %+v", a)
}
if len(a.ConnectedNorms) != 3 { // out(2) + in(1), self excluded, deduped
t.Errorf("connected norms: %v", a.ConnectedNorms)
}
if a.CrossRegime {
t.Error("single regime must not be cross-regime")
}
if a.WinnerMargin < 0.24 || a.WinnerMargin > 0.26 {
t.Errorf("margin = %v, want ~0.25", a.WinnerMargin)
}
if a.HumanReviewFlag {
t.Error("clean binding + healthy margin + single regime → no review")
}
}
func TestAssess_CrossRegimeFlagsReview(t *testing.T) {
a := Assess([]LegalSearchResult{
ares("CRA", "Art. 13 CRA", "binding_law", 1.05, 100, nil, nil),
ares("DORA", "Art. 6 DORA", "binding_law", 0.70, 100, nil, nil),
})
if !a.CrossRegime || !a.HumanReviewFlag {
t.Errorf("cross-regime must flag review: %+v", a)
}
}
func TestAssess_NonBindingFlagsReview(t *testing.T) {
a := Assess([]LegalSearchResult{
ares("ENISA", "ENISA SBOM", "supervisory_guidance", 0.90, 70, nil, nil),
ares("ENISA", "ENISA X", "supervisory_guidance", 0.40, 70, nil, nil),
})
if !a.HumanReviewFlag {
t.Error("non-binding primary → review")
}
}
func TestAssess_TightMarginFlagsReview(t *testing.T) {
a := Assess([]LegalSearchResult{
ares("CRA", "Art. 13 CRA", "binding_law", 1.00, 100, nil, nil),
ares("CRA", "Art. 14 CRA", "binding_law", 0.98, 100, nil, nil),
})
if a.WinnerMargin >= 0.05 || !a.HumanReviewFlag {
t.Errorf("tight margin → review: %+v", a)
}
}
func TestAssess_MarginIsNormLevelNotChunkLevel(t *testing.T) {
// Two near-identical chunks of the SAME norm at the top, then a distinct norm.
results := []LegalSearchResult{
ares("CRA", "Art. 13 CRA", "binding_law", 1.050, 100, []string{"CRA Anhang I"}, nil),
ares("CRA", "Art. 13 CRA", "binding_law", 1.049, 100, nil, nil), // same norm
ares("CRA", "Art. 14 CRA", "binding_law", 0.800, 100, nil, nil),
}
a := Assess(results)
if a.WinnerMargin < 0.24 || a.WinnerMargin > 0.26 { // Art.13 vs Art.14, not chunk vs chunk
t.Errorf("margin must be norm-level (~0.25), got %v", a.WinnerMargin)
}
if a.HumanReviewFlag {
t.Error("healthy norm-level margin → no review")
}
}
func TestDistinctNorms(t *testing.T) {
got := distinctNorms([]LegalSearchResult{
{CitationUnit: "Art. 13 CRA"},
{CitationUnit: "Art. 13 CRA"}, // duplicate norm → collapsed
{CitationUnit: "Art. 14 CRA"},
{CitationUnit: ""}, // no identity → kept
{CitationUnit: ""}, // no identity → kept
})
if len(got) != 4 {
t.Errorf("want 4 (2 distinct + 2 unidentified), got %d", len(got))
}
}
func TestDedupStrings(t *testing.T) {
got := dedupStrings([]string{"a", "b", "", "a"}, []string{"b", "c"}, "self")
if len(got) != 3 || got[0] != "a" || got[1] != "b" || got[2] != "c" {
t.Errorf("dedup: %v", got)
}
if len(dedupStrings([]string{"self"}, nil, "self")) != 0 {
t.Error("excluded value must be dropped")
}
}
@@ -20,6 +20,7 @@ type LegalRAGClient struct {
httpClient *http.Client
textIndexEnsured map[string]bool
hybridEnabled bool
graphEnabled bool
}
// NewLegalRAGClient creates a new Legal RAG client using Ollama bge-m3 embeddings.
@@ -38,6 +39,11 @@ func NewLegalRAGClient() *LegalRAGClient {
}
hybridEnabled := os.Getenv("RAG_HYBRID_SEARCH") != "false"
// Graph-Expansion ist OPT-IN: kein gemessener Rang-Nutzen ggue. der Binding-Augmentation,
// +1 Qdrant-Call/Suche, Flutungsrisiko ueber Reverse-Kanten. Bleibt als Recall-Sicherheitsnetz
// fuer spaetere Luecken (RAG_GRAPH_EXPANSION=true). Die Graph-Kanten werden in der Response
// zur Begruendung/Vollstaendigkeit genutzt, nicht zur Pool-Expansion (Default).
graphEnabled := os.Getenv("RAG_GRAPH_EXPANSION") == "true"
return &LegalRAGClient{
qdrantURL: qdrantURL,
@@ -47,6 +53,7 @@ func NewLegalRAGClient() *LegalRAGClient {
collection: "bp_compliance_ce",
textIndexEnsured: make(map[string]bool),
hybridEnabled: hybridEnabled,
graphEnabled: graphEnabled,
httpClient: &http.Client{
Timeout: 60 * time.Second,
},
@@ -93,6 +100,29 @@ func (c *LegalRAGClient) searchInternal(ctx context.Context, collection string,
hits = denseHits
}
// Stratified: den binding_law-Pool ERGAENZEN (nicht ersetzen), damit die Pflichtquelle
// immer Kandidat ist — Guidance bleibt als Auslegungskontext erhalten. Best-effort:
// Fehler beim Binding-Query degradieren still auf den semantischen Pool.
if bindingHits, bErr := c.searchBinding(ctx, collection, embedding, topK); bErr == nil {
hits = mergeDedupHits(hits, bindingHits)
}
// Control-Augmentation: bei expliziter Umsetzungsfrage einen tiefen dense-Pool ziehen und
// nur die Control-Pool-Rollen behalten — so werden NIST/CRA-Anhang (dense rank ~8-9, unter
// dem kleinen top-K) Kandidaten. Re-Rank/applyControlRoles ordnen sie danach.
if queryWantsControls(query) {
if controlHits, cErr := c.searchControls(ctx, collection, embedding); cErr == nil {
hits = mergeDedupHits(hits, controlHits)
}
}
// Graph-Augmentation: verbundene Normen (references_out/in) der Top-Hits ueber die
// praezise Zitations-Kante in den Pool ziehen — z.B. Art. 13 CRA zieht Anhang I (die
// eigentliche Pflichtquelle). Pool-Augmentation only; Re-Rank + topK bleiben.
if c.graphEnabled {
hits = c.expandViaGraph(ctx, collection, hits)
}
results := make([]LegalSearchResult, len(hits))
for i, hit := range hits {
// Legal-Metadaten nach rag_reingest_spec.md §2: bevorzugt die normalisierten Felder
@@ -121,12 +151,54 @@ func (c *LegalRAGClient) searchInternal(ctx context.Context, collection string,
Pages: getIntSlice(hit.Payload, "pages"),
SourceURL: getString(hit.Payload, "source"),
Score: hit.Score,
AuthorityWeight: getInt(hit.Payload, "authority_weight"),
SourceClass: getString(hit.Payload, "source_class"),
Jurisdiction: getString(hit.Payload, "jurisdiction"),
CitationUnit: getString(hit.Payload, "citation_unit"),
ReferencesOut: getStringSlice(hit.Payload, "references_out"),
ReferencesIn: getStringSlice(hit.Payload, "references_in"),
Superseded: getString(hit.Payload, "status") == "superseded",
}
}
// Authority-aware Re-Ranking: bindendes Recht der passenden Jurisdiktion/Domaene nach
// oben, Guidance/Fremdrecht/Off-Domain runter (nichts wird geloescht). Reihenfolge only,
// Response-Schema unveraendert. Score traegt den Authority-Score, damit nachgelagerte
// Multi-Collection-Merges (Advisor) die Ordnung bewahren.
results = rerankByAuthority(query, results)
// Control-Diversity: auf einer Umsetzungsfrage darf impl_guidance (ENISA) Top-1 bleiben,
// aber die Top-K soll mindestens eine binding operational_requirement (CRA Anhang I) und
// einen control_standard (NIST/ISO) zeigen, falls im Pool — Quellenarten sichtbar machen
// statt sie kuenstlich auf Top-1 zu heben. Nur Reihenfolge, vor der Truncation.
if queryWantsControls(query) {
results = ensureControlDiversity(results, topK)
}
if topK > 0 && len(results) > topK {
results = results[:topK]
}
return results, nil
}
// mergeDedupHits concatenates two hit lists, keeping the first occurrence of each point ID.
func mergeDedupHits(primary, extra []qdrantSearchHit) []qdrantSearchHit {
seen := make(map[string]bool, len(primary)+len(extra))
out := make([]qdrantSearchHit, 0, len(primary)+len(extra))
for _, list := range [][]qdrantSearchHit{primary, extra} {
for _, h := range list {
id := fmt.Sprint(h.ID)
if seen[id] {
continue
}
seen[id] = true
out = append(out, h)
}
}
return out
}
// FormatLegalContextForPrompt formats the legal context for inclusion in an LLM prompt.
func (c *LegalRAGClient) FormatLegalContextForPrompt(lc *LegalContext) string {
if lc == nil || len(lc.Results) == 0 {
@@ -0,0 +1,162 @@
package ucca
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sort"
)
// Graph-augmented retrieval: when a top hit cites an annex/article (references_out)
// or is cited by one (references_in), pull that connected norm into the candidate
// pool via the PRECISE citation graph instead of hoping semantic search surfaces
// it. E.g. a hit on CRA Art. 13 pulls in CRA Anhang I (the actual requirement).
// Pool-augmentation only — authority re-rank + topK slice still apply, so the
// response schema is unchanged.
const (
graphSeedCount = 5 // only the top hits seed the expansion
graphMaxExpand = 15 // cap connected norms pulled in (avoid pool explosion)
graphHopPenalty = 0.05 // a one-hop neighbour ranks just below its seed
)
// expandViaGraph augments hits with the norms they cite and the norms that cite
// them. Best-effort: on any error (or nothing to expand) the original hits are
// returned unchanged.
func (c *LegalRAGClient) expandViaGraph(ctx context.Context, collection string, hits []qdrantSearchHit) []qdrantSearchHit {
if len(hits) == 0 {
return hits
}
present := make(map[string]bool, len(hits))
for _, h := range hits {
if cu := getString(h.Payload, "citation_unit"); cu != "" {
present[cu] = true
}
}
seeds := hits
if len(seeds) > graphSeedCount {
seeds = seeds[:graphSeedCount]
}
// Forward edges only (references_out = the detail a hit explicitly points to,
// e.g. Art. 13 → Anhang I). Reverse (references_in) has high fan-out for popular
// annexes (Anhang I is cited by 23 articles) → pool flooding; it is surfaced as
// connected-norm metadata in the Phase 2 response instead of expanding the pool.
want := make(map[string]float64) // connected citation_unit -> best seeding score
for _, h := range seeds {
for _, cu := range getStringSlice(h.Payload, "references_out") {
if cu == "" || present[cu] {
continue
}
if s, ok := want[cu]; !ok || h.Score > s {
want[cu] = h.Score
}
}
}
if len(want) == 0 {
return hits
}
units := topByScore(want, graphMaxExpand)
fetched, err := c.fetchByCitationUnits(ctx, collection, units)
if err != nil || len(fetched) == 0 {
return hits
}
neighbours := make([]qdrantSearchHit, 0, len(fetched))
for cu, pt := range fetched {
neighbours = append(neighbours, qdrantSearchHit{ID: pt.ID, Score: want[cu] - graphHopPenalty, Payload: pt.Payload})
}
return mergeDedupHits(hits, neighbours)
}
// topByScore returns up to n keys with the highest values. Deterministic: ties
// broken by the key string so the cap is stable across runs.
func topByScore(m map[string]float64, n int) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
if m[keys[i]] != m[keys[j]] {
return m[keys[i]] > m[keys[j]]
}
return keys[i] < keys[j]
})
if len(keys) > n {
keys = keys[:n]
}
return keys
}
// fetchByCitationUnits loads one representative point (the first chunk) per
// citation_unit from the given collection.
func (c *LegalRAGClient) fetchByCitationUnits(ctx context.Context, collection string, units []string) (map[string]qdrantScrollPoint, error) {
should := make([]map[string]interface{}, 0, len(units))
for _, cu := range units {
should = append(should, map[string]interface{}{"key": "citation_unit", "match": map[string]interface{}{"value": cu}})
}
reqBody := map[string]interface{}{
"limit": len(units) * 4,
"with_payload": true,
"with_vectors": false,
"filter": map[string]interface{}{"should": should},
}
jsonBody, err := json.Marshal(reqBody)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s/collections/%s/points/scroll", c.qdrantURL, collection)
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonBody))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
if c.qdrantAPIKey != "" {
req.Header.Set("api-key", c.qdrantAPIKey)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("qdrant scroll returned %d: %s", resp.StatusCode, string(body))
}
var scrollResp qdrantScrollResponse
if err := json.NewDecoder(resp.Body).Decode(&scrollResp); err != nil {
return nil, err
}
out := make(map[string]qdrantScrollPoint, len(units))
for _, pt := range scrollResp.Result.Points {
cu := getString(pt.Payload, "citation_unit")
if cu != "" {
if _, seen := out[cu]; !seen {
out[cu] = pt
}
}
}
return out, nil
}
// getStringSlice extracts a []string from a Qdrant payload list field
// (references_out / references_in are stored as JSON arrays of strings).
func getStringSlice(m map[string]interface{}, key string) []string {
v, ok := m[key]
if !ok {
return nil
}
arr, ok := v.([]interface{})
if !ok {
return nil
}
out := make([]string, 0, len(arr))
for _, item := range arr {
if s, ok := item.(string); ok {
out = append(out, s)
}
}
return out
}
@@ -0,0 +1,89 @@
package ucca
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestGetStringSlice(t *testing.T) {
m := map[string]interface{}{
"refs": []interface{}{"a", "b", 3, "c"}, // non-strings are skipped
"str": "not-a-list",
}
got := getStringSlice(m, "refs")
if len(got) != 3 || got[0] != "a" || got[2] != "c" {
t.Errorf("refs: %v", got)
}
if getStringSlice(m, "missing") != nil {
t.Error("missing key should be nil")
}
if getStringSlice(m, "str") != nil {
t.Error("non-list should be nil")
}
}
func TestTopByScore_DeterministicCap(t *testing.T) {
m := map[string]float64{"x": 0.5, "y": 0.9, "z": 0.5, "w": 0.7}
got := topByScore(m, 2)
if len(got) != 2 || got[0] != "y" || got[1] != "w" {
t.Errorf("want [y w], got %v", got)
}
all := topByScore(m, 10)
if all[2] != "x" || all[3] != "z" { // tie 0.5 broken by key string
t.Errorf("tie-break not deterministic: %v", all)
}
}
func TestExpandViaGraph_NoSeedsOrRefs(t *testing.T) {
c := &LegalRAGClient{} // nil httpClient → must not be called on these paths
if out := c.expandViaGraph(context.Background(), "x", nil); out != nil {
t.Error("empty hits should return nil")
}
hits := []qdrantSearchHit{{ID: 1, Score: 0.8, Payload: map[string]interface{}{"citation_unit": "Art. 1 CRA"}}}
if out := c.expandViaGraph(context.Background(), "x", hits); len(out) != 1 {
t.Errorf("no references → unchanged, got %d", len(out))
}
}
func TestExpandViaGraph_PullsConnectedNorm(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"result": map[string]interface{}{
"points": []map[string]interface{}{
{"id": 99, "payload": map[string]interface{}{
"citation_unit": "CRA Anhang I", "chunk_text": "Sicherheitsanforderungen",
"source_class": "binding_law", "authority_weight": 100, "regulation_short": "CRA",
}},
},
"next_page_offset": nil,
},
})
}))
defer srv.Close()
c := &LegalRAGClient{qdrantURL: srv.URL, httpClient: srv.Client()}
hits := []qdrantSearchHit{
{ID: 1, Score: 0.70, Payload: map[string]interface{}{
"citation_unit": "Art. 13 CRA", "references_out": []interface{}{"CRA Anhang I"},
}},
}
out := c.expandViaGraph(context.Background(), "bp_compliance_ce", hits)
if len(out) != 2 {
t.Fatalf("want 2 hits (seed + connected annex), got %d", len(out))
}
var found *qdrantSearchHit
for i := range out {
if getString(out[i].Payload, "citation_unit") == "CRA Anhang I" {
found = &out[i]
}
}
if found == nil {
t.Fatal("connected norm CRA Anhang I was not pulled into the pool")
}
if found.Score < 0.64 || found.Score > 0.66 { // 0.70 seed 0.05 hop penalty
t.Errorf("connected score = %v, want ~0.65", found.Score)
}
}
@@ -185,6 +185,55 @@ func (c *LegalRAGClient) searchDense(ctx context.Context, collection string, emb
searchReq.Filter = &qdrantFilter{Should: conditions}
}
return c.doPointsSearch(ctx, collection, searchReq)
}
// searchBinding fetches the top binding_law hits (authority-stratified pool) so the
// obligation source is always a candidate even when guidance dominates semantically.
// It AUGMENTS the semantic pool — guidance is preserved as interpretation context.
func (c *LegalRAGClient) searchBinding(ctx context.Context, collection string, embedding []float64, topK int) ([]qdrantSearchHit, error) {
searchReq := qdrantSearchRequest{
Vector: embedding,
Limit: topK,
WithPayload: true,
Filter: &qdrantFilter{Must: []qdrantCondition{
{Key: "source_class", Match: qdrantMatch{Value: "binding_law"}},
}},
}
return c.doPointsSearch(ctx, collection, searchReq)
}
// controlPoolDepth is how deep the dense control pull reaches. Measured: for an EU-cyber
// control query the relevant control sources sit at dense rank ~8-9 (NIST, CRA Annex), far
// below the client's small top-K — so a fixed dense depth of 60 reliably surfaces them.
const controlPoolDepth = 60
// searchControls fetches a DEEP dense pool and keeps only the control-pool roles, so control
// sources that the small top-K (hybrid) search misses become candidates on an implementation
// question. Role is derived in code (no source_role tag needed). AUGMENTS the pool — the
// caller gates it on control-intent.
func (c *LegalRAGClient) searchControls(ctx context.Context, collection string, embedding []float64) ([]qdrantSearchHit, error) {
searchReq := qdrantSearchRequest{
Vector: embedding,
Limit: controlPoolDepth,
WithPayload: true,
}
hits, err := c.doPointsSearch(ctx, collection, searchReq)
if err != nil {
return nil, err
}
kept := make([]qdrantSearchHit, 0, len(hits))
for _, h := range hits {
if isControlPoolRole(controlRoleOf(h.Payload)) {
kept = append(kept, h)
}
}
return kept, nil
}
// doPointsSearch issues a POST /points/search and decodes the hits.
func (c *LegalRAGClient) doPointsSearch(ctx context.Context, collection string, searchReq qdrantSearchRequest) ([]qdrantSearchHit, error) {
jsonBody, err := json.Marshal(searchReq)
if err != nil {
return nil, fmt.Errorf("failed to marshal search request: %w", err)
@@ -0,0 +1,135 @@
package ucca
import "testing"
func intentRes(reg, sourceClass string, sem float64, weight int) LegalSearchResult {
return LegalSearchResult{
RegulationShort: reg, SourceClass: sourceClass, Score: sem,
AuthorityWeight: weight, Jurisdiction: "EU",
}
}
func TestQueryWantsGuidance(t *testing.T) {
wants := []string{
"Was empfiehlt der EDPB zum DSB?",
"Was sagt die ENISA zu Security Updates?",
"laut DSK ...",
"Orientierungshilfe zur DSFA",
"Welche BSI-Empfehlung gilt?",
"Auslegung der Aufsichtsbehörde",
}
plain := []string{
"Ab wann braucht man einen Datenschutzbeauftragten?",
"Welche Anforderungen bestehen an Security Updates?",
}
for _, q := range wants {
if !queryWantsGuidance(q) {
t.Errorf("should detect interpretation intent: %q", q)
}
}
for _, q := range plain {
if queryWantsGuidance(q) {
t.Errorf("should NOT detect intent (norm question): %q", q)
}
}
}
func TestRerank_NormQuestion_BindingStaysTop(t *testing.T) {
// No intent signal → binding wins even though guidance is semantically higher.
results := []LegalSearchResult{
intentRes("EDPB DPO", "supervisory_guidance", 0.64, 70),
intentRes("DSGVO", "binding_law", 0.58, 100),
}
out := rerankByAuthority("Ab wann braucht man einen Datenschutzbeauftragten?", results)
if out[0].SourceClass != "binding_law" {
t.Errorf("norm question: binding must stay Top-1, got %s", out[0].SourceClass)
}
}
func TestRerank_InterpretationQuestion_GuidanceMayWin(t *testing.T) {
// Explicit intent + guidance semantically competitive → guidance wins.
results := []LegalSearchResult{
intentRes("EDPB DPO", "supervisory_guidance", 0.64, 70),
intentRes("DSGVO", "binding_law", 0.58, 100),
}
out := rerankByAuthority("Was empfiehlt der EDPB zum Datenschutzbeauftragten?", results)
if out[0].SourceClass != "supervisory_guidance" {
t.Errorf("interpretation question: guidance should win Top-1, got %s", out[0].SourceClass)
}
}
func TestRerank_OffTopicGuidance_BlockedByGuard(t *testing.T) {
// Intent present, but guidance semantic is far below the best binding hit →
// the margin guard keeps binding on top (no off-topic guideline override).
results := []LegalSearchResult{
intentRes("EDPB DPO", "supervisory_guidance", 0.40, 70),
intentRes("DSGVO", "binding_law", 0.58, 100),
}
out := rerankByAuthority("Was empfiehlt der EDPB zum Datenschutzbeauftragten?", results)
if out[0].SourceClass != "binding_law" {
t.Errorf("off-topic guidance must not win even with intent, got %s", out[0].SourceClass)
}
}
func TestQueryWantsControls(t *testing.T) {
wants := []string{
"Welche Controls passen zu Security Updates?",
"Welche Maßnahmen sollten wir umsetzen?",
"Wie härten wir den Server ab?",
"Gibt es NIST-Controls dafür?",
"OWASP Best Practice für Logging?",
"BSI Grundschutz Bausteine",
}
plain := []string{
"Welche Anforderungen bestehen an Security Updates?",
"Ab wann braucht man einen Datenschutzbeauftragten?",
}
for _, q := range wants {
if !queryWantsControls(q) {
t.Errorf("should detect control/implementation intent: %q", q)
}
}
for _, q := range plain {
if queryWantsControls(q) {
t.Errorf("should NOT detect control intent (norm question): %q", q)
}
}
}
func TestRerank_ControlQuestion_OperationalReqTop(t *testing.T) {
// User priority for implementation questions: operational_requirement (binding concrete,
// CRA Anhang I) > control_standard (NIST). Both are in the control-pool; op_req wins.
results := []LegalSearchResult{
{RegulationShort: "NIST SP 800-82r3", ArticleLabel: "AU-8", SourceClass: "technical_standard", AuthorityWeight: 80, Jurisdiction: "EU", Score: 0.60},
{RegulationShort: "CRA", ArticleLabel: "CRA Anhang I", Category: "regulation", Score: 0.58},
}
out := rerankByAuthority("Welche Controls und Massnahmen passen zu Security Updates?", results)
if out[0].RegulationShort != "CRA" {
t.Errorf("operational_requirement (CRA Anhang I) should be Top-1 over control_standard, got %q", out[0].RegulationShort)
}
}
func TestRerank_NormQuestion_BindingOverStandard(t *testing.T) {
// "Anforderungen" → no control intent → binding obligation stays Top-1 over the standard.
results := []LegalSearchResult{
intentRes("NIST SP 800-82", "technical_standard", 0.62, 80),
intentRes("CRA", "binding_law", 0.58, 100),
}
out := rerankByAuthority("Welche Anforderungen bestehen an Security Updates?", results)
if out[0].SourceClass != "binding_law" {
t.Errorf("norm question: binding must stay Top-1 over standard, got %s", out[0].SourceClass)
}
}
func TestRerank_ControlQuestion_PoolBeatsBareObligation(t *testing.T) {
// A control-pool source (NIST control_standard) outranks an abstract obligation with no
// domain/topic advantage, because the implementation intent boosts the control-pool.
results := []LegalSearchResult{
{RegulationShort: "NIST SP 800-82r3", ArticleLabel: "AU-8", SourceClass: "technical_standard", AuthorityWeight: 80, Jurisdiction: "EU", Score: 0.55},
{RegulationShort: "XYZ", ArticleLabel: "Art. 5 XYZ", Category: "regulation", Score: 0.58},
}
out := rerankByAuthority("Welche Controls und Massnahmen passen zu Security Updates?", results)
if out[0].RegulationShort != "NIST SP 800-82r3" {
t.Errorf("control_standard should beat a bare abstract obligation on a control question, got %q", out[0].RegulationShort)
}
}
@@ -225,6 +225,18 @@ func getIntSlice(m map[string]interface{}, key string) []int {
return result
}
func getInt(m map[string]interface{}, key string) int {
if v, ok := m[key]; ok {
switch n := v.(type) {
case float64:
return int(n)
case int:
return n
}
}
return 0
}
func contains(slice []string, item string) bool {
for _, s := range slice {
if s == item {
@@ -0,0 +1,30 @@
package ucca
import "testing"
// A superseded alt-source must rank below the same result when it is NOT
// superseded (the eu-v1 norm), but only demoted — the penalty is finite, so it
// stays in the pool and remains findable for history/transition questions.
func TestAuthorityScore_SupersededIsDemotedNotRemoved(t *testing.T) {
fresh := LegalSearchResult{
Score: 0.65, SourceClass: "binding_law", AuthorityWeight: 100,
Jurisdiction: "EU", RegulationShort: "CRA", Article: "13",
}
old := fresh
old.Superseded = true
sFresh := authorityScore("CRA Sicherheitsupdates Hersteller", fresh, "", false)
sOld := authorityScore("CRA Sicherheitsupdates Hersteller", old, "", false)
if sOld >= sFresh {
t.Errorf("superseded must score lower: fresh=%.3f superseded=%.3f", sFresh, sOld)
}
gap := sFresh - sOld
if gap < supersededPenalty-0.001 || gap > supersededPenalty+0.001 {
t.Errorf("demotion should equal supersededPenalty (%.2f), got %.3f", supersededPenalty, gap)
}
// Still a positive, finite score → present in the pool, not hidden.
if sOld <= -1 {
t.Errorf("superseded score collapsed (%.3f) — must remain findable", sOld)
}
}
@@ -399,8 +399,9 @@ func TestHybridSearch_UsesQueryAPI(t *testing.T) {
return
}
// Fallback: should not reach dense search
t.Error("Unexpected dense search call when hybrid succeeded")
// /points/search is now the stratified binding-law augmentation query (it AUGMENTS
// the hybrid pool, it is not a dense fallback). Return empty so the hybrid hit
// remains the sole result for this test.
json.NewEncoder(w).Encode(qdrantSearchResponse{Result: []qdrantSearchHit{}})
}))
defer qdrantMock.Close()
@@ -446,6 +447,59 @@ func TestHybridSearch_UsesQueryAPI(t *testing.T) {
}
}
// TestSearch_StratifiedBindingRerank verifies that the binding-law pool augments the
// semantic pool and that authority re-ranking lifts binding law above higher-semantic guidance.
func TestSearch_StratifiedBindingRerank(t *testing.T) {
ollamaMock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(ollamaEmbeddingResponse{Embedding: make([]float64, 1024)})
}))
defer ollamaMock.Close()
qdrantMock := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/index") {
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"result":{"status":"completed"}}`))
return
}
if strings.Contains(r.URL.Path, "/points/query") {
json.NewEncoder(w).Encode(qdrantQueryResponse{Result: []qdrantSearchHit{
{ID: "g1", Score: 0.72, Payload: map[string]interface{}{
"chunk_text": "ENISA guidance", "regulation_short": "ENISA",
"article_label": "ENISA CRA Mapping", "source_class": "supervisory_guidance",
"authority_weight": float64(70), "jurisdiction": "EU",
}},
}})
return
}
// /points/search = stratified binding-law pool (source_class=binding_law)
json.NewEncoder(w).Encode(qdrantSearchResponse{Result: []qdrantSearchHit{
{ID: "b1", Score: 0.66, Payload: map[string]interface{}{
"chunk_text": "CRA Anhang I requirement", "regulation_short": "CRA",
"article_label": "CRA Anhang I", "source_class": "binding_law",
"authority_weight": float64(100), "jurisdiction": "EU",
}},
}})
}))
defer qdrantMock.Close()
client := &LegalRAGClient{
qdrantURL: qdrantMock.URL, ollamaURL: ollamaMock.URL, embeddingModel: "bge-m3",
collection: "bp_compliance_ce", textIndexEnsured: make(map[string]bool),
hybridEnabled: true, httpClient: http.DefaultClient,
}
results, err := client.Search(context.Background(), "Was gilt hier?", nil, 5)
if err != nil {
t.Fatalf("search failed: %v", err)
}
if len(results) != 2 {
t.Fatalf("expected 2 merged results (guidance + binding), got %d", len(results))
}
if results[0].RegulationShort != "CRA" {
t.Errorf("binding CRA must rank first over higher-semantic guidance, got %q", results[0].RegulationShort)
}
}
func TestHybridSearch_FallbackToDense(t *testing.T) {
var requestedPaths []string
@@ -20,6 +20,38 @@ type LegalSearchResult struct {
Pages []int `json:"pages,omitempty"`
SourceURL string `json:"source_url"`
Score float64 `json:"score"`
// Interne Felder fuer das Authority-Re-Ranking (Phase 1) — NICHT serialisiert
// (json:"-"), daher kein Contract-Change. Aus dem Qdrant-Payload befuellt und nur
// fuer die Sortierung in rerankByAuthority verwendet.
AuthorityWeight int `json:"-"`
SourceClass string `json:"-"`
Jurisdiction string `json:"-"`
// Zitations-Graph (Phase 2) — intern, speist nur die Assessment-Berechnung
// (verbundene Normen, Begruendung). Pro-Result-Schema bleibt eingefroren.
CitationUnit string `json:"-"`
ReferencesOut []string `json:"-"`
ReferencesIn []string `json:"-"`
// Supersede-Status (status="superseded", use_for_primary=false) — Alt-Quelle,
// die fuer Default-Fragen demoted wird (nicht versteckt; fuer Historie auffindbar).
Superseded bool `json:"-"`
}
// LegalAssessment is the auditable explanation layer over a ranked result set:
// which norm is primary, which norms connect to it via the citation graph,
// whether the answer crosses regulatory regimes, and whether a human should
// review. Computed from the already-ranked results — it EXPLAINS retrieval, it
// does not change it (graph edges for reasoning/completeness, not pool-expansion).
type LegalAssessment struct {
PrimaryNorm string `json:"primary_norm"`
PrimaryRegulation string `json:"primary_regulation"`
ConnectedNorms []string `json:"connected_norms"`
CrossRegime bool `json:"cross_regime"`
HumanReviewFlag bool `json:"human_review_flag"`
WinnerMargin float64 `json:"winner_margin"`
ScoreReasoning string `json:"score_reasoning"`
}
// LegalContext represents aggregated legal context for an assessment.
@@ -13,6 +13,7 @@ the map). Once the tabs are the source of truth, B18's v1 path retires.
from __future__ import annotations
import asyncio
import logging
from compliance.services.specialist_agents import REGISTRY, AgentInput
@@ -27,6 +28,8 @@ logger = logging.getLogger(__name__)
# topic key (matches state["doc_texts"]) -> registered agent_id
_TOPIC_AGENTS: dict[str, str] = {
"impressum": "impressum",
"agb": "agb", # v2: AGBAgent mit decision_method-Routing (71% FP -> ~0)
"dse": "dse", # v3: 4-Layer (Regex-Boost/Keyword/BGE-M3-Recall/Semantic)
}
_MIN_TEXT = 100
@@ -112,14 +115,17 @@ async def run_agent_outputs(state: dict) -> None:
)
outputs: dict[str, dict] = state.get("agent_outputs") or {}
for topic, agent_id in _TOPIC_AGENTS.items():
async def _run_one(topic: str, agent_id: str):
"""Einen Topic-Agent laufen lassen + sein Tab-Event sofort emittieren
(Zwischenbefund). Fängt eigene Fehler ein Agent reißt den Run nicht ab."""
text = (doc_texts.get(topic) or "").strip()
if len(text) < _MIN_TEXT:
continue
return None
agent = REGISTRY.get(agent_id)
if agent is None:
logger.warning("agent_outputs: agent '%s' not registered", agent_id)
continue
return None
try:
out = await agent.evaluate(AgentInput(
doc_type=topic,
@@ -128,15 +134,25 @@ async def run_agent_outputs(state: dict) -> None:
company_name=company_name,
origin_domain=origin_domain,
))
outputs[topic] = out.model_dump(mode="json")
emit(check_id, {"type": "topic", "topic": topic,
"output": outputs[topic]})
dump = out.model_dump(mode="json")
emit(check_id, {"type": "topic", "topic": topic, "output": dump})
logger.info(
"agent_outputs[%s]: %d findings, confidence %.2f",
topic, len(out.findings), out.confidence,
)
return topic, dump
except Exception as e: # noqa: BLE001 — best-effort, never break the run
logger.warning("agent_outputs[%s] failed: %s", topic, e)
return None
# Topic-Agenten laufen NEBENLÄUFIG (ihre Embedding-/LLM-Waits überlappen) und
# füllen ihren Tab via SSE, sobald sie fertig sind — kein Warten aufs Schlusslicht.
results = await asyncio.gather(
*(_run_one(topic, agent_id) for topic, agent_id in _TOPIC_AGENTS.items())
)
for r in results:
if r:
outputs[r[0]] = r[1]
if outputs:
state["agent_outputs"] = outputs
@@ -0,0 +1,82 @@
"""Pruefer-Library — gemeinsames Interface. Siehe docs platform_checker_matrix.md.
Ein Checker prueft EINEN Control gegen EIN Dokument und liefert: vorhanden / fehlt
/ unklar (+ Evidence). Module (DSE/Impressum/AGB/...) liefern nur Control-Metadaten
ueber `ControlSpec` (verification_method + decision_method + checker-spezifische
Config); die Engine routet method-agnostisch zum passenden Checker.
Ziel der Plattform: 14k Controls -> 7 Pruefertypen -> wenige Pruefer. Ein neues
Modul wird damit ein Klassifizierungs-, kein Forschungsproblem.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Optional, Protocol, runtime_checkable
class VerificationMethod:
"""Achse 1 — WELCHER Pruefer-Typ (Kategorie)."""
FIELD = "FIELD"
REFERENCE = "REFERENCE"
BEHAVIOR = "BEHAVIOR"
PRESENTATION = "PRESENTATION"
CONTENT = "CONTENT"
PROCESS = "PROCESS"
TECHNICAL = "TECHNICAL"
CONTRACTUAL = "CONTRACTUAL"
class DecisionMethod:
"""Achse 2 — WIE entschieden wird (konkreter Mechanismus)."""
REGEX = "REGEX"
EMBEDDING = "EMBEDDING"
LLM = "LLM"
LINK_RESOLVER = "LINK_RESOLVER"
PLAYWRIGHT = "PLAYWRIGHT"
AUDIT = "AUDIT"
SCANNER = "SCANNER"
@dataclass
class ControlSpec:
"""Routing-Metadaten + checker-spezifische Config eines Controls. Module fuellen
nur die fuer ihren decision_method relevanten Felder."""
control_id: str
verification_method: str
decision_method: str
label: str = ""
severity: str = "MEDIUM"
patterns: list[str] = field(default_factory=list) # FIELD/REGEX, REFERENCE
paraphrases: list[str] = field(default_factory=list) # CONTENT (EMBEDDING/LLM)
embed_threshold: Optional[float] = None # EMBEDDING (per-Control)
topic_regex: str = "" # LLM: Section-Retrieval
question: str = "" # LLM: Pruef-Frage
extra: dict[str, Any] = field(default_factory=dict)
@dataclass
class DocContext:
"""Das zu pruefende Artefakt. `text` = Volltext; `url`/`rendered` fuer
PRESENTATION/BEHAVIOR (Playwright) spaeter."""
text: str = ""
url: str = ""
rendered: Any = None
@dataclass
class CheckResult:
present: Optional[bool] # True=erfuellt, False=fehlt, None=unklar (fail-safe)
evidence: str = ""
confidence: float = 0.0
source: str = "" # welcher Pruefer/Tier geantwortet hat
detail: dict[str, Any] = field(default_factory=dict)
@runtime_checkable
class Checker(Protocol):
"""Alle Pruefer haben dieselbe Signatur -> die Engine ist method-agnostisch und
routet nur ueber ctrl.verification_method / ctrl.decision_method."""
verification_method: str
async def check(self, ctrl: ControlSpec, doc: DocContext) -> CheckResult:
...
@@ -0,0 +1,51 @@
"""CONTENT-Pruefer / decision_method=EMBEDDING.
Ist die Pflicht SEMANTISCH im Text vorhanden? Max-Cosinus (Doc-Chunks x Control-
Paraphrasen) >= per-Control-Schwelle. Deterministisch (festes Embedding-Modell)
und gecacht. Rettet Recall-FP (Klausel da, anders formuliert).
Faellt der Embedding-Service aus, liefert der Checker present=None (unklar) der
Aufrufer behaelt dann das Keyword-Ergebnis (kein Hang, kein Crash).
(Validiert an AGB: 17 Items, per-Item-Schwelle, 0 Fehl-Rescue.)
"""
from __future__ import annotations
import asyncio
import logging
from .base import CheckResult, ControlSpec, DocContext, VerificationMethod
logger = logging.getLogger(__name__)
# Paraphrasen-Vektoren je Control einmal einbetten + cachen.
_PARA_CACHE: dict[str, list] = {}
class EmbeddingChecker:
verification_method = VerificationMethod.CONTENT
async def check(self, ctrl: ControlSpec, doc: DocContext) -> CheckResult:
text = doc.text or ""
paras = ctrl.paraphrases or []
thr = ctrl.embed_threshold if ctrl.embed_threshold is not None else 0.60
if not paras or len(text) < 100:
return CheckResult(present=None, source="embedding")
try:
from compliance.services.mc_embedding_matcher import (
DIM, _chunk_text, _cosine, _embed_texts,
)
if ctrl.control_id not in _PARA_CACHE:
pv = await _embed_texts(paras)
_PARA_CACHE[ctrl.control_id] = [v for v in pv if v and len(v) == DIM]
pvecs = _PARA_CACHE[ctrl.control_id]
chunks = _chunk_text(text)
cvecs = [v for v in await asyncio.wait_for(
_embed_texts(chunks), timeout=90.0) if v and len(v) == DIM]
except (Exception, asyncio.TimeoutError) as e:
logger.info("embedding checker inaktiv %s: %s", ctrl.control_id, str(e)[:80])
return CheckResult(present=None, source="embedding")
if not pvecs or not cvecs:
return CheckResult(present=None, source="embedding")
best = max((_cosine(p, c) for p in pvecs for c in cvecs), default=0.0)
return CheckResult(present=best >= thr, confidence=round(best, 3),
source="embedding")
@@ -0,0 +1,106 @@
"""CONTENT/CONTRACTUAL-Pruefer / decision_method=LLM.
present/absent ueber die LLM-Kaskade (`call_with_cascade`; prod: OVH-120b zuerst).
Retrieval = GANZE Paragraph-Abschnitte zum Topic (nicht Top-k-Chunks das war in
der AGB-Validierung der Schluessel). KEIN DEFECT Korrektheits-/Defekt-Pruefung
ist ein separater Modus. present=None bei Fehler (fail-safe: Aufrufer behaelt
Keyword-Ergebnis). (Validiert an AGB delivery/warranty.)
"""
from __future__ import annotations
import json
import logging
import re
from .base import CheckResult, ControlSpec, DocContext, VerificationMethod
logger = logging.getLogger(__name__)
_SECTION = re.compile(r"(?m)(?=^\s*(?:§\s*)?\d+[\.\)]\s)")
_SYS = (
"Du bist deutscher Compliance-Rechtsexperte. Entscheide, ob die genannte "
"Pflicht in den vorgelegten Abschnitten vorhanden ist. NUR die Abschnitte "
'zaehlen. Antworte NUR JSON: {"verdict":"ERFUELLT|FEHLT","zitat":"woertlich '
'oder leer","begruendung":"1 Satz"}.'
)
def _sections(text: str) -> list[str]:
return [s.strip() for s in _SECTION.split(text) if s.strip()]
def _parse(txt: str) -> dict:
out = (txt or "").strip()
if out.startswith("```"):
out = out.split("```", 2)[1]
out = out[4:] if out.startswith("json") else out
a, b = out.find("{"), out.rfind("}")
return json.loads(out[a:b + 1] if 0 <= a < b else out)
class LLMChecker:
verification_method = VerificationMethod.CONTENT
async def check(self, ctrl: ControlSpec, doc: DocContext) -> CheckResult:
text = doc.text or ""
if len(text) < 50:
return CheckResult(present=None, source="llm")
# decision_method=LLM mit judge='haiku': Sufficiency-Pfad (validiert
# P0.89/R0.91). Der Qwen-first-Cascade ist als Sufficiency-Judge
# widerlegt -> hier Haiku direkt, kriteriengeführte Subsumtion.
if (ctrl.extra or {}).get("judge") == "haiku":
return await self._haiku(ctrl, text)
secs = _sections(text)
if ctrl.topic_regex:
rel = [s for s in secs if re.search(ctrl.topic_regex, s, re.I)][:6] or secs[:6]
else:
rel = secs[:6]
question = ctrl.question or f"Ist die Pflicht '{ctrl.label}' im Text vorhanden?"
try:
from compliance.services.llm_cascade import call_with_cascade
r = await call_with_cascade(
_SYS,
json.dumps({"frage": question, "abschnitte": rel}, ensure_ascii=False),
min_confidence=0.6, max_tokens=500,
)
obj = _parse(r.get("text"))
verdict = obj.get("verdict")
zitat = (obj.get("zitat") or "")[:120]
if verdict not in ("ERFUELLT", "FEHLT"):
return CheckResult(present=None, evidence=zitat, source=r.get("source", "?"))
return CheckResult(
present=verdict == "ERFUELLT", evidence=zitat,
confidence=float(r.get("confidence") or 0.0),
source=r.get("source", "llm"),
)
except Exception as e:
logger.info("llm checker fail %s: %s", ctrl.control_id, str(e)[:80])
return CheckResult(present=None, source="error")
async def _haiku(self, ctrl: ControlSpec, text: str) -> CheckResult:
"""Sufficiency via Haiku direkt (validierter Judge). Kriteriengeführt:
die Rechts-Elemente stehen in ctrl.paraphrases; wiederverwendet den
validierten deep_check-Sufficiency-Prompt."""
try:
from compliance.services.llm_cascade import _call_anthropic
from compliance.services.specialist_agents.dse.deep_check import (
_JUDGE_SYS, _build_user, _parse as _parse_judge,
)
crit = ctrl.paraphrases or [ctrl.label or ctrl.control_id]
user = _build_user(text, ctrl.label or ctrl.control_id, crit)
obj = None
for _ in range(2):
obj = _parse_judge(await _call_anthropic(_JUDGE_SYS, user, max_tokens=400))
if obj:
break
if not obj:
return CheckResult(present=None, source="haiku")
return CheckResult(
present=bool(obj.get("erfuellt")),
evidence=(obj.get("begruendung") or "")[:120],
confidence=float(obj.get("confidence") or 0.0),
source="haiku",
)
except Exception as e:
logger.info("llm haiku checker fail %s: %s", ctrl.control_id, str(e)[:80])
return CheckResult(present=None, source="error")
@@ -0,0 +1,41 @@
"""REFERENCE-Pruefer (verification_method=REFERENCE, decision_method=LINK_RESOLVER).
Ist ein klarer Verweis auf ein anderes Pflichtdokument vorhanden (+ optional: loest
der Link auf)? Deterministisch. Bsp: 'Details in unserer Datenschutzerklaerung'.
KEIN LLM, kein juristisches Urteil. (Validiert an AGB data_protection: 7/7.)
Die tatsaechliche HTTP-Aufloesung des Links ist ein optionaler Runtime-Schritt
(online), nicht Teil dieser deterministischen Text-Pruefung die URL wird hier
nur extrahiert und in `detail['link']` zurueckgegeben.
"""
from __future__ import annotations
import re
from .base import CheckResult, ControlSpec, DocContext, VerificationMethod
_URL = re.compile(r"https?://[^\s)\]]+", re.I)
class ReferenceChecker:
verification_method = VerificationMethod.REFERENCE
async def check(self, ctrl: ControlSpec, doc: DocContext) -> CheckResult:
text = doc.text or ""
pats = ctrl.patterns or []
if not pats or not text:
return CheckResult(present=False, source="reference")
for p in pats:
m = re.search(p, text, re.I)
if m:
window = text[max(0, m.start() - 40): m.end() + 200]
url = _URL.search(window) or _URL.search(text)
link = url.group(0) if url else None
return CheckResult(
present=True,
evidence=" ".join(m.group(0).split())[:120],
confidence=1.0,
source="reference",
detail={"link": link},
)
return CheckResult(present=False, source="reference")
@@ -0,0 +1,68 @@
"""Prüfer-Router — method-agnostischer Dispatch.
control sensor_classification (verification_method + decision_method) Checker.
Ein neues Modul liefert nur ControlSpecs; der Router wählt den Prüfer. Damit wird
der Embedding findet, Claude entscheidet"-Pfad EIN gemeinsamer CONTENT/LLM-Prüfer
statt Cookie-Sonderlogik. Nicht-gebaute Prüfer (PLAYWRIGHT/AUDIT/SCANNER/REGEX-
FIELD) present=None (fail-safe: Aufrufer behält sein deterministisches Ergebnis).
"""
from __future__ import annotations
from typing import Any, Optional
from .base import CheckResult, ControlSpec, DecisionMethod, DocContext
from .embedding_checker import EmbeddingChecker
from .llm_checker import LLMChecker
from .reference_checker import ReferenceChecker
_LLM = LLMChecker()
_EMB = EmbeddingChecker()
_REF = ReferenceChecker()
# decision_method → Checker. Fehlende Mechanismen bewusst None (noch nicht gebaut).
_BY_DECISION: dict[str, Any] = {
DecisionMethod.LLM: _LLM,
DecisionMethod.EMBEDDING: _EMB,
DecisionMethod.LINK_RESOLVER: _REF,
}
async def route_and_check(ctrl: ControlSpec, doc: DocContext) -> CheckResult:
checker = _BY_DECISION.get((ctrl.decision_method or "").upper())
if checker is None:
return CheckResult(present=None,
source=f"no_checker:{ctrl.decision_method}")
return await checker.check(ctrl, doc)
def build_spec(
control_id: str,
sensor_classification: Optional[dict[str, Any]],
*,
label: str = "",
criteria: Optional[list] = None,
question: str = "",
patterns: Optional[list[str]] = None,
embed_threshold: Optional[float] = None,
) -> ControlSpec:
"""Baut ein ControlSpec aus der GESPEICHERTEN sensor_classification
(canonical_controls.generation_metadata.sensor_classification) + den
Control-Kriterien. CONTENT/LLM judge='haiku' (validierter Sufficiency-
Judge; Default für Sufficiency lt. Entscheidung 2026-06-22)."""
sc = sensor_classification or {}
vm = (sc.get("verification_method") or "").upper()
dm = (sc.get("decision_method") or "").upper()
extra: dict[str, Any] = {}
if vm == "CONTENT" and dm == "LLM":
extra["judge"] = "haiku"
return ControlSpec(
control_id=control_id,
verification_method=vm,
decision_method=dm,
label=label,
paraphrases=[str(c) for c in (criteria or []) if c],
question=question,
patterns=patterns or [],
embed_threshold=embed_threshold,
extra=extra,
)
@@ -142,19 +142,26 @@ async def _call_ovh(system: str, user: str, max_tokens: int = 6000) -> str:
headers = {"Content-Type": "application/json"}
if key:
headers["Authorization"] = f"Bearer {key}"
# gpt-oss-120b is a REASONING model: it spends output tokens on
# chain-of-thought before emitting the answer. A low cap (e.g. deep_check's
# max_tokens=400) makes it hit the length limit mid-reasoning and return
# content=null — the whole tier then silently yields nothing. Floor the
# budget so the reasoning AND the JSON answer fit.
payload = {
"model": model, "temperature": 0.05, "max_tokens": max_tokens,
"model": model, "temperature": 0.05, "max_tokens": max(max_tokens, 2000),
"messages": [{"role": "system", "content": system},
{"role": "user", "content": user}],
"response_format": {"type": "json_object"},
}
try:
async with httpx.AsyncClient(timeout=45.0) as c:
async with httpx.AsyncClient(timeout=90.0) as c:
r = await c.post(f"{base.rstrip('/')}/v1/chat/completions",
json=payload, headers=headers)
r.raise_for_status()
choice = (r.json().get("choices") or [{}])[0]
return (choice.get("message") or {}).get("content", "") or ""
msg = (r.json().get("choices") or [{}])[0].get("message") or {}
# Answer is normally in content; if the model was length-capped the
# JSON can land in reasoning_content instead — fall back to it.
return (msg.get("content") or "") or (msg.get("reasoning_content") or "")
except Exception as e:
logger.warning("ovh cascade tier 2 failed: %s", e)
return ""
@@ -0,0 +1,179 @@
"""Obligation Aggregation Engine — Ausführung des Legal Obligation Layer v1.
Aggregiert Bewertungen auf KRITERIUM-Ebene (pro Control) zu Ergebnissen auf
OBLIGATION-Ebene. Das ist die erstmalige Ausführung des Modells
Regulation Legal Obligation Control Criterion
das Finding entsteht auf der OBLIGATION, nicht pro Control. Damit kollabiert
die im Katalog gemessene Redundanz (portability 11×, recipients 14×): N Controls,
die dieselbe Pflicht prüfen, ergeben EIN Obligation-Finding statt N Control-Findings.
Regulierungs-agnostisch: kennt nur obligation_id, tier, met, legal_basis,
conditional. DSGVO/CRA/NIS2/DORA/MaschVO/AI-Act speisen dieselbe Funktion.
Fail-safe (docs-src/development/legal_obligation_layer_v1.md, §Aggregation):
LEGAL_MINIMUM-Obligation:
applicable=false NA (kein Finding)
keine LM-Anforderung erfüllt FAILED (Pflicht-Lücke)
alle LM-Anforderungen erfüllt MET
nur ein Teil erfüllt PARTIAL
LM nicht bewertbar (Prüfer down) UNDETERMINED (Aufrufer behält Legacy)
BEST_PRACTICE/OPTIONAL-Obligation (kein LM):
mind. ein Kriterium erfüllt MET (abgedeckt)
keines OPEN (nur Empfehlung, NIE FAILED)
Redundanz-Kollaps: LM-Kriterien EINER Obligation werden zu Anforderungen" nach
`legal_basis` gruppiert; eine Anforderung gilt als erfüllt, sobald IRGENDEIN Control
sie bestätigt (OR). 9× recipients_disclosed (alle Art 13(1)(e)) = eine Anforderung.
PARTIAL entsteht nur bei mehreren DISTINKTEN LM-Anforderungen (verschiedene
legal_basis) innerhalb einer Obligation.
"""
from __future__ import annotations
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from typing import Callable, Optional
LM, BP, OPT = "LEGAL_MINIMUM", "BEST_PRACTICE", "OPTIONAL"
MET, PARTIAL, FAILED = "MET", "PARTIAL", "FAILED"
NA, UNDETERMINED, OPEN = "NA", "UNDETERMINED", "OPEN"
PFLICHT, EMPFEHLUNG, NICHT_ANWENDBAR = "PFLICHT", "EMPFEHLUNG", "NICHT_ANWENDBAR"
# Predikat-Hook: (conditional, doc_text) → True (anwendbar) / False (→ NA) / None (unbekannt → anwendbar)
ApplicableFn = Callable[[str, str], Optional[bool]]
@dataclass(frozen=True)
class CriterionEval:
"""Eine Kriteriums-Bewertung eines Controls, einer Obligation zugeordnet."""
obligation_id: str
tier: str # LEGAL_MINIMUM / BEST_PRACTICE / OPTIONAL
met: Optional[bool] # True erfüllt · False fehlt · None unbestimmt
control_id: str
legal_basis: str = ""
criterion: str = ""
conditional: Optional[str] = None # Applicability-Prädikat der Obligation
@dataclass
class ObligationResult:
obligation_id: str
status: str # MET / PARTIAL / FAILED / NA / UNDETERMINED / OPEN
bucket: str # PFLICHT / EMPFEHLUNG / NICHT_ANWENDBAR
tier: str # bestimmende Tier der Obligation
applicable: bool
evidence: list[str] # beitragende control_ids
lm_met: int # erfüllte LM-Anforderungen
lm_total: int # distinkte LM-Anforderungen (bewertbar)
recommendations: list[dict] = field(default_factory=list)
def _governing_tier(evals: list[CriterionEval]) -> str:
tiers = {e.tier for e in evals}
if LM in tiers:
return LM
return BP if BP in tiers else OPT
def _requirement_state(evals: list[CriterionEval]) -> Optional[bool]:
"""Zustand EINER LM-Anforderung über alle prüfenden Controls (OR/Redundanz):
True (irgendwer bestätigt) · None (alle unbestimmt) · False (bewertet, fehlt)."""
if any(e.met is True for e in evals):
return True
if all(e.met is None for e in evals):
return None
return False
def _recommendations(evals: list[CriterionEval]) -> list[dict]:
"""Nicht erfüllte BEST_PRACTICE/OPTIONAL-Kriterien → Empfehlungen."""
return [{"criterion": e.criterion, "tier": e.tier, "legal_basis": e.legal_basis,
"control_id": e.control_id}
for e in evals if e.tier in (BP, OPT) and e.met is False]
def aggregate_obligation(obligation_id: str, evals: list[CriterionEval], *,
applicable_fn: Optional[ApplicableFn] = None,
doc_text: str = "") -> ObligationResult:
evidence = sorted({e.control_id for e in evals if e.control_id})
conditional = next((e.conditional for e in evals if e.conditional), None)
tier = _governing_tier(evals)
recs = _recommendations(evals)
applicable = True
if applicable_fn is not None and conditional:
verdict = applicable_fn(conditional, doc_text)
applicable = True if verdict is None else bool(verdict)
if not applicable:
return ObligationResult(obligation_id, NA, NICHT_ANWENDBAR, tier, False,
evidence, 0, 0, recs)
lm_evals = [e for e in evals if e.tier == LM]
if lm_evals:
reqs: dict[str, list[CriterionEval]] = defaultdict(list)
for e in lm_evals:
reqs[e.legal_basis or obligation_id].append(e)
states = [_requirement_state(v) for v in reqs.values()]
determinable = [s for s in states if s is not None]
if not determinable:
return ObligationResult(obligation_id, UNDETERMINED, PFLICHT, LM, True,
evidence, 0, len(states), recs)
met = sum(1 for s in determinable if s)
total = len(determinable)
status = MET if met == total else (FAILED if met == 0 else PARTIAL)
return ObligationResult(obligation_id, status, PFLICHT, LM, True,
evidence, met, total, recs)
# Reine BEST_PRACTICE/OPTIONAL-Obligation: nie Pflicht, nie FAILED.
covered = any(e.met is True for e in evals)
return ObligationResult(obligation_id, MET if covered else OPEN, EMPFEHLUNG,
tier, True, evidence, 0, 0, recs)
def aggregate_obligations(evals: list[CriterionEval], *,
applicable_fn: Optional[ApplicableFn] = None,
doc_text: str = "") -> list[ObligationResult]:
"""Flache Kriteriums-Liste → ein ObligationResult je obligation_id."""
groups: dict[str, list[CriterionEval]] = defaultdict(list)
for e in evals:
if e.obligation_id:
groups[e.obligation_id].append(e)
return [aggregate_obligation(oid, g, applicable_fn=applicable_fn, doc_text=doc_text)
for oid, g in groups.items()]
def evals_from_tiered(control_id: str, tiered_criteria: list[dict],
detail: list[dict], conditional: Optional[str] = None
) -> list[CriterionEval]:
"""Adapter: tiered_criteria (obligation_id/tier/legal_basis) + das
evaluate_tiered-`detail` (met pro Index, gleiche Reihenfolge) CriterionEvals.
`conditional` kommt aus der Control-`applicability` (gilt für die Obligation)."""
out: list[CriterionEval] = []
for i, c in enumerate(tiered_criteria or []):
oid = c.get("obligation_id")
if not oid:
continue
d = detail[i] if i < len(detail) else {}
out.append(CriterionEval(
obligation_id=oid,
tier=(c.get("compliance_tier") or "").upper(),
met=d.get("met"),
control_id=control_id,
legal_basis=c.get("legal_basis") or "",
criterion=c.get("criterion") or "",
conditional=conditional,
))
return out
def summarize(results: list[ObligationResult]) -> dict:
"""Phase-C-Kennzahlen: Obligation-Anzahl + Verteilung nach Bucket/Status."""
return {
"obligations": len(results),
"buckets": dict(Counter(r.bucket for r in results)),
"statuses": dict(Counter(r.status for r in results)),
"pflicht_failed": sum(1 for r in results if r.bucket == PFLICHT and r.status == FAILED),
"pflicht_partial": sum(1 for r in results if r.bucket == PFLICHT and r.status == PARTIAL),
"recommendations": sum(len(r.recommendations) for r in results),
}
@@ -0,0 +1,76 @@
"""Applicability-Prädikate (minimal) für die Obligation Aggregation Engine.
Jedes Prädikat entscheidet aus dem Dokumenttext, ob eine BEDINGTE Obligation
anwendbar ist:
True anwendbar (normal bewerten)
False NICHT anwendbar ( NA statt FEHLT)
None Prädikat unbekannt Aufrufer behält Default=anwendbar (fail-safe,
KEINE stille NA)
Bewusst KLEIN gehalten: nur die bereits modellierten Bedingungen
has_third_country_transfer · uses_legitimate_interest · direct_marketing
(+ legitimate_interest_or_public_task, weil objection_general_art21_1 dieselbe
Rechtsgrundlage als Anknüpfung nutzt). profiling/employment/telecom/health/
data_act folgen in der nächsten Charge bis dahin None anwendbar.
"""
from __future__ import annotations
from typing import Optional
_THIRD_COUNTRY = (
"drittland", "drittstaat", "drittländ", "third countr", "außerhalb der eu",
"ausserhalb der eu", "außerhalb des ewr", "ausserhalb des ewr",
"angemessenheitsbeschluss", "standardvertragsklausel", "standarddatenschutzklausel",
"binding corporate rules", "verbindliche interne datenschutzvorschriften",
"data privacy framework", "privacy shield", "in die usa", "in den usa",
"vereinigte staaten", "international transfer", "internationale übermittlung",
"art. 44", "art. 46",
)
_LEGIT = (
"berechtigtes interesse", "berechtigten interesse", "berechtigte interesse",
"legitimate interest", "art. 6 abs. 1 lit. f", "art. 6 abs. 1 f",
"art. 6 (1) (f)", "abs. 1 buchstabe f", "interessenabwägung",
)
_PUBLIC_TASK = (
"öffentliche aufgabe", "öffentlichen aufgabe", "im öffentlichen interesse",
"art. 6 abs. 1 lit. e", "ausübung öffentlicher gewalt", "official authority",
)
_DIRECT_MKT = (
"direktwerbung", "direktmarketing", "direkt-werbung", "werbe-e-mail", "werbe-mail",
"newsletter", "werbliche", "marketingzweck", "marketing-zweck", "zwecke der werbung",
"zu werbezwecken", "e-mail-marketing", "postwerbung", "telefonwerbung",
)
def _has(text: str, kws: tuple[str, ...]) -> bool:
return any(k in text for k in kws)
def has_third_country_transfer(text: str) -> bool:
return _has(text, _THIRD_COUNTRY)
def uses_legitimate_interest(text: str) -> bool:
return _has(text, _LEGIT)
def direct_marketing(text: str) -> bool:
return _has(text, _DIRECT_MKT)
_PREDICATES = {
"has_third_country_transfer": has_third_country_transfer,
"uses_legitimate_interest": uses_legitimate_interest,
"legitimate_interest_or_public_task":
lambda t: _has(t, _LEGIT) or _has(t, _PUBLIC_TASK),
"direct_marketing": direct_marketing,
}
def applicable(conditional: str, doc_text: str) -> Optional[bool]:
"""applicable_fn-Hook für `aggregate_obligations`. Unbekanntes Prädikat → None
(Aufrufer behält Default=anwendbar; NIE stille NA)."""
fn = _PREDICATES.get(conditional)
if fn is None:
return None
return fn((doc_text or "").lower())
@@ -0,0 +1,26 @@
"""Obligation-Taxonomie-Registry — versioniertes Artefakt bis zur DB-Owner-Tabelle
(Legal Obligation Layer v1, docs-src/development/legal_obligation_layer_v1.md).
Hält Metadaten auf OBLIGATION-Ebene, die (noch) keine eigene DB-Tabelle haben.
`decision_method_required`: Obligations, deren Erkennung Keyword/Embedding
NACHWEISLICH nicht zuverlässig leistet (kompakte/synonymreiche Offenlegung) und
die CONTENT/LLM brauchen. Empirisch belegt am TeamViewer-Recall-Defekt: 0/22
recipients+international_transfer Controls trafen, obwohl die Pflicht erfüllt war
(außerhalb EU/EWR Standardvertragsklauseln/Schutzmaßnahmen"); Embedding cos
0.490.57 < 0.62, teils falscher Chunk kein Schwellen-Fix, sondern LLM-Klasse.
Wirkung: der Shadow zählt ein FAILED solcher Obligations NICHT als echte Lücke",
sondern als RECALL_LIMITED (Prüfer kann sie mit aktueller Methode nicht verifizieren).
"""
OBLIGATION_META: dict[str, dict] = {
"recipients_disclosed": {"decision_method_required": "LLM"},
"third_country_transfer_disclosed": {"decision_method_required": "LLM"},
"safeguards_disclosed": {"decision_method_required": "LLM"},
"safeguards_accessible": {"decision_method_required": "LLM"},
}
def requires_llm(obligation_id: str) -> bool:
"""True, wenn diese Obligation CONTENT/LLM braucht (Keyword/Embedding-Recall belegt unzureichend)."""
return OBLIGATION_META.get(obligation_id, {}).get("decision_method_required") == "LLM"
@@ -0,0 +1,102 @@
"""AGB-Routing-Pipeline (C-lean): nimmt das Keyword-Ergebnis des ChecklistAgent
und routet keyword-durchgefallene Items per `_routing.decision_method` an die
wiederverwendbare Prüfer-Library (Embedding / Reference / LLM). Davor das
Geschäftsmodell-Gate (Applicability). Das Re-Tiering (LOW Empfehlung) +
Output-Zusammenbau macht der AGBAgent hier nur die Routing-Entscheidung.
Validiert (7-Firmen-Opus-GT): 71 % FP ~0. agent.py bleibt dünn, dies ist der
einzige Ort des C-lean-Flows.
"""
from __future__ import annotations
import logging
from compliance.services.checkers.base import (
ControlSpec,
DecisionMethod,
DocContext,
VerificationMethod,
)
from compliance.services.checkers.embedding_checker import EmbeddingChecker
from compliance.services.checkers.llm_checker import LLMChecker
from compliance.services.checkers.reference_checker import ReferenceChecker
from . import _routing
logger = logging.getLogger(__name__)
# Checker sind zustandslos (schwere Imports erst in .check()) → Modul-Singletons.
_EMB = EmbeddingChecker()
_REF = ReferenceChecker()
_LLM = LLMChecker()
def _spec(item_id: str) -> ControlSpec:
"""ControlSpec für ein Item aus der AGB-Routing-Config bauen."""
dm = _routing.decision_method(item_id)
if dm == _routing.REFERENCE:
return ControlSpec(
control_id=item_id, verification_method=VerificationMethod.REFERENCE,
decision_method=DecisionMethod.LINK_RESOLVER,
patterns=[_routing.REFERENCE_PATTERNS[item_id]],
)
if dm == _routing.LLM:
return ControlSpec(
control_id=item_id, verification_method=VerificationMethod.CONTENT,
decision_method=DecisionMethod.LLM,
paraphrases=_routing.PARAPHRASES.get(item_id, []),
topic_regex=_routing.LLM_TOPIC.get(item_id, ""),
question=_routing.LLM_QUESTION.get(item_id, ""),
)
return ControlSpec(
control_id=item_id, verification_method=VerificationMethod.CONTENT,
decision_method=DecisionMethod.EMBEDDING,
paraphrases=_routing.PARAPHRASES.get(item_id, []),
embed_threshold=_routing.EMBED_THRESHOLDS.get(item_id),
)
async def _resolves(item_id: str, text: str, skip_llm: bool):
"""True = Klausel doch vorhanden (Keyword-Finding auflösen). False/None =
Finding behalten (fail-safe: bei Unsicherheit/Service-Ausfall lieber melden)."""
dm = _routing.decision_method(item_id)
if dm == _routing.MERGED:
return True # in ein anderes Item aufgegangen → kein eigenes Finding
doc = DocContext(text=text)
spec = _spec(item_id)
if dm == _routing.REFERENCE:
return (await _REF.check(spec, doc)).present
if dm == _routing.LLM:
if skip_llm:
return None # interaktiv: kein LLM → Keyword-Ergebnis behalten
return (await _LLM.check(spec, doc)).present
return (await _EMB.check(spec, doc)).present
async def run_routed(base_findings: list, text: str, context: dict | None = None):
"""Routet die keyword-durchgefallenen Items.
Returns (kept, resolved_ids, gated_ids):
kept = Findings, die nach Gate+Rescue bestehen bleiben
resolved_ids = per Embedding/Reference/LLM doch als vorhanden erkannt
gated_ids = per Geschäftsmodell nicht anwendbar (N/A)
"""
context = context or {}
skip_llm = bool(context.get("skip_llm"))
model = _routing.detect_business_model(text)
kept, resolved, gated = [], [], []
for f in base_findings:
item_id = f.field_id
if not _routing.is_applicable(item_id, model):
gated.append(item_id)
continue
try:
present = await _resolves(item_id, text, skip_llm)
except Exception as e: # noqa: BLE001 — best-effort, Finding behalten
logger.info("agb routing %s failed: %s", item_id, str(e)[:80])
present = None
if present is True:
resolved.append(item_id)
else:
kept.append(f)
return kept, resolved, gated
@@ -0,0 +1,144 @@
"""AGB-Routing — das verification_method / decision_method-Meta-Modell, angewandt
auf die AGB_CHECKLIST. Siehe docs-src/development/platform_checker_matrix.md.
Pro Checklisten-Item: WELCHER Pruefer (verification_method) und WIE entschieden
wird (decision_method). Single source of truth; `agb_checks.py` bleibt die reine
Pflichtangaben-Liste, dieses Modul ist der additive Routing-Overlay.
Validiert 2026-06-20/21 gegen 7-Firmen-Opus-GT (71 % FP -> ~0):
- 17 Items EMBEDDING (per-Item-Cosinus-Schwelle; 21 recall-FP gekillt, 0 Fehl-Rescue)
- 2 Items LLM (delivery_timeframe, warranty_period; ganze Paragraph-Abschnitte + starkes Modell, present/absent)
- 1 Item REFERENCE (data_protection; DSE-Verweis + Link, 7/7 deterministisch)
- incorporation_clause MERGED in contract (implizit, kein eigener Pruefer)
"""
from __future__ import annotations
# ── decision_method-Werte ────────────────────────────────────────────────
EMBEDDING = "EMBEDDING"
LLM = "LLM"
REFERENCE = "REFERENCE"
MERGED = "MERGED" # in ein anderes Item aufgegangen -> kein eigener Check
# ── Per-Item Embedding-Rescue-Schwellen ───────────────────────────────────
# An der 7-Firmen-GT kalibriert. BEWUSST per-Item: eine globale Schwelle trennt
# bei juristischer Prosa nicht (PASS/FAIL ueberlappen global, trennen per-Item).
# Vorlaeufig (FAIL n=25 klein) -> vor Prod mit mehr Firmen nachkalibrieren.
EMBED_THRESHOLDS: dict[str, float] = {
"scope": 0.58, "contract": 0.58, "payment": 0.60, "payment_methods": 0.58,
"delivery": 0.57, "warranty": 0.58, "termination": 0.60,
"termination_period": 0.60, "termination_form": 0.60, "consumer_rights": 0.55,
"liability": 0.615, "jurisdiction": 0.585, "dispute_odr_link": 0.67,
"choice_of_law_specific": 0.625, "payment_due_date": 0.705,
"salvatory_clause": 0.565, "amendment_clause": 0.635,
}
# ── decision_method je Item (deckt alle 21 Checklisten-IDs ab) ────────────
DECISION_METHOD: dict[str, str] = {cid: EMBEDDING for cid in EMBED_THRESHOLDS}
DECISION_METHOD.update({
"delivery_timeframe": LLM,
"warranty_period": LLM,
"data_protection": REFERENCE,
"incorporation_clause": MERGED, # -> contract
})
# ── Applicability-Gate (VOR allen Pruefern; Geschaeftsmodell entscheidet) ──
ABO_ONLY = {"termination", "termination_period", "termination_form"} # nur Dauerschuld
B2C_ONLY = {"consumer_rights", "dispute_odr_link"} # nicht reines B2B
# ── Referenz-Paraphrasen (Embedding-Rescue + LLM-Section-Ranking) ──────────
PARAPHRASES: dict[str, list[str]] = {
"scope": ["Diese AGB gelten fuer alle Vertraege zwischen dem Anbieter und dem Kunden.",
"Die Angebote richten sich ausschliesslich an Verbraucher, die privat kaufen.",
"Geltungsbereich: fuer die Geschaeftsbeziehung gelten die nachfolgenden Bedingungen."],
"contract": ["Durch Anklicken des Bestellbuttons gibt der Kunde ein verbindliches Angebot ab.",
"Der Vertrag kommt mit Zugang der Bestellbestaetigung zustande.",
"Mit der Bestellung erkennt der Kunde diese AGB als Vertragsbestandteil an."],
"liability": ["Die Haftung fuer leicht fahrlaessige Pflichtverletzungen ist beschraenkt.",
"Wir haften unbeschraenkt fuer Schaeden aus Verletzung von Leben, Koerper, Gesundheit.",
"Bei Verletzung wesentlicher Vertragspflichten Haftung auf vorhersehbaren Schaden begrenzt."],
"jurisdiction": ["Es gilt das Recht der Bundesrepublik Deutschland unter Ausschluss des UN-Kaufrechts.",
"Gerichtsstand fuer alle Streitigkeiten ist der Sitz des Unternehmens.",
"Auf die Vertraege findet deutsches Recht Anwendung."],
"dispute_odr_link": ["Die EU-Kommission stellt eine Plattform zur Online-Streitbeilegung bereit.",
"Zur aussergerichtlichen Streitbeilegung steht die OS-Plattform zur Verfuegung."],
"choice_of_law_specific": ["Es gilt deutsches Recht unter Ausschluss des UN-Kaufrechts (CISG).",
"Anwendbar ist das Recht der Bundesrepublik Deutschland."],
"payment": ["Die Preise sind Endpreise inklusive Mehrwertsteuer; Versandkosten gesondert ausgewiesen.",
"Zahlungsbedingungen und Preise richten sich nach den Angaben im Bestellprozess."],
"payment_methods": ["Zur Zahlung stehen Vorkasse, Kreditkarte, Lastschrift, Rechnung und PayPal zur Verfuegung.",
"Folgende Zahlungsarten werden akzeptiert: Ueberweisung, SEPA-Lastschrift, Kreditkarte."],
"payment_due_date": ["Der Kaufpreis ist sofort mit Vertragsschluss faellig.",
"Die Zahlung ist bei Bestellung zu leisten.",
"Der Rechnungsbetrag wird mit Versand der Ware faellig.",
"Bei Kauf auf Rechnung ist der Betrag innerhalb von 14 Tagen zu zahlen."],
"delivery": ["Die Lieferung erfolgt an die vom Kunden angegebene Lieferadresse.",
"Wir liefern innerhalb Deutschlands; die Leistung wird nach Vertragsschluss erbracht."],
"delivery_timeframe": ["Die Lieferzeit betraegt in der Regel 3-5 Werktage.",
"Die Ware wird voraussichtlich innerhalb von 2 bis 4 Werktagen geliefert."],
"warranty": ["Es gelten die gesetzlichen Maengelhaftungsrechte (Gewaehrleistung).",
"Bei Maengeln stehen dem Kunden die gesetzlichen Gewaehrleistungsrechte zu.",
"Fuer Sachmaengel haften wir nach den gesetzlichen Bestimmungen."],
"warranty_period": ["Die Gewaehrleistungsfrist betraegt zwei Jahre ab Lieferung.",
"Die Verjaehrungsfrist fuer Maengelansprueche betraegt zwei Jahre."],
"termination": ["Der Vertrag kann von beiden Parteien ordentlich gekuendigt werden.",
"Das Abonnement kann jederzeit zum Ende der Laufzeit gekuendigt werden."],
"termination_period": ["Die Kuendigungsfrist betraegt einen Monat zum Vertragsende.",
"Der Vertrag ist mit einer Frist von vier Wochen kuendbar."],
"termination_form": ["Die Kuendigung bedarf der Textform und kann per E-Mail erfolgen.",
"Eine Kuendigung ist schriftlich oder per E-Mail moeglich."],
"salvatory_clause": ["Sollten einzelne Bestimmungen unwirksam sein, bleibt die Wirksamkeit der uebrigen unberuehrt.",
"Die Unwirksamkeit einzelner Klauseln beruehrt nicht die Gueltigkeit der uebrigen AGB."],
"amendment_clause": ["Wir behalten uns vor, diese AGB mit Wirkung fuer die Zukunft zu aendern.",
"Aenderungen dieser Bedingungen werden dem Kunden rechtzeitig mitgeteilt."],
"consumer_rights": ["Die gesetzlichen Rechte des Verbrauchers bleiben unberuehrt.",
"Zwingende Verbraucherschutzvorschriften bleiben von diesen Bedingungen unberuehrt."],
}
# ── LLM-Items: Paragraph-Abschnitts-Retrieval + Pruef-Frage ───────────────
LLM_TOPIC: dict[str, str] = {
"delivery_timeframe": r"liefer",
"warranty_period": r"gew(?:ä|ae)hrleist|m(?:ä|ae)ngel|sachm|verj(?:ä|ae)hr|haftungsdauer|garantie",
}
LLM_QUESTION: dict[str, str] = {
"delivery_timeframe": ("Wird eine KONKRETE Lieferzeit/Lieferfrist genannt (z.B. '3-5 Werktage', "
"'innerhalb von 2 Werktagen')? Eine nur allgemeine Lieferregelung ODER ein "
"Verweis 'Lieferzeit im Bestellvorgang' ohne konkrete Frist zaehlt NICHT."),
"warranty_period": ("Wird eine KONKRETE Gewaehrleistungs-/Verjaehrungsfrist als ZAHL genannt "
"(z.B. 'zwei Jahre', 'ein Jahr')? Ein blosser Verweis auf 'gesetzliche "
"Verjaehrungsfristen' ohne Zahl zaehlt NICHT."),
}
# ── REFERENCE-Item data_protection ────────────────────────────────────────
REFERENCE_PATTERNS: dict[str, str] = {
"data_protection": r"datenschutz(erkl(?:ä|ae)rung|bestimmung|hinweis)",
}
def detect_business_model(text: str) -> dict[str, bool]:
"""Deterministischer Geschaeftsmodell-Detektor fuer das Applicability-Gate.
Edge-Case: gemischte Modelle (Webshop + Finanzierung/Service) koennen 'abo'
triggern -> dann greift das termination-Gate nicht; bewusst konservativ
(lieber eine Kuendigungs-Pruefung zu viel als eine echte Luecke uebersehen)."""
tl = text.lower()
consumer = ("widerrufsbelehrung" in tl) or ("widerrufsrecht" in tl and "verbraucher" in tl)
b2b = (not consumer) and any(s in tl for s in (
"geschäftskunden", "ausschließlich an unternehmer", "nur an unternehmer",
"lieferbedingungen für geschäftskunden"))
abo = any(s in tl for s in (
"abonnement", "mindestlaufzeit", "vertragslaufzeit", "verlängert sich",
"monatsabo", "jahresabo")) or ("abo" in tl and "kündig" in tl)
return {"b2b": b2b, "abo": abo, "b2c": not b2b}
def is_applicable(item_id: str, model: dict[str, bool]) -> bool:
"""Gate: gilt das Item fuer dieses Geschaeftsmodell? (False -> N/A, nicht pruefen)."""
if item_id in ABO_ONLY and not model.get("abo"):
return False
if item_id in B2C_ONLY and model.get("b2b"):
return False
return True
def decision_method(item_id: str) -> str:
"""decision_method fuer ein Item; Default EMBEDDING (Prosa-Rescue)."""
return DECISION_METHOD.get(item_id, EMBEDDING)
@@ -1,19 +1,60 @@
"""AGBAgent — Allgemeine Geschäftsbedingungen (§§ 305 ff. BGB).
Thin-Subclass von ChecklistAgent über die kuratierte AGB_CHECKLIST (L1
Pflichtangaben + L2 Detailchecks). KEIN Library-Firehose.
ChecklistAgent-Subclass: erst L1/L2-Keyword-Pass, dann **C-lean-Routing** die
keyword-durchgefallenen Items werden per `decision_method` an die wiederverwendbare
Prüfer-Library geroutet (Embedding / Reference / LLM), davor das Geschäftsmodell-
Gate (Applicability), danach Severity-Re-Tiering (LOW Empfehlung).
Validiert gegen 7-Firmen-Opus-GT: 71 % FP ~0. Config in `_routing`, Flow in `_pipeline`.
"""
from __future__ import annotations
from compliance.services.doc_checks.agb_checks import AGB_CHECKLIST
from .._base import AgentInput, AgentOutput, lint_output
from .._checklist_agent import ChecklistAgent
from .._rollup import rollup
from ._pipeline import run_routed
class AGBAgent(ChecklistAgent):
CHECKLIST = AGB_CHECKLIST
agent_id = "agb"
agent_version = "1.0"
agent_version = "2.0" # v2: decision_method-Routing (Embedding/Reference/LLM)
doc_type = "agb"
owned_mc_ids = tuple(c["id"] for c in AGB_CHECKLIST)
async def evaluate(self, agent_input: AgentInput) -> AgentOutput:
# 1) Basis-Keyword-Pass (L1/L2). out.findings = keyword-durchgefallene Items.
out = await super().evaluate(agent_input)
text = (agent_input.text or "").strip()
if len(text) < 100 or not out.findings:
return out # zu kurz / nichts zu routen
# 2) Routing: Gate + Embedding/Reference/LLM-Rescue der Keyword-Misses.
kept, resolved, gated = await run_routed(
out.findings, text, agent_input.context)
resolved_set, gated_set = set(resolved), set(gated)
# 3) Coverage angleichen: rescued → ok, gated → na.
for c in out.mc_coverage:
if c.mc_id in resolved_set:
c.status, c.reason = "ok", "semantisch vorhanden (Routing)"
elif c.mc_id in gated_set:
c.status, c.reason = "na", "für Geschäftsmodell nicht anwendbar"
# 4) Severity-Re-Tiering: HIGH/MEDIUM = Findings, LOW = nur Empfehlung.
out.findings = [f for f in kept if f.severity in ("HIGH", "MEDIUM")]
out.recommendations = rollup(kept)
# 5) Aggregat-Kennzahlen neu (Coverage hat sich verschoben).
cov = out.mc_coverage
out.mc_total = len(cov)
out.mc_ok = sum(1 for c in cov if c.status == "ok")
out.mc_na = sum(1 for c in cov if c.status == "na")
out.mc_high = sum(1 for c in cov if c.status == "high")
out.mc_medium = sum(1 for c in cov if c.status == "medium")
out.mc_low = sum(1 for c in cov if c.status == "low")
out.notes = ((out.notes + " · ") if out.notes else "") + \
f"routed: {len(resolved)} rescued, {len(gated)} n/a"
return lint_output(out)
@@ -0,0 +1,78 @@
"""Applicability-Gate fuer den Cookie-Policy-Scan.
Schliesst Controls aus dem Cookie-Findings-Scan aus, die laut
`compliance.control_classification` NICHT gegen eine Cookie-Policy laufen
('COOKIE_POLICY' nicht in applicable_artifacts). Diese gehoeren zu einem
anderen Artefakt/Pruefer Banner (BEHAVIOR/Playwright), Security/TOM/Audit
(PROCESS) und erzeugen sonst Unsinn-Findings (z.B. 'TOMs nicht dokumentiert'
gegen eine Cookie-Richtlinie). Sie werden NICHT geloescht, sondern als
Routing-Liste zurueckgegeben.
Anders als das DSE-Gate OHNE needs_review-Ausnahme: das Artefakt-Signal ist
hier entscheidend und per Inventar (2026-06-21) belegt; die mis-scopeten 11
sind geprueft. Fail-safe: fehlt die Tabelle / DB nicht erreichbar -> leeres
Dict -> es wird NICHT gefiltert (kein stiller Recall-Verlust).
"""
from __future__ import annotations
import logging
import os
from typing import Any
logger = logging.getLogger(__name__)
async def load_cookie_gate(db_url: str = "") -> dict[str, dict[str, Any]]:
"""Liefert {control_id: meta} fuer Controls, die aus dem Cookie-Findings-
Scan auszuschliessen sind (kein COOKIE_POLICY-Artefakt). Leeres Dict =
kein Filter."""
dsn = (db_url or os.getenv("DATABASE_URL")
or os.getenv("COMPLIANCE_DATABASE_URL") or "")
if not dsn:
return {}
try:
import asyncpg
conn = await asyncpg.connect(dsn)
try:
rows = await conn.fetch(
"""SELECT control_id, obligation_type, check_intent,
applicable_artifacts
FROM compliance.control_classification
WHERE is_active
AND NOT ('COOKIE_POLICY' = ANY(applicable_artifacts))""")
finally:
await conn.close()
except Exception as e: # Tabelle fehlt / DB weg -> kein Filter
logger.info("cookie classification gate inaktiv: %s", str(e)[:90])
return {}
return {
r["control_id"]: {
"obligation_type": r["obligation_type"],
"check_intent": r["check_intent"],
"applicable_artifacts": list(r["applicable_artifacts"] or []),
}
for r in rows if r["control_id"]
}
def apply_gate(
controls: list[dict[str, Any]],
gate: dict[str, dict[str, Any]],
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
"""Teilt geladene Controls in (kept, routed_out).
kept: laufen normal durch den Cookie-Scan.
routed_out: aus dem Scan genommen (control_id + title + Klassifikations-
Metadaten fuer das Routing zu Banner/Security/Audit).
"""
kept: list[dict[str, Any]] = []
routed_out: list[dict[str, Any]] = []
for c in controls:
cid = c.get("control_id")
meta = gate.get(cid) if cid else None
if meta:
routed_out.append({"control_id": cid, "title": c.get("title"), **meta})
else:
kept.append(c)
return kept, routed_out
@@ -0,0 +1,63 @@
"""Layer-3 Sufficiency-Judge fuer Cookie-Policy.
Das Embedding/Boost-Auto-Rescue (Layer 0/2) ist BEWUSST optimistisch es findet
das Thema, beweist aber nicht die Erfuellung. Messung (2026-06-22): 159 FN
(Over-Rescue) gegen Opus-GT, weil 'Thema erwaehnt' als 'erfuellt' durchgewunken
wurde. Diese Schicht prueft GENAU die rescued Controls mit dem validierten
Haiku-Judge (Cohort cookie_sufficiency_v1: P0.89/R0.91) NICHT die Qwen-first-
Kaskade (lokal ist als Sufficiency-Judge widerlegt) und nimmt 'passed' zurueck,
wenn die konkrete Pflicht nicht erfuellt ist. 'Embedding findet, Claude entscheidet.'
Nur fuer den NICHT-skip_llm-Pfad (voller Check); der schnelle/interaktive Pfad
behaelt das deterministische Rescue.
"""
from __future__ import annotations
import logging
from typing import Any
logger = logging.getLogger(__name__)
_RESCUE_MARKERS = ("+embedding", "+regex_boost")
def _is_rescued(r: dict[str, Any]) -> bool:
src = r.get("source") or ""
return r.get("passed") and any(m in src for m in _RESCUE_MARKERS)
async def judge_rescued(text: str, results: list[dict[str, Any]]) -> int:
"""Prueft alle rescued (embedding/boost) passed-Controls mit Haiku.
Nimmt passed zurueck, wenn der Judge die Pflicht als NICHT erfuellt sieht.
Gibt die Anzahl zurueckgenommener (korrigierter) Rescues zurueck.
"""
# Über den gemeinsamen Prüfer-Router (kein Cookie-Sonderfall mehr):
# CONTENT/LLM → build_spec setzt judge='haiku' → LLMChecker (validierter
# Sufficiency-Judge). Damit ist Cookie der erste echte Router-Consumer.
from compliance.services.checkers.base import DocContext
from compliance.services.checkers.router import build_spec, route_and_check
candidates = [r for r in results if _is_rescued(r)]
if not candidates:
return 0
doc = DocContext(text=text)
sc = {"verification_method": "CONTENT", "decision_method": "LLM"}
corrected = 0
for r in candidates:
crit = r.get("_pass_criteria") or [r.get("label") or r.get("hint") or ""]
if not isinstance(crit, list):
crit = [str(crit)]
label = r.get("label") or r.get("hint") or r.get("control_id") or ""
spec = build_spec(r.get("control_id") or "", sc, label=label, criteria=crit)
res = await route_and_check(spec, doc)
if res.present is False:
r["passed"] = False
r["source"] = (r.get("source") or "") + "+llm_failed"
r["matched_text"] = "[layer-3 sufficiency-judge: nicht erfuellt]"
r["_judge_reason"] = (res.evidence or "")[:200]
corrected += 1
if corrected:
logger.info("cookie layer-3 sufficiency-judge: %d/%d rescues zurueckgenommen",
corrected, len(candidates))
return corrected
@@ -96,6 +96,22 @@ class CookiePolicyAgent(BaseSpecialistAgent):
"Branchen-MCs entfernt"
)
# Layer 3 — Sufficiency-Judge (Haiku) auf die embedding/boost-rescued
# Controls: Embedding findet das Thema, Claude entscheidet ob die Pflicht
# konkret erfuellt ist. Nur im vollen Check (nicht skip_llm).
skip_llm = bool((agent_input.context or {}).get("skip_llm"))
if not skip_llm:
try:
from ._sufficiency_judge import judge_rescued
corrected = await judge_rescued(text, results)
if corrected:
notes_parts.append(
f"layer-3 sufficiency-judge: {corrected} Rescues "
"zurückgenommen"
)
except Exception as e:
logger.warning("cookie layer-3 judge skipped: %s", e)
seen: set[str] = set()
for r in results:
mc_id = r.get("control_id") or ""
@@ -45,6 +45,15 @@ async def run_v3_pipeline(
controls = []
_normalize_criteria(controls)
controls, sector_dropped = _filter_sector(controls, business_scope)
# Artefakt-Gate: Controls ohne COOKIE_POLICY-Artefakt (Security/TOM/Audit,
# Banner) raus — sie gehoeren zu anderem Pruefer/Artefakt und erzeugen sonst
# Unsinn-Findings. Siehe _classification_gate.
routed_out: list[dict[str, Any]] = []
try:
from ._classification_gate import apply_gate, load_cookie_gate
controls, routed_out = apply_gate(controls, await load_cookie_gate(db_url))
except Exception as e:
logger.warning("cookie classification gate skipped: %s", e)
results: list[dict[str, Any]] = []
if controls:
try:
@@ -111,6 +120,7 @@ async def run_v3_pipeline(
"layer_0_boost_overrides": boost_overrides,
"total_mcs": len(results),
"sector_dropped": sector_dropped,
"artifact_gated": len(routed_out),
}
return results, telemetry
@@ -0,0 +1,80 @@
"""Applicability-Gate fuer den DSE-Scan.
Schliesst Controls aus dem DSE-FINDINGS-Scan aus, die laut
`compliance.control_classification` NICHT gegen eine DSE laufen
('DSE' nicht in applicable_artifacts) UND sicher klassifiziert sind
(needs_review=false). Diese werden NICHT geloescht, sondern als
*organisatorische Checkliste* zurueckgegeben (Routing zu VVT/TOM/Audit).
Fail-safe: unsichere Klassifikationen (needs_review=true) bleiben im
Findings-Scan. Defensiv: fehlt die Tabelle (z.B. Prod ohne Migration),
liefert das Gate ein leeres Dict -> es wird NICHT gefiltert.
"""
from __future__ import annotations
import logging
import os
from typing import Any
logger = logging.getLogger(__name__)
async def load_dse_gate(db_url: str = "") -> dict[str, dict[str, Any]]:
"""Liefert {control_id: meta} fuer Controls, die aus dem DSE-Findings-Scan
auszuschliessen sind (hochsicher organisatorisch). Leeres Dict = kein Filter.
"""
dsn = (db_url or os.getenv("DATABASE_URL")
or os.getenv("COMPLIANCE_DATABASE_URL") or "")
if not dsn:
return {}
try:
import asyncpg
conn = await asyncpg.connect(dsn)
try:
rows = await conn.fetch(
"""SELECT control_id, obligation_type, check_intent,
applicable_artifacts, reference_allowed
FROM compliance.control_classification
WHERE is_active AND NOT needs_review
AND NOT ('DSE' = ANY(applicable_artifacts))""")
finally:
await conn.close()
except Exception as e: # Tabelle fehlt / DB nicht erreichbar -> kein Filter
logger.info("dse classification gate inaktiv: %s", str(e)[:90])
return {}
return {
r["control_id"]: {
"obligation_type": r["obligation_type"],
"check_intent": r["check_intent"],
"applicable_artifacts": list(r["applicable_artifacts"] or []),
"reference_allowed": r["reference_allowed"],
}
for r in rows if r["control_id"]
}
def apply_gate(
controls: list[dict[str, Any]],
gate: dict[str, dict[str, Any]],
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
"""Teilt geladene Controls in (findings_controls, organizational).
findings_controls: laufen normal durch den DSE-Scan.
organizational: aus dem Scan genommen, als Checkliste ausgegeben
(control_id + title + Klassifikations-Metadaten fuer das Routing).
"""
kept: list[dict[str, Any]] = []
organizational: list[dict[str, Any]] = []
for c in controls:
cid = c.get("control_id")
meta = gate.get(cid) if cid else None
if meta:
organizational.append({
"control_id": cid,
"title": c.get("title"),
**meta,
})
else:
kept.append(c)
return kept, organizational
@@ -0,0 +1,170 @@
"""Deterministische semantische Recall-Schicht für den DSE-Check.
WARUM: Reines Keyword-Matching hat schlechten Recall (eine Pflicht lässt sich
auf viele Arten formulieren). Der frühere Regex-Boost war zu stumpf (über-passt
auf vollständigen Dokumenten). BGE-M3-Embeddings erkennen den SINN und sind
dabei DETERMINISTISCH: ein Embedding-Modell ist eine feste Funktion, gleicher
Text gleicher Vektor gleiches Pass/Fail bei fester Schwelle. Reproduzierbar,
auditierbar, kein Keyword-Katalog, kein generatives LLM zur Checkzeit.
Design:
- Doc wird EINMAL pro Dokument-Hash eingebettet (teuer: ~37s/64k-Doc), die
Per-Control-Scores werden gecacht (/data) Folge-Checks sind instant.
- Reachability-Guard: ist der Embedding-Service nicht erreichbar, liefert die
Schicht leer zurück (der deterministische Keyword-Layer trägt) KEIN Hang.
- Schwelle ist die einzige Stellschraube (DSE-Default 0.65, an BMW-GT kalibriert;
braucht Mehr-Firmen-Kalibrierung gegen Overfitting bewusst konservativ).
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import logging
import os
import sqlite3
from typing import Iterable
logger = logging.getLogger(__name__)
# DSE-Schwelle: an BMW-Haiku-GT vermessen (PASS-Median 0.648 / FAIL-Median 0.612).
# 0.65 = präzisionsfreundlich (wenig Über-Pass). Per ENV überschreibbar für
# spätere Mehr-Firmen-Kalibrierung, ohne Code-Änderung.
DSE_EMBED_THRESHOLD = float(os.getenv("DSE_EMBED_THRESHOLD", "0.65"))
_CACHE_PATH = os.getenv("DSE_EMBED_CACHE", "/data/dse_embed_cache.json")
_SIDECAR_DB = os.getenv("MC_CLASS_DB", "/data/mc_classification.db")
def _doc_hash(text: str) -> str:
return hashlib.sha256(text.encode("utf-8", "ignore")).hexdigest()[:20]
def _load_cache() -> dict:
try:
with open(_CACHE_PATH, encoding="utf-8") as f:
return json.load(f)
except Exception:
return {}
def _save_cache(cache: dict) -> None:
try:
# LRU-Kappung: max 30 Dokumente im Cache (Scores sind klein)
if len(cache) > 30:
for k in list(cache.keys())[:-30]:
cache.pop(k, None)
tmp = _CACHE_PATH + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(cache, f)
os.replace(tmp, _CACHE_PATH)
except Exception as e:
logger.warning("dse embed-cache save failed: %s", e)
def _load_control_vecs(cids: Iterable[str]) -> dict[str, list[float]]:
from compliance.services.mc_embedding_matcher import _blob_to_vec
cid_list = [c for c in cids if c]
if not cid_list:
return {}
try:
with sqlite3.connect(_SIDECAR_DB) as c:
ph = ",".join("?" * len(cid_list))
rows = c.execute(
f"SELECT control_id, embedding FROM mc_classification "
f"WHERE control_id IN ({ph}) AND doc_type='dse' "
f"AND check_type='text' AND embedding IS NOT NULL",
cid_list,
).fetchall()
return {cid: _blob_to_vec(b) for cid, b in rows}
except Exception as e:
logger.warning("dse control-vec load failed: %s", e)
return {}
async def _embedding_reachable(timeout: float = 2.0) -> bool:
"""Schneller TCP-Connect zum Embedding-Service. Verhindert, dass ein toter
Service den Check blockiert (macmini-Lehrer-Last hat das Embedding früher
verstopft)."""
url = os.getenv("EMBEDDING_URL", "http://embedding-service:8087")
hostport = url.split("://", 1)[-1].split("/", 1)[0]
host, _, port = hostport.partition(":")
port = int(port or "8087")
try:
fut = asyncio.open_connection(host, port)
reader, writer = await asyncio.wait_for(fut, timeout=timeout)
writer.close()
try:
await writer.wait_closed()
except Exception:
pass
return True
except Exception as e:
logger.warning("dse embedding-service nicht erreichbar (%s) — "
"deterministischer Layer trägt", e)
return False
async def _compute_scores(text: str, all_cids: list[str]) -> dict[str, float]:
"""Bettet das Dokument EINMAL ein und liefert max-Cosinus je Control."""
from compliance.services.mc_embedding_matcher import (
_chunk_text, _cosine, _embed_texts, DIM,
)
mc_vecs = _load_control_vecs(all_cids)
if not mc_vecs:
return {}
chunks = _chunk_text(text)
if not chunks:
return {}
chunk_vecs = await _embed_texts(chunks)
chunk_vecs = [v for v in chunk_vecs if v and len(v) == DIM]
if not chunk_vecs:
return {}
return {
cid: round(float(max((_cosine(mv, cv) for cv in chunk_vecs),
default=0.0)), 4)
for cid, mv in mc_vecs.items()
}
async def embedding_recall(
text: str,
candidate_cids: Iterable[str],
threshold: float | None = None,
embed_timeout: float = 90.0,
) -> set[str]:
"""Returns die candidate control_ids, die semantisch (>= Schwelle) im Doc
vorkommen. Deterministisch + gecacht. Leeres Set, wenn Service down/Fehler.
candidate_cids: die im Keyword-Layer DURCHGEFALLENEN Controls (Recall-Rescue).
"""
cands = [c for c in candidate_cids if c]
if not text or len(text) < 100 or not cands:
return set()
thr = DSE_EMBED_THRESHOLD if threshold is None else threshold
h = _doc_hash(text)
cache = _load_cache()
scores = cache.get(h)
if scores is None:
if not await _embedding_reachable():
return set()
try:
scores = await asyncio.wait_for(
_compute_scores(text, cands), timeout=embed_timeout)
except (Exception, asyncio.TimeoutError) as e:
logger.warning("dse embedding_recall skipped: %s", e)
return set()
if not scores:
return set()
cache[h] = scores
_save_cache(cache)
logger.info("dse embedding_recall: doc %s eingebettet (%d Scores)",
h, len(scores))
else:
logger.info("dse embedding_recall: Cache-Treffer doc %s", h)
cand_set = set(cands)
return {cid for cid, s in scores.items()
if cid in cand_set and s >= thr}
@@ -0,0 +1,130 @@
"""DSE Shadow-Verdrahtung der Obligation Aggregation Engine.
Erzeugt aus den v3-`results` zusätzlich Obligation-Ergebnisse AUSSCHLIESSLICH
für die Telemetrie (Shadow Mode). Ändert KEINE nutzer-sichtbaren Findings.
Mapping control-level über generation_metadata.legal_obligations +
applicability.conditional; das `met`-Signal ist das Legacy-`passed` des Controls
(kein zusätzlicher Prüfer-Call, kein Key). Liefert die Vergleichszahlen, mit denen
sich der Umschalt-Entscheid später absichern lässt:
legacy_control_findings · obligation_shadow_results · collapse_factor ·
na_count · met_failed_delta · top_collapsed_obligations
"""
from __future__ import annotations
import logging
import os
from typing import Any, Optional
logger = logging.getLogger(__name__)
async def fetch_obligation_markers(cids: list[str], db_url: str = "") -> dict[str, dict]:
"""legal_obligations + applicability.conditional der Controls laden.
Leeres Dict bei Fehler/keiner DB (Shadow fällt still aus)."""
cids = [c for c in cids if c]
if not cids:
return {}
import json
dsn = db_url or os.getenv("DATABASE_URL") or os.getenv("COMPLIANCE_DATABASE_URL")
if not dsn:
return {}
try:
import asyncpg
conn = await asyncpg.connect(dsn)
rows = await conn.fetch(
"select control_id, generation_metadata->'legal_obligations' obl, "
"generation_metadata->'applicability'->>'conditional' cond "
"from compliance.canonical_controls "
"where control_id = any($1::text[]) "
"and generation_metadata ? 'legal_obligations'", cids)
await conn.close()
except Exception as e:
logger.warning("fetch_obligation_markers failed: %s", e)
return {}
out: dict[str, dict] = {}
for r in rows:
obl = r["obl"]
obl = json.loads(obl) if isinstance(obl, str) else obl
if obl:
out[r["control_id"]] = {"obl": obl, "cond": r["cond"]}
return out
def compute_obligation_shadow(results: list[dict], text: str,
markers: dict[str, dict]) -> dict[str, Any]:
"""Reiner Shadow-Vergleich (keine DB, keine Seiteneffekte). `markers`:
{control_id: {obl:[...], cond:str|None}}. `met` = Legacy-`passed`."""
from compliance.services.obligation_aggregation import (
FAILED, LM, MET, NA, PARTIAL, CriterionEval, aggregate_obligations,
)
from compliance.services.obligation_applicability import applicable
from compliance.services.obligation_taxonomy import requires_llm
legacy = 0
evals: list[Any] = []
contrib: dict[str, list] = {}
for r in results:
cid = r.get("control_id")
m = markers.get(cid)
if not m:
continue
passed = bool(r.get("passed"))
if not passed:
legacy += 1
for ob in m["obl"]:
evals.append(CriterionEval(ob, LM, passed, cid, "", "", m.get("cond")))
contrib.setdefault(ob, []).append((cid, passed))
if not evals:
return {"status": "no obligation markers on result controls"}
obls = aggregate_obligations(evals, applicable_fn=applicable, doc_text=text)
# FAILED/PARTIAL ehrlich trennen: echte Lücke (failed_by_current_checker) vs
# RECALL_LIMITED (Obligation braucht LLM, aktueller Prüfer kann sie nicht verifizieren).
findings = failed_current = recall_limited = na = 0
for o in obls:
if o.status == NA:
na += 1
elif o.status in (FAILED, PARTIAL):
findings += 1
if requires_llm(o.obligation_id):
recall_limited += 1
else:
failed_current += 1
top = []
for o in obls:
cs = contrib.get(o.obligation_id, [])
fehlt = sum(1 for _, p in cs if not p)
if fehlt >= 2:
top.append({"obligation": o.obligation_id, "fehlt": fehlt,
"total": len(cs), "status": o.status,
"recall_limited": bool(requires_llm(o.obligation_id)
and o.status in (FAILED, PARTIAL))})
top.sort(key=lambda x: -x["fehlt"])
met_count = sum(1 for o in obls if o.status == MET)
recall_limited_obls = sorted({o.obligation_id for o in obls
if o.status in (FAILED, PARTIAL)
and requires_llm(o.obligation_id)})
return {
"legacy_control_findings": legacy,
"obligation_shadow_results": len(obls),
"obligation_findings": findings,
"failed_by_current_checker": failed_current,
"recall_limited": recall_limited,
"met_count": met_count,
"collapse_factor": round(legacy / findings, 2) if findings else None,
"na_count": na,
"met_failed_delta": legacy - findings,
"top_collapsed_obligations": top[:10],
"recall_limited_obligations": recall_limited_obls,
}
async def build_obligation_shadow(results: list[dict], text: str,
db_url: str = "") -> dict[str, Any]:
"""Async-Wrapper: Marker laden, dann Shadow rechnen. NIE in `results` schreiben."""
cids = [r.get("control_id") for r in results if r.get("control_id")]
markers = await fetch_obligation_markers(cids, db_url)
if not markers:
return {"status": "no markers"}
return compute_obligation_shadow(results, text, markers)
@@ -0,0 +1,183 @@
"""Getierte 3-Status-Auswertung für DSE-Controls mit `tiered_criteria`.
Pro Kriterium wird nach `decision_method` bewertet:
- EMBEDDING (Präsenz): deterministisch (festes Modell), Doc EINMAL pro Scan
eingebettet reproduzierbar, kein LLM. Trägt den GROSSTEIL.
- LLM (Sufficiency): Haiku-Judge, GECACHT pro (doc_hash, control_id#idx,
PROMPT_VERSION, criterion) gleicher Scan = gleiches Ergebnis. Löst die
empirisch gemessene Judge-Varianz (ein Live-Call ist NICHT reproduzierbar).
Status NUR aus LEGAL_MINIMUM:
ERFÜLLT (alle LM erfüllt ODER kein LM) · FEHLT (kein LM erfüllt) ·
TEILWEISE (Teil der LM erfüllt) · UNBESTIMMT (LM nicht bewertbar, z. B.
Embedding-Service down Aufrufer behält sein Legacy-Ergebnis).
BEST_PRACTICE/OPTIONAL fließen NIE in den Status, nur in `recommendations`.
Siehe docs-src/development/criterion_meta_model.md.
"""
from __future__ import annotations
import asyncio
import hashlib
import logging
import os
import sqlite3
from typing import Any, Optional
logger = logging.getLogger(__name__)
PROMPT_VERSION = "dse-tier-v1"
_CACHE_DB = os.getenv("TIERED_JUDGE_CACHE", "/data/tiered_judge_cache.db")
_EMBED_THR = float(os.getenv("DSE_CRITERION_EMBED_THRESHOLD", "0.62"))
LM = "LEGAL_MINIMUM"
def _doc_hash(text: str) -> str:
return hashlib.sha256(text.encode("utf-8", "ignore")).hexdigest()[:20]
def _ckey(dh: str, cid: str, idx: int, crit: str) -> str:
ch = hashlib.sha256(crit.encode("utf-8", "ignore")).hexdigest()[:12]
return f"{dh}|{cid}#{idx}|{PROMPT_VERSION}|{ch}"
def _cache_get(key: str) -> Optional[bool]:
try:
with sqlite3.connect(_CACHE_DB) as c:
c.execute("create table if not exists judge(k text primary key, met int)")
row = c.execute("select met from judge where k=?", (key,)).fetchone()
return None if row is None else bool(row[0])
except Exception:
return None
def _cache_put(key: str, met: bool) -> None:
try:
with sqlite3.connect(_CACHE_DB) as c:
c.execute("create table if not exists judge(k text primary key, met int)")
c.execute("insert or replace into judge values(?,?)", (key, int(met)))
except Exception as e:
logger.warning("tiered judge cache put: %s", e)
async def prepare_doc(text: str) -> dict[str, Any]:
"""Doc EINMAL pro Scan einbetten. Liefert {hash, chunk_vecs}. Bei Embedding-
Ausfall: chunk_vecs=None EMBEDDING-Kriterien werden UNBESTIMMT (Fallback)."""
ctx: dict[str, Any] = {"hash": _doc_hash(text or ""), "chunk_vecs": None}
if not text or len(text) < 100:
return ctx
try:
from compliance.services.mc_embedding_matcher import DIM, _chunk_text, _embed_texts
vecs = await asyncio.wait_for(_embed_texts(_chunk_text(text)), timeout=90.0)
ctx["chunk_vecs"] = [v for v in vecs if v and len(v) == DIM]
except (Exception, asyncio.TimeoutError) as e:
logger.warning("tiered prepare_doc embedding inaktiv: %s", e)
return ctx
async def _embed_present(crits: list[str], ctx: dict, thr: float) -> dict[str, Optional[bool]]:
cvecs = ctx.get("chunk_vecs")
if not cvecs:
return {c: None for c in crits}
try:
from compliance.services.mc_embedding_matcher import DIM, _cosine, _embed_texts
pv = await _embed_texts(crits)
out: dict[str, Optional[bool]] = {}
for crit, v in zip(crits, pv):
if not v or len(v) != DIM:
out[crit] = None
else:
out[crit] = max((_cosine(v, cv) for cv in cvecs), default=0.0) >= thr
return out
except Exception as e:
logger.warning("tiered embed present: %s", e)
return {c: None for c in crits}
async def _llm_met(cid: str, idx: int, crit: str, doc, dh: str) -> Optional[bool]:
key = _ckey(dh, cid, idx, crit)
cached = _cache_get(key)
if cached is not None:
return cached
from compliance.services.checkers.router import build_spec, route_and_check
spec = build_spec(cid, {"verification_method": "CONTENT", "decision_method": "LLM"},
label=crit, criteria=[crit])
res = await route_and_check(spec, doc)
if res.present is None:
return None
_cache_put(key, bool(res.present))
return bool(res.present)
def _status(lm_vals: list[Optional[bool]]) -> str:
if not lm_vals:
return "ERFÜLLT" # kein gesetzliches Minimum → nie rot
if any(m is None for m in lm_vals):
return "UNBESTIMMT" # Aufrufer behält Legacy
n = sum(1 for m in lm_vals if m)
if n == len(lm_vals):
return "ERFÜLLT"
return "FEHLT" if n == 0 else "TEILWEISE"
async def evaluate_tiered(control_id: str, tiered_criteria: list[dict],
ctx: dict, doc) -> dict[str, Any]:
dh = ctx.get("hash") or _doc_hash(getattr(doc, "text", "") or "")
emb_texts = [c["criterion"] for c in (tiered_criteria or [])
if c.get("criterion")
and (c.get("decision_method") or "EMBEDDING").upper() != "LLM"]
emb_res = await _embed_present(emb_texts, ctx, _EMBED_THR) if emb_texts else {}
lm_vals: list[Optional[bool]] = []
recs: list[dict] = []
detail: list[dict] = []
for idx, c in enumerate(tiered_criteria or []):
crit = c.get("criterion") or ""
if not crit:
continue
tier = (c.get("compliance_tier") or "").upper()
if (c.get("decision_method") or "EMBEDDING").upper() == "LLM":
met = await _llm_met(control_id, idx, crit, doc, dh)
src = "haiku-cache"
else:
met = emb_res.get(crit)
src = "embedding"
detail.append({"criterion": crit, "tier": tier, "met": met, "source": src})
if tier == LM:
lm_vals.append(met)
elif met is False:
recs.append({"criterion": crit, "tier": tier or "OPTIONAL",
"legal_basis": c.get("legal_basis")})
return {"status": _status(lm_vals), "lm_met": sum(1 for m in lm_vals if m),
"lm_total": len(lm_vals), "recommendations": recs, "detail": detail}
async def fetch_tiered_criteria(cids: list[str], db_url: str = "") -> dict[str, list]:
"""tiered_criteria der angegebenen Controls aus canonical_controls laden.
Leeres Dict bei Fehler/keiner DB (Fallback: kein Tiering, Legacy trägt)."""
cids = [c for c in cids if c]
if not cids:
return {}
import json
dsn = db_url or os.getenv("DATABASE_URL") or os.getenv("COMPLIANCE_DATABASE_URL")
if not dsn:
return {}
try:
import asyncpg
conn = await asyncpg.connect(dsn)
rows = await conn.fetch(
"select control_id, generation_metadata->'tiered_criteria' tc "
"from compliance.canonical_controls "
"where control_id = any($1::text[]) "
"and generation_metadata ? 'tiered_criteria'", cids)
await conn.close()
except Exception as e:
logger.warning("fetch_tiered_criteria failed: %s", e)
return {}
out: dict[str, list] = {}
for r in rows:
tc = r["tc"]
tc = json.loads(tc) if isinstance(tc, str) else tc
if tc:
out[r["control_id"]] = tc
return out
@@ -1,29 +1,286 @@
"""DSEAgent — Datenschutzerklärung / Datenschutzinformation (Art. 13/14 DSGVO).
"""DSE-Agent v3 — Datenschutzerklärung / Datenschutzinformation (Art. 13/14
DSGVO), baut auf doc_check_controls (267 text-MCs aus DB).
Thin-Subclass von ChecklistAgent über die kuratierte ART13_CHECKLIST (KEIN
90k-Library-Firehose). Einzige Spezialität: Drittland wird bei dokumentiertem
Drittlandtransfer (Scan-Kontext) zu HIGH angehoben.
Volle Parität zu impressum/ + cookie_policy/ (User-Vorgabe 2026-06-17):
Layer 0 Regex-Boost (kuratierte Art-13-Patterns aus mcs.py / ART13_CHECKLIST)
Layer 1 Keyword-Match aus pass_criteria der DSE-DB-MCs (deterministisch)
Layer 2 BGE-M3 Embedding-Match
Layer 3 Semantic-Validator (LLM) für offene HIGH/MEDIUM-Fails + Auto-Learning
Die kuratierten Patterns gehen NICHT verloren sie boosten (Layer 0) die DB-
Controls (z.B. präzises "keine Drittlandübermittlung" drittland-MC PASS, kein
False-Positive). DSE-Spezialität bleibt: Drittland HIGH bei dokumentiertem
Transfer (scan_context).
Output-Layer (Linter / Rollup / Methodik-UI) bleibt 1:1.
"""
from __future__ import annotations
from compliance.services.doc_checks.dse_checks import ART13_CHECKLIST
import logging
from datetime import datetime, timezone
from .._base import AgentInput
from .._checklist_agent import ChecklistAgent
from .._base import (
AgentInput,
AgentOutput,
BaseSpecialistAgent,
EscalationLog,
EvidenceSource,
Finding,
McCoverage,
Severity,
SourceType,
lint_output,
)
from .._pattern_library import record as record_pattern
from .._rollup import rollup
from .._semantic_validator import build_rename_action, validate_present
from .mcs import MC_IDS, MCS
from .regex_boost import BOOST_KEYWORDS
from .v3_engine import run_v3_pipeline
logger = logging.getLogger(__name__)
class DSEAgent(ChecklistAgent):
CHECKLIST = ART13_CHECKLIST
_SEV_TO_ENUM = {
"CRITICAL": Severity.HIGH,
"HIGH": Severity.HIGH,
"MEDIUM": Severity.MEDIUM,
"LOW": Severity.LOW,
"INFO": Severity.INFO,
}
# Drittland-Vokabeln für die scan_context-Heraufstufung (Art. 13(1)(f)).
_THIRD_COUNTRY_KW = tuple(set(
BOOST_KEYWORDS.get("third_country", ())
+ BOOST_KEYWORDS.get("third_country_mechanism", ())
))
def _build_measure(label: str, norm: str) -> str:
"""Maßnahme (Imperativ) statt Pruef-Frage als action."""
base = (label or "").strip().rstrip(".")
if not base:
return ("Datenschutz-Pflichtangabe ergänzen und gegen Art. 13/14 "
"DSGVO prüfen.")
msg = f"Pflichtangabe ergänzen: {base}."
if norm:
msg += f" Rechtsgrundlage: {norm}."
return msg
def _is_third_country_topic(result: dict) -> bool:
"""Ist dieses DB-MC thematisch ein Drittland-Control?"""
parts: list[str] = [str(result.get("label") or "").lower()]
for c in (result.get("_pass_criteria") or []):
if c:
parts.append(str(c).lower())
blob = " ".join(parts)
hits = sum(1 for kw in _THIRD_COUNTRY_KW if kw in blob)
return hits >= 1
class DSEAgent(BaseSpecialistAgent):
agent_id = "dse"
agent_version = "1.0"
agent_version = "3.0"
doc_type = "dse"
owned_mc_ids = tuple(c["id"] for c in ART13_CHECKLIST)
owned_mc_ids = MC_IDS
def _severity_override(self, c: dict, agent_input: AgentInput):
def _third_country_transfer(self, agent_input: AgentInput) -> bool:
sc = (agent_input.context or {}).get("scan_context") or {}
tc = str(sc.get("third_country_transfer", "")).lower() in (
return str(sc.get("third_country_transfer", "")).lower() in (
"yes", "true", "1", "ja")
if tc and c["id"] in ("third_country", "third_country_mechanism"):
return "HIGH"
return None
async def evaluate(self, agent_input: AgentInput) -> AgentOutput:
start = datetime.now(timezone.utc)
text = (agent_input.text or "").strip()
scope = set(agent_input.business_scope or [])
coverage: list[McCoverage] = []
findings: list[Finding] = []
esc_logs: list[EscalationLog] = []
notes_parts: list[str] = []
if len(text) < 100:
for mc in MCS:
coverage.append(McCoverage(
mc_id=mc.mc_id, status="skipped",
label=mc.label, reason="text too short",
))
return self._finalize(
start, findings, esc_logs, coverage,
confidence=0.0,
notes="DSE-Text zu kurz oder leer.",
)
tc_transfer = self._third_country_transfer(agent_input)
# Embedding-Recall (Layer 2) läuft IMMER — deterministisch, gecacht
# (pro Doc-Hash → Folge-Views instant) und Reachability-gegated
# (kein Hang, wenn der Service fehlt). Ersetzt den über-passenden Boost.
results, telemetry = await run_v3_pipeline(text, scope)
notes_parts.append(
f"v3-pipeline: {telemetry.get('total_mcs', 0)} DB-MCs · "
f"{telemetry.get('layer_1_pass', 0)} Keyword-Treffer · "
f"{telemetry.get('embedding_passes', 0)} semantisch (Embedding)"
)
if telemetry.get("sector_dropped") or telemetry.get("offtopic_dropped"):
notes_parts.append(
f"Scope-Filter: {telemetry.get('sector_dropped', 0)} "
f"Branchen-MCs, {telemetry.get('offtopic_dropped', 0)} "
"themenfremde MCs entfernt"
)
seen: set[str] = set()
for r in results:
mc_id = r.get("control_id") or ""
if not mc_id or mc_id in seen:
continue
seen.add(mc_id)
passed = bool(r.get("passed"))
sev = _SEV_TO_ENUM.get(
(r.get("severity") or "MEDIUM").upper(), Severity.MEDIUM,
)
# DSE-Spezialität: Drittland → HIGH bei dokumentiertem Transfer.
sev_reason = "db_mc_failed"
if tc_transfer and _is_third_country_topic(r):
sev = Severity.HIGH
sev_reason = "db_mc_failed_third_country_transfer"
coverage.append(McCoverage(
mc_id=mc_id,
status="ok" if passed else sev.value.lower(),
reason=str(r.get("matched_text") or r.get("hint") or "")[:120],
))
if passed:
continue
label = r.get("label") or r.get("hint") or ""
norm_str = str(r.get("regulation") or "").strip()
if r.get("article"):
norm_str = (norm_str + f" Art. {r.get('article')}").strip()
if not norm_str:
norm_str = "DSGVO Art. 13/14"
findings.append(Finding(
check_id=f"DSE-DBMC-{mc_id}",
agent=self.agent_id,
agent_version=self.agent_version,
field_id=mc_id,
severity=sev,
severity_reason=sev_reason,
title=str(label)[:200] or f"DB-MC {mc_id} nicht erfüllt",
norm=norm_str,
evidence="",
action=_build_measure(str(label), norm_str)[:400],
confidence=0.9,
sources=[EvidenceSource(
source_type=SourceType.MC,
source_id=mc_id,
detail=str(r.get("source") or "keyword_match")[:120],
confidence=0.9,
)],
))
# Boost-Coverage: meine Pattern-Treffer (regex-boost field_ids).
boost_ids = set(telemetry.get("layer_0_field_ids") or [])
for mc in MCS:
coverage.append(McCoverage(
mc_id=mc.mc_id,
status="ok" if mc.field_id in boost_ids else "na",
label=mc.label,
reason=("regex-boost hit"
if mc.field_id in boost_ids
else "kein Pattern-Treffer (kein Veto)"),
))
if not (agent_input.context or {}).get("skip_llm"):
await self._semantic_demote(text, findings, coverage)
confs = [f.confidence for f in findings if f.confidence] or [0.95]
overall = sum(confs) / len(confs)
return self._finalize(
start, findings, esc_logs, coverage,
confidence=overall, notes=" · ".join(notes_parts),
)
async def _semantic_demote(
self, text: str, findings: list[Finding],
coverage: list[McCoverage],
) -> None:
"""LLM-Layer für HIGH/MEDIUM-DB-MCs: Label-Mismatch-Check.
Bei Fund HIGH/MEDIUM LOW + Rename-Action."""
candidates = [
f for f in findings
if f.severity in (Severity.HIGH.value, Severity.MEDIUM.value)
and f.severity_reason in (
"db_mc_failed", "db_mc_failed_third_country_transfer")
]
if not candidates:
return
result = await validate_present(
text, [(f.field_id, f.title[:80]) for f in candidates],
)
if not result:
return
for finding in candidates:
row = result.get(finding.field_id)
if not row or not row.get("found"):
continue
if row.get("confidence", 0) < 0.6:
continue
label_used = row.get("label_used") or "abweichendes Label"
conf = float(row.get("confidence") or 0.8)
finding.severity = Severity.LOW.value
finding.severity_reason = "label_mismatch"
finding.title = (
f"Label '{label_used}' weicht von Standard ab"
)
finding.evidence = str(row.get("evidence") or "")[:200]
finding.action = build_rename_action(
finding.field_id, label_used,
)
finding.confidence = conf
finding.sources.append(EvidenceSource(
source_type=SourceType.LLM_LOCAL,
source_id="semantic_validator",
detail=f"LLM-confirmed: '{label_used}'",
confidence=conf,
))
for c in coverage:
if c.mc_id == finding.field_id:
c.status = "low"
c.reason = f"label_mismatch: '{label_used}'"
try:
record_pattern(
field_id=finding.field_id,
label_used=label_used,
confidence=conf,
agent_id=self.agent_id,
)
except Exception as e:
logger.warning("pattern-library record failed: %s", e)
def _finalize(
self, start: datetime, findings: list[Finding],
esc_logs: list[EscalationLog], coverage: list[McCoverage],
confidence: float, notes: str = "",
) -> AgentOutput:
end = datetime.now(timezone.utc)
recs = rollup(findings)
out = AgentOutput(
agent=self.agent_id,
agent_version=self.agent_version,
started_at=start,
finished_at=end,
duration_ms=int((end - start).total_seconds() * 1000),
findings=findings,
recommendations=recs,
mc_coverage=coverage,
escalation_log=esc_logs,
confidence=confidence,
notes=notes,
mc_total=len(coverage),
mc_ok=sum(1 for c in coverage if c.status == "ok"),
mc_na=sum(1 for c in coverage if c.status == "na"),
mc_high=sum(1 for c in coverage if c.status == "high"),
mc_medium=sum(1 for c in coverage if c.status == "medium"),
mc_low=sum(1 for c in coverage if c.status == "low"),
)
return lint_output(out)
@@ -0,0 +1,129 @@
"""DSE-Tiefenprüfung: LLM-Kaskade auf die UNSCHARFEN Findings.
User-Architektur (2026-06-18): die deterministische Engine (Keyword + Embedding)
triagiert. Eindeutige Fälle (sehr hoher/niedriger Embedding-Score) bleiben
deterministisch. Die UNSCHARFE Mitte + grenzwertig-Bestandene gehen durch die
Kaskade denn dort entstehen sowohl 'verpasste Lücken' (schlimmster Fehler) als
auch Falsch-Findings (Rework).
Eskalation auf ANTWORT-UNSICHERHEIT (nicht JSON-Gültigkeit): jedes Tier liefert
{erfuellt, confidence, begruendung}. Confidence < Schwelle nächstes Tier.
Tier 1: Qwen 35B (lokal, schnell, billig)
Tier 2: OVH gpt-oss-120B
Tier 3: Claude NUR mit Freigabe (allow_claude), sonst 'needs_freigabe'.
Judging-Leitplanken (User-Vorgaben):
- Speicherdauer nur erfüllt bei konkreter Höchstdauer ODER echtem,
nachvollziehbarem Kriterium NICHT zirkulär ('bis Zweck wegfällt').
- Ohne ausreichenden Kontext eher nicht erfüllt (nichts fehlen lassen).
"""
from __future__ import annotations
import json
import logging
import os
from compliance.services.llm_cascade import (
_call_anthropic, _call_ollama, _call_ovh,
)
logger = logging.getLogger(__name__)
# Unscharfe Embedding-Zone (kalibriert an 5-Firmen-GT 2026-06-18): außerhalb ist
# die Engine sicher genug, innen entscheidet der LLM.
FUZZY_LO = float(os.getenv("DSE_FUZZY_LO", "0.50"))
FUZZY_HI = float(os.getenv("DSE_FUZZY_HI", "0.72"))
# Selbstkonfidenz-Schwelle: darunter → eskalieren.
ESC_CONF = float(os.getenv("DSE_ESC_CONF", "0.75"))
_JUDGE_SYS = (
"Du bist ein erfahrener DSGVO-Datenschutz-Auditor. Du prüfst, ob eine "
"konkrete Pflicht in einer Datenschutzerklärung (DSE) ERFÜLLT ist. "
"Sei streng wie ein Fachanwalt: lieber 'nicht erfüllt' wenn unklar — eine "
"übersehene Lücke ist schlimmer als ein Hinweis zu viel. "
"Speicherdauer ist NUR erfüllt bei konkreter Höchstdauer ODER einem echten, "
"nachvollziehbaren Kriterium; zirkuläre Formeln ('bis der Zweck wegfällt') "
"erfüllen die Pflicht NICHT. "
'Antworte AUSSCHLIESSLICH als JSON: '
'{"erfuellt": true|false, "confidence": 0.0-1.0, "begruendung": "kurz"}'
)
def _build_user(doc_text: str, title: str, criteria: list) -> str:
crit = "; ".join(str(c) for c in (criteria or []) if c)[:600]
return (
f"PFLICHT: {title}\n"
f"Erfüllt, wenn: {crit}\n\n"
f"DATENSCHUTZERKLÄRUNG (Auszug):\n{doc_text[:14000]}\n\n"
"Ist die Pflicht im Text inhaltlich erfüllt?"
)
def _parse(text: str) -> dict | None:
if not text:
return None
s, e = text.find("{"), text.rfind("}")
if s < 0 or e <= s:
return None
try:
o = json.loads(text[s:e + 1])
return {
"erfuellt": bool(o.get("erfuellt")),
"confidence": float(o.get("confidence") or 0.0),
"begruendung": str(o.get("begruendung") or "")[:300],
}
except Exception:
return None
async def judge_control(
doc_text: str, title: str, criteria: list, allow_claude: bool = False,
) -> dict:
"""Tiered judgment mit Selbstkonfidenz-Eskalation. Returns
{erfuellt, confidence, source, begruendung, needs_freigabe}."""
user = _build_user(doc_text, title, criteria)
tiers = [("qwen", _call_ollama), ("ovh_120b", _call_ovh)]
best: dict | None = None
for name, call in tiers:
try:
if name == "qwen":
txt = await call(_JUDGE_SYS, user, max_tokens=400,
timeout=60, think=False)
else:
txt = await call(_JUDGE_SYS, user, max_tokens=400)
except Exception as e:
logger.warning("deep_check tier %s failed: %s", name, e)
txt = ""
p = _parse(txt)
if p:
p["source"] = name
best = p
if p["confidence"] >= ESC_CONF:
return {**p, "needs_freigabe": False}
# Tier 3: Claude — nur mit Freigabe
if not allow_claude:
if best:
return {**best, "needs_freigabe": True}
return {"erfuellt": False, "confidence": 0.0, "source": "none",
"begruendung": "Unsicher — Anwalt/Claude-Freigabe nötig",
"needs_freigabe": True}
try:
txt = await _call_anthropic(_JUDGE_SYS, user, max_tokens=400)
p = _parse(txt)
if p:
return {**p, "source": "anthropic_claude", "needs_freigabe": False}
except Exception as e:
logger.warning("deep_check claude failed: %s", e)
if best:
return {**best, "needs_freigabe": False}
return {"erfuellt": False, "confidence": 0.0, "source": "none",
"begruendung": "Kein LLM-Ergebnis", "needs_freigabe": False}
def is_fuzzy(score: float, kw_pass: bool) -> bool:
"""Unscharf = im Embedding-Graubereich UND nicht durch Keyword klar bestätigt.
Klar-bestanden (kw) bleibt deterministisch; klar-hoch/niedrig auch."""
if kw_pass:
return False
return FUZZY_LO <= score <= FUZZY_HI
@@ -0,0 +1,78 @@
"""Machine-Check-Definitionen für den DSE-Agent (Layer-0 Regex-Boost).
Eine MC = ein abgegrenztes Art-13/14-DSGVO-Pflichtfeld mit deterministischen
Patterns. Quelle der Patterns ist die EINE kuratierte ART13_CHECKLIST
(doc_checks/dse_checks.py) hier nur in das MC-Format gehoben, damit der
Regex-Boost (regex_boost.py) und die v3-Engine (v3_engine.py) dieselbe Struktur
nutzen wie impressum/ + cookie_policy/. KEINE Pattern-Duplikation: die Patterns
bleiben in dse_checks.py, dieses Modul kompiliert sie nur.
Owner = dse-agent.
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import Pattern
from compliance.services.doc_checks.dse_checks import ART13_CHECKLIST
@dataclass(frozen=True)
class MC:
"""Eine Machine-Check-Definition (Boost-Pattern für ein DSE-Feld)."""
mc_id: str # DSE-MC-001 ...
field_id: str # controller, legal_basis, third_country ...
label: str
norm: str
patterns: tuple[Pattern[str], ...] = field(default_factory=tuple)
severity_if_missing: str = "MEDIUM"
level: int = 1
_NORM_RE = re.compile(r"\((Art\.[^)]+|§\s*\d+[^)]*)\)")
def _norm_of(label: str) -> str:
m = _NORM_RE.search(label or "")
return m.group(1).strip() if m else "Art. 13/14 DSGVO"
def _compile(patterns: list[str]) -> tuple[Pattern[str], ...]:
out: list[Pattern[str]] = []
for p in patterns or ():
try:
out.append(re.compile(p, re.IGNORECASE | re.MULTILINE))
except re.error:
continue
return tuple(out)
def _build_mcs() -> tuple[MC, ...]:
"""Hebt die ART13_CHECKLIST in das MC-Format (Boost-Pattern pro Feld)."""
mcs: list[MC] = []
for i, c in enumerate(ART13_CHECKLIST, start=1):
mcs.append(MC(
mc_id=f"DSE-MC-{i:03d}",
field_id=c["id"],
label=c["label"],
norm=_norm_of(c["label"]),
patterns=_compile(c.get("patterns", [])),
severity_if_missing=c.get("severity", "MEDIUM"),
level=c.get("level", 1),
))
return tuple(mcs)
MCS: tuple[MC, ...] = _build_mcs()
# Public list of all MC-IDs for the Registry / owned_mc_ids.
MC_IDS: tuple[str, ...] = tuple(m.mc_id for m in MCS)
def scope_matches(mc: MC, scope: set[str]) -> bool:
"""Art-13/14-Pflichten gelten universell für jede DSE — keine Branchen-
Gating auf Boost-Ebene (anders als Impressum mit Kammerberufen). Das
Sektor-Gate über den control_id-Prefix passiert in der v3-Engine."""
return True
@@ -0,0 +1,179 @@
"""Layer-0 Regex-Boost für den DSE-Agent — die kuratierten Art-13/14-Patterns
als deterministische Vor-Stufe vor dem Keyword-Match aus doc_check_controls.
Analog zu impressum/regex_boost.py + cookie_policy/regex_boost.py:
- run_v3_pipeline lädt die 267 text-MCs (doc_type='dse') und macht
Keyword-Match aus deren pass_criteria.
- MEIN Beitrag (Layer 0): die präzisen Art-13-Patterns (mcs.py / aus
ART13_CHECKLIST) laufen ZUERST. Trifft ein Pattern das thematisch
passende DB-MC wird zu PASS geboostet (auch wenn der Keyword-Match unklar
war). Mapping: field_id typische Wörter in der pass_criteria der DB-MC.
Damit gehen die kuratierten DSE-Patterns nicht verloren, sondern boosten das
DB-Control-System (statt es zu ersetzen).
"""
from __future__ import annotations
import logging
from .mcs import MCS, scope_matches
logger = logging.getLogger(__name__)
# field_id (aus ART13_CHECKLIST) → Wörter, wie sie in der pass_criteria der
# zugehörigen DSE-DB-MCs vorkommen. Treffen ≥2 dieser Wörter in den criteria
# eines DB-MC, gehört es zu diesem Feld → Boost. Die Vokabeln sind an den
# real beobachteten DB-Kriterien ausgerichtet (DATA/SEC/AUTH-Controls).
BOOST_KEYWORDS: dict[str, tuple[str, ...]] = {
"controller": (
"verantwortlich", "verantwortliche stelle", "verantwortlichen",
"kontaktdaten des verantwortlichen", "name und kontaktdaten",
"firmenname", "rechtsform", "anschrift", "ladungsfähige",
"identität des verantwortlichen", "controller",
),
"dpo": (
"datenschutzbeauftragt", "datenschutzbeauftragter",
"datenschutzbeauftragte", "data protection officer",
"kontaktdaten des datenschutz", "benennung", "art. 37",
),
"purposes": (
"zweck", "zwecke", "verarbeitungszweck", "zweck der verarbeitung",
"zwecke der verarbeitung", "verarbeitungstätigkeit", "purpose",
"zweckbindung", "erhebung",
),
"legal_basis": (
"rechtsgrundlage", "berechtigte interesse", "berechtigtes interesse",
"einwilligung", "vertragserfüllung", "vertragserfuellung",
"interessenabwägung", "interessenabwaegung", "art. 6",
"rechtmäßigkeit", "rechtmaessigkeit", "erforderlich",
),
"recipients": (
"empfänger", "empfaenger", "empfängerkategorien",
"empfaengerkategorien", "weitergabe", "übermittlung an",
"auftragsverarbeit", "auftragsverarbeiter", "dienstleister",
"dritte", "drittempfänger", "kategorien von empfängern",
),
"third_country": (
"drittland", "drittstaat", "drittländer", "drittlaender",
"standardvertragsklausel", "angemessenheitsbeschluss",
"übermittlung in ein drittland", "geeignete garantien",
"schutzgarantien", "data privacy framework", "ewr",
"internationale übermittlung", "transfermechanismus",
),
"third_country_mechanism": (
"standardvertragsklausel", "angemessenheitsbeschluss",
"geeignete garantien", "data privacy framework",
"schutzgarantien", "art. 46", "art. 45",
),
"retention": (
"speicherdauer", "aufbewahrungsfrist", "aufbewahrungsdauer",
"löschfrist", "loeschfrist", "speicherbegrenzung", "löschung",
"loeschung", "dauer der speicherung", "kriterien für die festlegung",
"speicherfrist", "aufbewahrung",
),
"retention_periods": (
"aufbewahrungsfrist", "löschfrist", "speicherdauer",
"gesetzliche frist", "handelsrechtlich", "steuerrechtlich",
),
"rights": (
"betroffenenrecht", "betroffenenrechte", "recht auf auskunft",
"auskunft", "berichtigung", "löschung", "loeschung",
"einschränkung", "einschraenkung", "datenübertragbarkeit",
"datenuebertragbarkeit", "widerspruch", "widerruf",
"rechte der betroffenen", "art. 15", "art. 17", "art. 21",
),
"complaint": (
"beschwerderecht", "aufsichtsbehörde", "aufsichtsbehoerde",
"datenschutzbehörde", "datenschutzbehoerde", "beschwerde",
"recht auf beschwerde", "art. 77", "zuständige aufsichtsbehörde",
),
"rights_art22_profiling": (
"automatisierte entscheidung", "profiling", "art. 22",
"automatisierte einzelentscheidung", "scoring",
),
"dse_version_date": (
"stand", "letzte aktualisierung", "zuletzt geändert",
"gültig ab", "gueltig ab", "version", "versionsdatum",
"aktualität", "nachweisbarkeit",
),
}
def compute_regex_boosts(text: str, business_scope: set[str] | None = None) -> set[str]:
"""Welche DSE-field_ids haben die kuratierten Patterns erkannt?
Returns die Menge gehit'ter field_ids, über die später entschieden wird,
ob ein DB-MC darüber automatisch passed werden kann. business_scope wird
akzeptiert (Signatur-Parität mit impressum), für DSE aber nicht gegated
Art-13-Pflichten sind universell.
"""
if not text or len(text) < 50:
return set()
scope = business_scope or set()
hits: set[str] = set()
for mc in MCS:
if not scope_matches(mc, scope):
continue
if any(p.search(text) for p in mc.patterns):
hits.add(mc.field_id)
return hits
def boost_matches_db_mc(
boosts: set[str],
pass_criteria: list,
fail_criteria: list | None = None,
) -> str | None:
"""Hat ein gebooster field_id ≥2 Keyword-Überlapp mit den pass/fail_criteria
eines DB-MC? Returns field_id (höchster Match-Count) oder None."""
if not boosts:
return None
crit_parts: list[str] = []
for c in (pass_criteria or []):
if c:
crit_parts.append(str(c).lower())
for c in (fail_criteria or []):
if c:
crit_parts.append(str(c).lower())
if not crit_parts:
return None
crit_text = " ".join(crit_parts)
best: tuple[int, str] | None = None
for field_id in boosts:
kws = BOOST_KEYWORDS.get(field_id) or ()
match_count = sum(1 for kw in kws if kw in crit_text)
if match_count >= 2:
if best is None or match_count > best[0]:
best = (match_count, field_id)
return best[1] if best else None
def criteria_on_topic(
pass_criteria: list | None,
fail_criteria: list | None = None,
min_hits: int = 2,
) -> bool:
"""Deterministischer Themen-Gate: gehört ein DB-MC überhaupt ins DSE-
Themenfeld (Art 13/14)? min_hits unterschiedliche Schlüsselwörter aus
IRGENDEINEM DSE-Feld in den kombinierten criteria. Fängt fremd-getaggte
MCs ab. Leere Kriterien on-topic behalten (konservativ)."""
crit_parts: list[str] = []
for c in (pass_criteria or []):
if c:
crit_parts.append(str(c).lower())
for c in (fail_criteria or []):
if c:
crit_parts.append(str(c).lower())
if not crit_parts:
return True
crit_text = " ".join(crit_parts)
hits: set[str] = set()
for kws in BOOST_KEYWORDS.values():
for kw in kws:
if kw in crit_text:
hits.add(kw)
if len(hits) >= min_hits:
return True
return False
@@ -0,0 +1,251 @@
"""v3-Engine: läuft die 4-Layer-Pipeline auf einem DSE-Text (Art. 13/14 DSGVO).
Layer 0 Regex-Boost (die kuratierten Art-13-Patterns aus mcs.py)
Layer 1 MC-Laden + Keyword-Match. Das LADEN delegiert an die Main-Tool-
Engine (rag_document_checker._load_controls, doc_type='dse'):
eine Quelle der Wahrheit inkl. P72-Scope, check_type='text'
(267 von 571) und fits_doc_type/scope_requires aus dem Sidecar.
Layer 2 BGE-M3 Embedding-Match (mc_embedding_matcher, shared)
Layer 0 Override failed MCs, deren criteria zu einem gebooster field_id
passen, werden zu PASS überschrieben.
Zusätzlich am Agent-Rand: subtraktives Sektor-/Themen-Gate (_filter_controls)
das Sektor-Gate (Branchen-Prefix GOV/FIN/MED) verwirft branchenfremde MCs,
das Themen-Gate fremd-getaggte. Analog impressum/v3_engine.py.
Output: Liste Result-Dicts kompatibel mit rag_document_checker. Der Agent
konvertiert sie zu Finding-Objekten.
"""
from __future__ import annotations
import logging
from typing import Any
from .regex_boost import (
compute_regex_boosts,
criteria_on_topic,
)
logger = logging.getLogger(__name__)
# Branchen-Prefix -> erwarteter Scope-Token. Reuse aus dem Mail-V2-Scope-
# Filter, damit Agent-Pfad und Report-Pfad dieselbe Quelle nutzen. Import
# defensiv: faellt der Mail-Pfad weg, bleibt der Agent lauffaehig.
try:
from compliance.services.mail_render_v2._scope_filter import (
SECTOR_PREFIXES,
)
except Exception: # pragma: no cover - defensiver Fallback
SECTOR_PREFIXES = {}
async def run_v3_pipeline(
text: str,
business_scope: set[str],
db_url: str = "",
skip_embedding: bool = False,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""Returns (results, telemetry).
results: pro DB-MC ein dict {control_id, passed, severity, ...}
telemetry: counters für Frontend-Anzeige (Layer-Aufschlüsselung)
skip_embedding: Layer-2 (BGE-M3 Recall) überspringen. Nur für Unit-Tests
ohne Embedding-Service. Im Betrieb läuft die Recall-Schicht: sie ist
gecacht (pro Doc-Hash) und Reachability-gegated, blockiert also nie.
"""
if not text or len(text) < 100:
return [], {"reason": "text too short"}
# Layer 0: kuratierte Art-13-Patterns
boosts = compute_regex_boosts(text, business_scope)
boost_field_ids = sorted(boosts)
logger.info("dse v3 Layer-0 boosts: %d hits — %s",
len(boost_field_ids), boost_field_ids)
# Layer 1: MC-Laden DELEGIERT an die Main-Tool-Engine (Scope-Schutz inkl.).
try:
from compliance.services.rag_document_checker import _load_controls
controls = await _load_controls(
"dse", db_url, 0, business_scope,
)
except Exception as e:
logger.warning("dse v3 load via main-tool engine failed: %s", e)
controls = []
_normalize_criteria(controls)
# Agent-Rand-Backstop: Sektor-Gate (Branchen-Prefix) + Themen-Gate.
controls, drop_stats = _filter_controls(controls, business_scope)
# Applicability-Gate: hochsichere organisatorische Controls (laut
# control_classification NICHT DSE, needs_review=false) aus dem
# FINDINGS-Scan nehmen -> organisatorische Checkliste statt False-FEHLT.
# Fail-safe: needs_review bleiben drin. Defensiv: fehlt die Tabelle, kein
# Filter (Prod-sicher). Siehe _classification_gate.
from ._classification_gate import apply_gate, load_dse_gate
gate = await load_dse_gate(db_url)
organizational: list[dict[str, Any]] = []
if gate:
controls, organizational = apply_gate(controls, gate)
results: list[dict[str, Any]] = []
if controls:
try:
from compliance.services.rag_document_checker import (
_check_mc_deterministic,
)
text_lower = text.lower().replace("\xad", "")
for mc in controls:
r = _check_mc_deterministic(text_lower, mc)
if r:
r["_pass_criteria"] = mc.get("pass_criteria")
r["_fail_criteria"] = mc.get("fail_criteria")
results.append(r)
except Exception as e:
logger.warning("layer-1 keyword check failed: %s", e)
results = []
layer_1_pass = sum(1 for r in results if r.get("passed"))
# Layer 2: DETERMINISTISCHE semantische Recall-Schicht (BGE-M3, gecacht).
# Ersetzt den früheren Regex-Boost, der auf vollständigen DSE-Dokumenten
# massiv über-passte (BMW: 71/94 Boost-Overrides → 49% Übereinstimmung).
# Embedding ist genauer (BMW-GT: KW|EMB@0.65 = 75%) UND deterministisch
# (feste Funktion, reproduzierbar — kein Keyword-Katalog, kein LLM).
embedding_passes = 0
if not skip_embedding:
failed_cids = [r.get("control_id") for r in results
if r and not r.get("passed") and r.get("control_id")]
if failed_cids:
try:
from ._embedding_recall import embedding_recall
semantic = await embedding_recall(text, failed_cids)
except Exception as e:
logger.warning("dse embedding recall failed: %s", e)
semantic = set()
for r in results:
if (r.get("control_id") in semantic
and not r.get("passed")):
r["passed"] = True
r["matched_text"] = "[semantisch erkannt — Embedding]"
r["source"] = (r.get("source") or "") + "+embedding"
embedding_passes += 1
# Layer 3: getierte 3-Status-Auswertung (nur Controls mit tiered_criteria).
# Reproduzierbar: EMBEDDING-Präsenz (deterministisch) + GECACHTER Haiku-Judge
# nur für Sufficiency. UNBESTIMMT → Legacy-Pass bleibt. Gated + fail-safe.
tiered_evaluated = 0
try:
from compliance.services.checkers.base import DocContext
from ._tiered_eval import (
evaluate_tiered, fetch_tiered_criteria, prepare_doc,
)
result_cids = [r.get("control_id") for r in results if r.get("control_id")]
tiered_map = await fetch_tiered_criteria(result_cids, db_url)
if tiered_map:
ctx = await prepare_doc(text)
doc_ctx = DocContext(text=text)
for r in results:
tc = tiered_map.get(r.get("control_id"))
if not tc:
continue
ev = await evaluate_tiered(r["control_id"], tc, ctx, doc_ctx)
if ev["status"] == "UNBESTIMMT":
continue
r["compliance_status"] = ev["status"]
r["recommendations"] = ev["recommendations"]
r["tier_lm"] = f"{ev['lm_met']}/{ev['lm_total']}"
r["passed"] = ev["status"] == "ERFÜLLT"
tiered_evaluated += 1
except Exception as e:
logger.warning("dse tiered eval skipped: %s", e)
# Layer 4 (SHADOW): Obligation-Aggregation NUR in die Telemetrie. Greift NICHT
# in `results` ein — nutzer-sichtbare Findings bleiben unverändert. Liefert die
# Vergleichszahlen für den späteren Umschalt-Entscheid (collapse_factor etc.).
obligation_shadow: dict[str, Any] = {}
try:
from ._obligation_shadow import build_obligation_shadow
obligation_shadow = await build_obligation_shadow(results, text, db_url)
except Exception as e:
logger.warning("dse obligation shadow skipped: %s", e)
obligation_shadow = {"error": str(e)}
telemetry = {
"layer_0_field_hits": len(boost_field_ids),
"layer_0_field_ids": boost_field_ids,
"layer_1_pass": layer_1_pass,
"embedding_passes": embedding_passes,
"tiered_evaluated": tiered_evaluated,
"total_mcs": len(results),
"sector_dropped": drop_stats.get("sector_dropped", 0),
"offtopic_dropped": drop_stats.get("offtopic_dropped", 0),
"gate_excluded": len(organizational),
"organizational_checklist": organizational,
"obligation_shadow": obligation_shadow,
}
logger.info("dse v3 telemetry: %s", telemetry)
return results, telemetry
def _filter_controls(
controls: list[dict[str, Any]],
business_scope: set[str],
) -> tuple[list[dict[str, Any]], dict[str, int]]:
"""Subtraktiver Scope-Filter VOR der Bewertung.
1. Sektor-Gate MCs deren control_id-Prefix eine Branche bezeichnet
(FIN/GOV/MED/INS/EDU/LEG/REL/POL), die NICHT im business_scope liegt
UND die nicht on-topic ist, werden verworfen.
2. Themen-Gate MCs ohne DSE-Themenüberlapp werden verworfen.
Rein subtraktiv: entfernt nur falsch-positive Kandidaten.
"""
scope_lc = {s.lower() for s in (business_scope or set())}
kept: list[dict[str, Any]] = []
sector_dropped = 0
offtopic_dropped = 0
for c in controls:
cid = c.get("control_id") or ""
prefix = cid.split("-")[0].upper() if "-" in cid else ""
on_topic = criteria_on_topic(c.get("pass_criteria"),
c.get("fail_criteria"))
required = SECTOR_PREFIXES.get(prefix)
# Sektor-Gate nur fuer NICHT-on-topic Controls: ein klar DSE-
# thematischer Control (z.B. GOV-Prefix aus der Domain-Erkennung)
# darf nicht am Branchen-Prefix scheitern.
if required and not (scope_lc & required) and not on_topic:
sector_dropped += 1
continue
if not on_topic:
offtopic_dropped += 1
continue
kept.append(c)
if sector_dropped or offtopic_dropped:
logger.info(
"dse v3 scope-filter: -%d Branchen-MCs, -%d themenfremde MCs "
"(scope=%s)", sector_dropped, offtopic_dropped,
sorted(scope_lc) or "leer",
)
return kept, {
"sector_dropped": sector_dropped,
"offtopic_dropped": offtopic_dropped,
}
def _normalize_criteria(controls: list[dict[str, Any]]) -> None:
"""asyncpg liefert JSONB-Spalten (pass_criteria/fail_criteria) als
Roh-String. In echte Listen parsen, damit Sektor-/Themen-Gate und der
Boost-Layer Element-weise iterieren."""
import json
for c in controls:
for key in ("pass_criteria", "fail_criteria"):
v = c.get(key)
if isinstance(v, list):
continue
if isinstance(v, str):
try:
parsed = json.loads(v)
c[key] = parsed if isinstance(parsed, list) else [v]
except Exception:
c[key] = [v] if v else []
else:
c[key] = []
@@ -1,12 +1,27 @@
"""AGBAgent — kuratierte §§-305-ff-BGB-Checkliste (ChecklistAgent-Subclass)."""
from __future__ import annotations
"""AGBAgent (v2, routed). Embedding/LLM offline-gestubbt → kein Netzwerk."""
import asyncio
import pytest
import compliance.services.specialist_agents.agb._pipeline as pipeline
from compliance.services.checkers.base import CheckResult
from compliance.services.specialist_agents import REGISTRY, AgentInput
class _Stub:
def __init__(self, present):
self._p = present
async def check(self, ctrl, doc):
return CheckResult(present=self._p)
@pytest.fixture(autouse=True)
def _offline(monkeypatch):
monkeypatch.setattr(pipeline, "_EMB", _Stub(None))
monkeypatch.setattr(pipeline, "_LLM", _Stub(None))
def _run(text: str):
return asyncio.run(
REGISTRY.get("agb").evaluate(AgentInput(doc_type="agb", text=text)))
@@ -0,0 +1,62 @@
"""AGB routed-Pipeline: Gate, Reference-/Embedding-Rescue, LLM-skip, Re-Tiering.
Embedding + LLM offline-gestubbt deterministisch, kein Netzwerk (Reference = echtes Regex)."""
import asyncio
from types import SimpleNamespace
import pytest
import compliance.services.specialist_agents.agb._pipeline as pipeline
from compliance.services.checkers.base import CheckResult
from compliance.services.specialist_agents._base import AgentInput
from compliance.services.specialist_agents.agb.agent import AGBAgent
class _Stub:
def __init__(self, present):
self._p = present
async def check(self, ctrl, doc):
return CheckResult(present=self._p)
@pytest.fixture(autouse=True)
def _offline(monkeypatch):
monkeypatch.setattr(pipeline, "_EMB", _Stub(None))
monkeypatch.setattr(pipeline, "_LLM", _Stub(None))
def _routed(field_ids, text, context=None):
findings = [SimpleNamespace(field_id=fid) for fid in field_ids]
return asyncio.run(pipeline.run_routed(findings, text, context or {}))
def test_gate_termination_na_for_oneoff_shop():
text = "Widerrufsbelehrung: Sie koennen binnen 14 Tagen widerrufen. " * 5
kept, resolved, gated = _routed(["termination", "termination_form"], text)
assert set(gated) == {"termination", "termination_form"}
assert kept == []
def test_reference_rescues_data_protection():
text = "Einzelheiten zur Verarbeitung in unserer Datenschutzerklaerung. " * 5
kept, resolved, gated = _routed(["data_protection"], text)
assert "data_protection" in resolved and kept == []
def test_embedding_rescue_resolves(monkeypatch):
monkeypatch.setattr(pipeline, "_EMB", _Stub(True))
kept, resolved, gated = _routed(["scope"], "x" * 200)
assert "scope" in resolved
def test_llm_skipped_keeps_finding():
kept, resolved, gated = _routed(["delivery_timeframe"], "x" * 200, {"skip_llm": True})
assert [f.field_id for f in kept] == ["delivery_timeframe"] and resolved == []
def test_evaluate_retiers_low_out_of_findings():
text = ("Allgemeine Geschaeftsbedingungen. Vertragsschluss durch Bestellung. "
"Haftung beschraenkt. Gerichtsstand Muenchen. ") * 6
out = asyncio.run(AGBAgent().evaluate(AgentInput(doc_type="agb", text=text)))
assert out.agent == "agb" and out.agent_version == "2.0"
assert all(f.severity in ("HIGH", "MEDIUM") for f in out.findings)
@@ -0,0 +1,14 @@
"""AGB muss im LIVE-Pfad verdrahtet sein (_TOPIC_AGENTS), nicht nur per Snapshot."""
from compliance.api.agent_check._agent_outputs import _TOPIC_AGENTS
def test_agb_wired_into_live_topic_agents():
assert _TOPIC_AGENTS.get("agb") == "agb"
def test_dse_wired_into_live_topic_agents():
assert _TOPIC_AGENTS.get("dse") == "dse"
def test_impressum_still_wired():
assert _TOPIC_AGENTS.get("impressum") == "impressum"
@@ -0,0 +1,83 @@
"""Unit-Tests der Prüfer-Library. Embedding + LLM gemockt → kein Netzwerk."""
import asyncio
import compliance.services.llm_cascade as cascade_mod
import compliance.services.mc_embedding_matcher as emb_mod
from compliance.services.checkers.base import (
ControlSpec,
DecisionMethod,
DocContext,
VerificationMethod,
)
from compliance.services.checkers.embedding_checker import EmbeddingChecker
from compliance.services.checkers.llm_checker import LLMChecker
from compliance.services.checkers.reference_checker import ReferenceChecker
def _run(coro):
return asyncio.run(coro)
def test_reference_present_and_absent():
rc = ReferenceChecker()
spec = ControlSpec("data_protection", VerificationMethod.REFERENCE,
DecisionMethod.LINK_RESOLVER,
patterns=[r"datenschutz(erkl|bestimmung|hinweis)"])
r = _run(rc.check(spec, DocContext(
text="Details in unserer Datenschutzerklaerung: https://x.de/datenschutz")))
assert r.present is True
assert r.detail.get("link", "").startswith("https://")
r2 = _run(rc.check(spec, DocContext(text="Keine Angabe zum Datenschutz-Thema.")))
assert r2.present is False
def test_embedding_threshold(monkeypatch):
monkeypatch.setattr(emb_mod, "DIM", 3, raising=False)
monkeypatch.setattr(emb_mod, "_chunk_text", lambda t: [t], raising=False)
async def _embed(texts):
return [[1.0, 0.0, 0.0] for _ in texts]
monkeypatch.setattr(emb_mod, "_embed_texts", _embed, raising=False)
ec = EmbeddingChecker()
spec = ControlSpec("scope_t", VerificationMethod.CONTENT, DecisionMethod.EMBEDDING,
paraphrases=["Geltungsbereich"], embed_threshold=0.58)
monkeypatch.setattr(emb_mod, "_cosine", lambda a, b: 0.90, raising=False)
r = _run(ec.check(spec, DocContext(text="x" * 200)))
assert r.present is True and r.confidence >= 0.58
monkeypatch.setattr(emb_mod, "_cosine", lambda a, b: 0.20, raising=False)
r2 = _run(ec.check(spec, DocContext(text="x" * 200)))
assert r2.present is False
def test_embedding_offline_returns_none(monkeypatch):
async def _boom(texts):
raise ConnectionError("embedding-service down")
monkeypatch.setattr(emb_mod, "_embed_texts", _boom, raising=False)
ec = EmbeddingChecker()
spec = ControlSpec("scope_off", VerificationMethod.CONTENT, DecisionMethod.EMBEDDING,
paraphrases=["x"], embed_threshold=0.6)
r = _run(ec.check(spec, DocContext(text="y" * 200)))
assert r.present is None # fail-safe
def test_llm_present_and_absent(monkeypatch):
lc = LLMChecker()
spec = ControlSpec("delivery_timeframe", VerificationMethod.CONTENT, DecisionMethod.LLM,
topic_regex=r"liefer", question="Konkrete Lieferfrist?")
doc = DocContext(text=("1. Lieferung\nDie Ware wird innerhalb von 2 Werktagen "
"geliefert.\n") * 4)
async def _erfuellt(system, user, **kw):
return {"text": '{"verdict":"ERFUELLT","zitat":"2 Werktagen","begruendung":"x"}',
"source": "qwen", "confidence": 0.7}
monkeypatch.setattr(cascade_mod, "call_with_cascade", _erfuellt, raising=False)
assert _run(lc.check(spec, doc)).present is True
async def _fehlt(system, user, **kw):
return {"text": '{"verdict":"FEHLT"}', "source": "qwen"}
monkeypatch.setattr(cascade_mod, "call_with_cascade", _fehlt, raising=False)
assert _run(lc.check(spec, doc)).present is False
@@ -1,65 +1,153 @@
"""DSEAgent — kuratierte Art-13/14-Checkliste (kein Library-Firehose)."""
"""DSE-Agent v3 — DB-Controls (doc_check_controls) via run_v3_pipeline +
kuratierter Art-13-Regex-Boost (Layer 0). Volle Parität zu impressum/cookie.
Die Tests prüfen die deterministischen Bausteine (regex_boost/mcs) ohne DB und
den Agent-Pfad mit gemocktem run_v3_pipeline (CI hat keine DB).
"""
from __future__ import annotations
import asyncio
import compliance.services.specialist_agents.dse.agent as dse_agent
from compliance.services.specialist_agents import REGISTRY, AgentInput
from compliance.services.specialist_agents.dse.mcs import MCS, MC_IDS
from compliance.services.specialist_agents.dse.regex_boost import (
boost_matches_db_mc,
compute_regex_boosts,
criteria_on_topic,
)
def _run(text: str):
return asyncio.run(
REGISTRY.get("dse").evaluate(AgentInput(doc_type="dse", text=text)))
def test_dse_agent_registered():
assert REGISTRY.get("dse") is not None
def test_dse_detects_core_obligations():
text = (
"Datenschutzerklaerung. Verantwortlich im Sinne der DSGVO ist die "
"Muster GmbH, Musterstrasse 1, 12345 Berlin. E-Mail: info@muster.de. "
_DSE_SAMPLE = (
"Datenschutzerklaerung. Verantwortlich im Sinne der DSGVO ist die Muster "
"GmbH, Musterstrasse 1, 12345 Berlin. E-Mail: info@muster.de. "
"Datenschutzbeauftragter: dsb@muster.de. Zwecke der Verarbeitung und "
"Rechtsgrundlage Art. 6 Abs. 1. Empfaenger Ihrer Daten. Speicherdauer "
"der Daten. Ihre Rechte: Auskunft, Loeschung, Widerspruch, Beschwerde "
"bei der Aufsichtsbehoerde. ") * 3
out = _run(text)
assert out.agent == "dse"
# 10 L1-Pflichtangaben immer + L2-Details deren Parent vorhanden ist
# (fehlende Parents → L2 übersprungen, kein 'na'-Rauschen).
assert 10 <= out.mc_total <= 33
ok = [c.label for c in out.mc_coverage if c.status == "ok"]
assert any("Verantwortlich" in lbl for lbl in ok)
assert any("Rechtsgrundlage" in lbl for lbl in ok)
"Rechtsgrundlage Art. 6 Abs. 1 lit. f berechtigtes Interesse. Empfaenger "
"Ihrer Daten sind Auftragsverarbeiter. Speicherdauer der Daten richtet "
"sich nach Aufbewahrungsfristen. Sie haben das Recht auf Auskunft, das "
"Recht auf Berichtigung, das Recht auf Loeschung sowie ein "
"Widerspruchsrecht. Beschwerde bei der Aufsichtsbehoerde moeglich. Stand: "
"Januar 2026. ") * 3
def test_dse_missing_obligations_are_findings():
out = _run("Lorem ipsum dolor sit amet consectetur adipiscing elit. " * 6)
assert out.findings
assert any(f.severity == "HIGH" for f in out.findings)
# ── Registrierung ────────────────────────────────────────────────────────
def test_dse_agent_registered():
agent = REGISTRY.get("dse")
assert agent is not None
assert agent.agent_version == "3.0"
assert agent.doc_type == "dse"
def test_owned_mc_ids_match_checklist():
# owned_mc_ids = die Boost-Pattern-IDs (aus ART13_CHECKLIST gehoben).
assert MC_IDS == tuple(m.mc_id for m in MCS)
assert len(MC_IDS) >= 10 # mind. die 10 L1-Pflichtfelder + L2
# ── Layer-0 Regex-Boost (deterministisch, ohne DB) ───────────────────────
def test_regex_boost_detects_core_fields():
boosts = compute_regex_boosts(_DSE_SAMPLE)
# Die zentralen Art-13-Felder müssen erkannt werden.
for field in ("controller", "legal_basis", "rights", "complaint",
"retention", "dse_version_date"):
assert field in boosts, f"{field} nicht erkannt: {sorted(boosts)}"
def test_regex_boost_empty_on_short_text():
assert compute_regex_boosts("zu kurz") == set()
def test_criteria_on_topic_accepts_dse_rejects_foreign():
dse_crit = ["Rechtsgrundlage gemäß Art. 6 DSGVO benannt",
"Speicherdauer und Löschfrist angegeben"]
assert criteria_on_topic(dse_crit) is True
foreign = ["Bestellbestätigung wird per E-Mail versendet",
"Versandkosten werden im Warenkorb angezeigt"]
assert criteria_on_topic(foreign) is False
# leere Kriterien → konservativ on-topic behalten
assert criteria_on_topic([]) is True
def test_boost_matches_db_mc_third_country():
boosts = {"third_country", "controller"}
crit = ["Standardvertragsklauseln für Drittland benannt",
"Geeignete Garantien bei Übermittlung in ein Drittland"]
assert boost_matches_db_mc(boosts, crit) == "third_country"
# ohne passende Boosts → None
assert boost_matches_db_mc(set(), crit) is None
# ── Agent-Pfad mit gemocktem run_v3_pipeline ─────────────────────────────
def _mock_v3(results, telemetry=None):
async def _fake(text, scope, db_url="", skip_embedding=False):
return results, (telemetry or {
"total_mcs": len(results), "layer_0_field_hits": 0,
"layer_0_field_ids": [], "layer_0_boost_overrides": 0,
"sector_dropped": 0, "offtopic_dropped": 0})
return _fake
def _run(text, context=None):
return asyncio.run(REGISTRY.get("dse").evaluate(
AgentInput(doc_type="dse", text=text, context=context or {})))
def test_dse_short_text_skips():
out = _run("zu kurz")
assert out.confidence == 0.0
assert all(c.status == "skipped" for c in out.mc_coverage)
assert out.mc_coverage and all(
c.status == "skipped" for c in out.mc_coverage)
def test_third_country_high_when_applicable_no_na_detail_short_action():
# Text ohne Drittland-Abschnitt + Scan-Kontext drittland=ja:
# - third_country (L1) fehlt → HIGH (nicht weiches MEDIUM)
# - Transfermechanismus (L2) → KEIN 'na' (übersprungen, Parent deckt ab)
# - Titel/Maßnahme kurz (kein 280-Zeichen-Hint als Recommendation-Titel)
text = ("Datenschutz. Verantwortlich ist die Muster GmbH, info@muster.de. "
"Zwecke und Rechtsgrundlage Art. 6. Speicherdauer. Ihre Rechte. ") * 4
out = asyncio.run(REGISTRY.get("dse").evaluate(AgentInput(
doc_type="dse", text=text,
context={"scan_context": {"third_country_transfer": "yes"}})))
tc = [f for f in out.findings if "Drittland" in f.title]
assert tc and tc[0].severity == "HIGH"
assert not any(c.status == "na" and "Transfermechanismus" in c.label
for c in out.mc_coverage)
assert all(len(f.action) < 110 for f in out.findings)
# Detail-Begründung bleibt als evidence erhalten
assert any(f.evidence for f in out.findings)
def test_dse_findings_from_failed_db_mc(monkeypatch):
results = [{
"control_id": "DATA-525-A17", "passed": False, "severity": "HIGH",
"label": "Berechtigte Interessen ausweisen", "regulation": None,
"article": None, "_pass_criteria": ["berechtigtes interesse benannt"],
"matched_text": "", "source": "keyword_match",
}, {
"control_id": "AUTH-2051-A11", "passed": True, "severity": "LOW",
"label": "Prägnante Form", "regulation": None, "article": None,
"_pass_criteria": [], "matched_text": "ok",
}]
monkeypatch.setattr(dse_agent, "run_v3_pipeline", _mock_v3(results))
out = _run(_DSE_SAMPLE, context={"skip_llm": True})
fids = {f.field_id for f in out.findings}
assert "DATA-525-A17" in fids # failed → Finding
assert "AUTH-2051-A11" not in fids # passed → kein Finding
f = next(f for f in out.findings if f.field_id == "DATA-525-A17")
assert f.severity == "HIGH"
assert f.norm == "DSGVO Art. 13/14" # NULL-regulation → Fallback-Norm
assert len(f.action) < 410
def test_dse_third_country_override_to_high(monkeypatch):
# MEDIUM-Drittland-MC → HIGH bei dokumentiertem Transfer (scan_context).
results = [{
"control_id": "DATA-900-A01", "passed": False, "severity": "MEDIUM",
"label": "Drittlandtransfer Schutzgarantien benennen",
"regulation": None, "article": None,
"_pass_criteria": ["standardvertragsklauseln", "drittland garantien"],
"matched_text": "", "source": "keyword_match",
}]
monkeypatch.setattr(dse_agent, "run_v3_pipeline", _mock_v3(results))
out = _run(_DSE_SAMPLE, context={
"skip_llm": True,
"scan_context": {"third_country_transfer": "yes"}})
f = next(f for f in out.findings if f.field_id == "DATA-900-A01")
assert f.severity == "HIGH"
assert f.severity_reason == "db_mc_failed_third_country_transfer"
def test_dse_no_transfer_keeps_medium(monkeypatch):
results = [{
"control_id": "DATA-900-A01", "passed": False, "severity": "MEDIUM",
"label": "Drittlandtransfer Schutzgarantien benennen",
"regulation": None, "article": None,
"_pass_criteria": ["standardvertragsklauseln", "drittland garantien"],
"matched_text": "", "source": "keyword_match",
}]
monkeypatch.setattr(dse_agent, "run_v3_pipeline", _mock_v3(results))
out = _run(_DSE_SAMPLE, context={"skip_llm": True})
f = next(f for f in out.findings if f.field_id == "DATA-900-A01")
assert f.severity == "MEDIUM"
@@ -0,0 +1,59 @@
"""Tests fuer das DSE-Applicability-Gate (_classification_gate).
Deckt die reine Split-Logik (apply_gate) und das defensive Verhalten von
load_dse_gate ohne DB ab. Die DB-Abfrage selbst ist I/O und wird hier nicht
gegen eine echte DB getestet (defensiver Pfad: kein DSN -> leeres Dict)."""
import asyncio
import os
from compliance.services.specialist_agents.dse._classification_gate import (
apply_gate,
load_dse_gate,
)
def test_apply_gate_splits_findings_and_organizational():
controls = [
{"control_id": "AUTH-2051-A02", "title": "Speicherdauer nennen"},
{"control_id": "AUTH-2049-A01", "title": "VVT fuehren"},
]
gate = {
"AUTH-2049-A01": {
"obligation_type": "EVIDENCE",
"check_intent": "DIRECT_EVIDENCE",
"applicable_artifacts": ["VVT", "AUDIT"],
"reference_allowed": "NO",
}
}
kept, organizational = apply_gate(controls, gate)
assert [c["control_id"] for c in kept] == ["AUTH-2051-A02"]
assert len(organizational) == 1
org = organizational[0]
assert org["control_id"] == "AUTH-2049-A01"
assert org["title"] == "VVT fuehren"
assert org["applicable_artifacts"] == ["VVT", "AUDIT"]
assert org["check_intent"] == "DIRECT_EVIDENCE"
def test_apply_gate_empty_gate_keeps_all():
controls = [{"control_id": "X-1"}, {"control_id": "X-2"}]
kept, organizational = apply_gate(controls, {})
assert len(kept) == 2
assert organizational == []
def test_load_dse_gate_without_dsn_is_defensive():
"""Kein DSN + keine Env -> leeres Dict (kein Filter), kein Fehler."""
saved = (
os.environ.pop("DATABASE_URL", None),
os.environ.pop("COMPLIANCE_DATABASE_URL", None),
)
try:
result = asyncio.run(load_dse_gate(""))
assert result == {}
finally:
if saved[0] is not None:
os.environ["DATABASE_URL"] = saved[0]
if saved[1] is not None:
os.environ["COMPLIANCE_DATABASE_URL"] = saved[1]
@@ -0,0 +1,67 @@
"""DSE Embedding-Recall — deterministische semantische Schicht (gecacht).
Testet die reine Logik OHNE Embedding-Service: Cache-Treffer-Pfad,
Schwellen-Filter, Kandidaten-Schnitt, Reachability-Guard. Das Einbetten selbst
(Embedding-Service) ist Integration und wird auf macmini/Prod validiert.
"""
from __future__ import annotations
import asyncio
import json
import compliance.services.specialist_agents.dse._embedding_recall as er
_TEXT = ("Datenschutzerklaerung der Muster GmbH. " * 20) # > 100 Zeichen
def _seed_cache(tmp_path, scores: dict[str, float]) -> str:
p = tmp_path / "dse_embed_cache.json"
p.write_text(json.dumps({er._doc_hash(_TEXT): scores}))
return str(p)
def test_doc_hash_deterministic():
# feste Funktion: gleicher Text → gleicher Hash (Reproduzierbarkeit)
assert er._doc_hash(_TEXT) == er._doc_hash(_TEXT)
assert er._doc_hash("a") != er._doc_hash("b")
def test_cache_hit_threshold_filter(tmp_path, monkeypatch):
# Cache-Treffer: kein Embedding-Service nötig. Nur Scores >= Schwelle UND
# in den Kandidaten werden zurückgegeben.
scores = {"DATA-1": 0.71, "DATA-2": 0.60, "AUTH-3": 0.68, "SEC-4": 0.50}
monkeypatch.setenv("DSE_EMBED_CACHE", _seed_cache(tmp_path, scores))
monkeypatch.setattr(er, "_CACHE_PATH", str(tmp_path / "dse_embed_cache.json"))
cands = ["DATA-1", "DATA-2", "AUTH-3", "SEC-4"]
out = asyncio.run(er.embedding_recall(_TEXT, cands, threshold=0.65))
# >=0.65: DATA-1 (0.71), AUTH-3 (0.68). NICHT DATA-2 (0.60), SEC-4 (0.50).
assert out == {"DATA-1", "AUTH-3"}
def test_cache_hit_candidate_intersection(tmp_path, monkeypatch):
# Nur Kandidaten (durchgefallene Controls) zählen — andere ignoriert.
scores = {"DATA-1": 0.90, "DATA-2": 0.90}
monkeypatch.setattr(er, "_CACHE_PATH", str(tmp_path / "c.json"))
(tmp_path / "c.json").write_text(json.dumps({er._doc_hash(_TEXT): scores}))
out = asyncio.run(er.embedding_recall(_TEXT, ["DATA-1"], threshold=0.65))
assert out == {"DATA-1"} # DATA-2 nicht in Kandidaten
def test_empty_inputs():
assert asyncio.run(er.embedding_recall("zu kurz", ["X"])) == set()
assert asyncio.run(er.embedding_recall(_TEXT, [])) == set()
def test_service_down_returns_empty(tmp_path, monkeypatch):
# Kein Cache + Service nicht erreichbar → leer (deterministischer Layer trägt),
# KEIN Hang.
monkeypatch.setattr(er, "_CACHE_PATH", str(tmp_path / "none.json"))
async def _unreachable(timeout=2.0):
return False
monkeypatch.setattr(er, "_embedding_reachable", _unreachable)
out = asyncio.run(er.embedding_recall(_TEXT, ["DATA-1"]))
assert out == set()
@@ -0,0 +1,51 @@
"""Prüfer-Router: build_spec aus sensor_classification + method-agnostischer
Dispatch. CONTENT/LLM -> Haiku-Sufficiency-Tier (validiert), unbekannte
decision_methods -> fail-safe present=None."""
import pytest
from unittest.mock import AsyncMock, patch
from compliance.services.checkers.base import DocContext
from compliance.services.checkers.router import build_spec, route_and_check
_ANTHROPIC = "compliance.services.llm_cascade._call_anthropic"
def test_build_spec_content_llm_uses_haiku():
s = build_spec("X", {"verification_method": "CONTENT", "decision_method": "LLM"},
label="L", criteria=["a", "b"])
assert s.verification_method == "CONTENT" and s.decision_method == "LLM"
assert s.extra.get("judge") == "haiku"
assert s.paraphrases == ["a", "b"]
def test_build_spec_embedding_no_haiku():
s = build_spec("X", {"verification_method": "CONTENT", "decision_method": "EMBEDDING"})
assert s.extra.get("judge") is None
@pytest.mark.asyncio
async def test_route_unknown_decision_is_failsafe():
s = build_spec("X", {"verification_method": "BEHAVIOR", "decision_method": "PLAYWRIGHT"})
r = await route_and_check(s, DocContext(text="x" * 200))
assert r.present is None and "no_checker" in r.source
@pytest.mark.asyncio
async def test_route_content_llm_haiku_fehlt():
s = build_spec("X", {"verification_method": "CONTENT", "decision_method": "LLM"},
label="Speicherdauer", criteria=["Höchstdauer pro Kategorie"])
fake = AsyncMock(return_value='{"erfuellt": false, "confidence": 0.9, "begruendung": "fehlt"}')
with patch(_ANTHROPIC, new=fake):
r = await route_and_check(s, DocContext(text="Wir nutzen Cookies. " * 30))
assert r.present is False and r.source == "haiku"
assert fake.call_count >= 1
@pytest.mark.asyncio
async def test_route_content_llm_haiku_erfuellt():
s = build_spec("X", {"verification_method": "CONTENT", "decision_method": "LLM"},
label="L", criteria=["x"])
fake = AsyncMock(return_value='{"erfuellt": true, "confidence": 0.8}')
with patch(_ANTHROPIC, new=fake):
r = await route_and_check(s, DocContext(text="text " * 40))
assert r.present is True
@@ -0,0 +1,42 @@
"""Tests for the cookie-policy applicability gate: controls without a
COOKIE_POLICY artifact are routed out of the findings scan (not deleted),
and the gate is fail-safe (no DSN -> no filter)."""
import pytest
from compliance.services.specialist_agents.cookie_policy._classification_gate import (
apply_gate, load_cookie_gate,
)
def test_apply_gate_splits_kept_and_routed():
controls = [
{"control_id": "COOK-1", "title": "Kategorien"},
{"control_id": "TOM-1", "title": "Verschlüsselung"},
{"control_id": "BAN-1", "title": "Consent vor Setzen"},
]
gate = {
"TOM-1": {"obligation_type": "TECHNICAL", "check_intent": "DIRECT_TECHNICAL",
"applicable_artifacts": ["TOM", "AUDIT"]},
"BAN-1": {"obligation_type": "TECHNICAL", "check_intent": "DIRECT_TECHNICAL",
"applicable_artifacts": ["COOKIE_BANNER", "SYSTEMSCAN"]},
}
kept, routed = apply_gate(controls, gate)
assert [c["control_id"] for c in kept] == ["COOK-1"]
assert {c["control_id"] for c in routed} == {"TOM-1", "BAN-1"}
# routed entries carry title + classification metadata for downstream routing
tom = next(c for c in routed if c["control_id"] == "TOM-1")
assert tom["title"] == "Verschlüsselung"
assert tom["applicable_artifacts"] == ["TOM", "AUDIT"]
def test_apply_gate_empty_gate_keeps_all():
controls = [{"control_id": "A"}, {"control_id": "B"}]
kept, routed = apply_gate(controls, {})
assert len(kept) == 2 and routed == []
@pytest.mark.asyncio
async def test_load_cookie_gate_no_dsn_is_failsafe(monkeypatch):
monkeypatch.delenv("DATABASE_URL", raising=False)
monkeypatch.delenv("COMPLIANCE_DATABASE_URL", raising=False)
assert await load_cookie_gate("") == {}
@@ -0,0 +1,68 @@
"""Layer-3 cookie sufficiency-judge: only embedding/boost-RESCUED passes are
re-judged by Haiku; keyword passes are untouched; a FEHLT verdict un-passes."""
import pytest
from unittest.mock import AsyncMock, patch
from compliance.services.specialist_agents.cookie_policy._sufficiency_judge import (
judge_rescued,
)
_ANTHROPIC = "compliance.services.llm_cascade._call_anthropic"
_DOC = "Volltext der Cookie-Richtlinie mit ausreichend Inhalt. " * 4
def _r(cid, source, passed=True):
return {"control_id": cid, "source": source, "passed": passed,
"label": cid, "_pass_criteria": ["konkrete Angabe nötig"]}
@pytest.mark.asyncio
async def test_rescued_unpassed_when_judge_fehlt():
results = [_r("A", "keyword+embedding")]
fake = AsyncMock(return_value='{"erfuellt": false, "confidence": 0.9, "begruendung": "fehlt"}')
with patch(_ANTHROPIC, new=fake):
n = await judge_rescued(_DOC, results)
assert n == 1
assert results[0]["passed"] is False
assert "+llm_failed" in results[0]["source"]
@pytest.mark.asyncio
async def test_rescued_kept_when_judge_erfuellt():
results = [_r("A", "keyword+embedding")]
fake = AsyncMock(return_value='{"erfuellt": true, "confidence": 0.9}')
with patch(_ANTHROPIC, new=fake):
n = await judge_rescued(_DOC, results)
assert n == 0
assert results[0]["passed"] is True
@pytest.mark.asyncio
async def test_keyword_pass_not_judged():
"""Deterministisch (keyword) bestandene Controls werden NICHT befragt."""
results = [_r("A", "keyword")]
fake = AsyncMock(return_value='{"erfuellt": false}')
with patch(_ANTHROPIC, new=fake):
n = await judge_rescued(_DOC, results)
assert n == 0
assert results[0]["passed"] is True
assert fake.call_count == 0
@pytest.mark.asyncio
async def test_boost_rescue_is_judged():
results = [_r("A", "keyword+regex_boost")]
fake = AsyncMock(return_value='{"erfuellt": false}')
with patch(_ANTHROPIC, new=fake):
n = await judge_rescued(_DOC, results)
assert n == 1 and results[0]["passed"] is False
@pytest.mark.asyncio
async def test_failed_controls_ignored():
"""Nicht-bestandene (failed) Controls sind nicht Sache dieser Schicht."""
results = [_r("A", "keyword+embedding", passed=False)]
fake = AsyncMock(return_value='{"erfuellt": false}')
with patch(_ANTHROPIC, new=fake):
n = await judge_rescued(_DOC, results)
assert n == 0 and fake.call_count == 0
@@ -0,0 +1,77 @@
"""Regression tests for the OVH (gpt-oss-120b) tier of the LLM cascade.
gpt-oss-120b is a reasoning model: it spends output tokens on chain-of-thought
before the answer. Two bugs this pins:
1. A small max_tokens (deep_check passed 400) length-caps it mid-reasoning
content=null the tier silently returns nothing. _call_ovh must floor the
budget so reasoning + the JSON answer fit.
2. When length-capped, the JSON can land in reasoning_content, not content
_call_ovh must fall back to reasoning_content.
"""
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from compliance.services import llm_cascade
def _resp(data):
r = MagicMock()
r.raise_for_status = MagicMock()
r.json = MagicMock(return_value=data)
return r
def _client(resp):
inst = AsyncMock()
inst.post.return_value = resp
inst.__aenter__ = AsyncMock(return_value=inst)
inst.__aexit__ = AsyncMock(return_value=False)
return inst
class TestCallOvhReasoning:
@pytest.mark.asyncio
async def test_reasoning_content_used_when_content_null(self, monkeypatch):
monkeypatch.setenv("OVH_LLM_URL", "https://llm.example.com")
monkeypatch.setenv("OVH_LLM_MODEL", "gpt-oss-120b")
monkeypatch.setenv("OVH_LLM_KEY", "k")
resp = _resp({"choices": [{"message": {
"content": None,
"reasoning_content": '{"erfuellt": true, "confidence": 0.9}'}}]})
with patch("httpx.AsyncClient", return_value=_client(resp)):
out = await llm_cascade._call_ovh("sys", "user", max_tokens=400)
assert '"erfuellt": true' in out
@pytest.mark.asyncio
async def test_small_budget_is_floored(self, monkeypatch):
monkeypatch.setenv("OVH_LLM_URL", "https://llm.example.com")
monkeypatch.setenv("OVH_LLM_MODEL", "gpt-oss-120b")
inst = _client(_resp({"choices": [{"message": {"content": "{}"}}]}))
with patch("httpx.AsyncClient", return_value=inst):
await llm_cascade._call_ovh("sys", "user", max_tokens=400)
assert inst.post.call_args.kwargs["json"]["max_tokens"] >= 2000
@pytest.mark.asyncio
async def test_large_budget_is_preserved(self, monkeypatch):
monkeypatch.setenv("OVH_LLM_URL", "https://llm.example.com")
monkeypatch.setenv("OVH_LLM_MODEL", "gpt-oss-120b")
inst = _client(_resp({"choices": [{"message": {"content": "{}"}}]}))
with patch("httpx.AsyncClient", return_value=inst):
await llm_cascade._call_ovh("sys", "user", max_tokens=6000)
assert inst.post.call_args.kwargs["json"]["max_tokens"] == 6000
@pytest.mark.asyncio
async def test_content_preferred_when_present(self, monkeypatch):
monkeypatch.setenv("OVH_LLM_URL", "https://llm.example.com")
monkeypatch.setenv("OVH_LLM_MODEL", "gpt-oss-120b")
resp = _resp({"choices": [{"message": {
"content": '{"erfuellt": false}', "reasoning_content": "noise"}}]})
with patch("httpx.AsyncClient", return_value=_client(resp)):
out = await llm_cascade._call_ovh("sys", "user")
assert out == '{"erfuellt": false}'
@pytest.mark.asyncio
async def test_unconfigured_returns_empty(self, monkeypatch):
monkeypatch.delenv("OVH_LLM_URL", raising=False)
monkeypatch.delenv("OVH_LLM_MODEL", raising=False)
assert await llm_cascade._call_ovh("sys", "user") == ""
@@ -0,0 +1,153 @@
"""Unit-Tests Obligation Aggregation Engine (Legal Obligation Layer v1).
Deckt die fail-safe Regeln + den Redundanz-Kollaps ab (echte DSE-Szenarien:
recipients 9×, objection LM+BP, portability OPTIONAL-Format)."""
from compliance.services.obligation_aggregation import (
BP, LM, OPT, CriterionEval, aggregate_obligation, aggregate_obligations,
evals_from_tiered, summarize,
)
def _ce(oid, tier, met, cid, basis="", crit="", cond=None):
return CriterionEval(oid, tier, met, cid, basis, crit, cond)
class TestRedundancyCollapse:
def test_nine_controls_one_confirms_collapses_to_one_met(self):
# recipients_disclosed: 9 Controls, gleiche Anforderung (Art 13(1)(e))
evals = [_ce("recipients_disclosed", LM, i == 4, f"DATA-{i}", "Art. 13(1)(e)")
for i in range(9)]
res = aggregate_obligation("recipients_disclosed", evals)
assert res.status == "MET"
assert res.lm_met == 1 and res.lm_total == 1 # 9 → 1 Anforderung
assert len(res.evidence) == 9
def test_all_nine_absent_fails_once(self):
evals = [_ce("recipients_disclosed", LM, False, f"DATA-{i}", "Art. 13(1)(e)")
for i in range(9)]
res = aggregate_obligation("recipients_disclosed", evals)
assert res.status == "FAILED"
assert res.bucket == "PFLICHT"
class TestPartialMultiFacet:
def test_two_distinct_lm_requirements_one_met_is_partial(self):
evals = [
_ce("transfer", LM, True, "C1", "Art. 13(1)(f)"), # erfüllt
_ce("transfer", LM, False, "C2", "Art. 46"), # fehlt → distinkt
]
res = aggregate_obligation("transfer", evals)
assert res.status == "PARTIAL"
assert res.lm_met == 1 and res.lm_total == 2
def test_both_distinct_requirements_met(self):
evals = [
_ce("transfer", LM, True, "C1", "Art. 13(1)(f)"),
_ce("transfer", LM, True, "C2", "Art. 46"),
]
assert aggregate_obligation("transfer", evals).status == "MET"
class TestApplicability:
def test_conditional_false_is_na(self):
evals = [_ce("transfer", LM, False, "C1", "Art. 44", cond="has_third_country_transfer")]
res = aggregate_obligation("transfer", evals, applicable_fn=lambda c, t: False)
assert res.status == "NA"
assert res.bucket == "NICHT_ANWENDBAR"
assert res.applicable is False
def test_conditional_true_evaluates_normally(self):
evals = [_ce("transfer", LM, False, "C1", "Art. 44", cond="has_third_country_transfer")]
res = aggregate_obligation("transfer", evals, applicable_fn=lambda c, t: True)
assert res.status == "FAILED"
def test_conditional_unknown_defaults_applicable(self):
evals = [_ce("transfer", LM, True, "C1", "Art. 44", cond="x")]
res = aggregate_obligation("transfer", evals, applicable_fn=lambda c, t: None)
assert res.applicable is True and res.status == "MET"
def test_no_predicate_means_applicable(self):
evals = [_ce("transfer", LM, True, "C1", cond="x")]
assert aggregate_obligation("transfer", evals).applicable is True
class TestUndetermined:
def test_all_lm_none_is_undetermined(self):
evals = [_ce("ob", LM, None, "C1", "b"), _ce("ob", LM, None, "C2", "b")]
res = aggregate_obligation("ob", evals)
assert res.status == "UNDETERMINED"
assert res.bucket == "PFLICHT"
def test_one_determinable_requirement_decides(self):
# eine Anforderung unbestimmt, die andere klar erfüllt → MET über die bewertbare
evals = [_ce("ob", LM, None, "C1", "b1"), _ce("ob", LM, True, "C2", "b2")]
res = aggregate_obligation("ob", evals)
assert res.status == "MET"
assert res.lm_total == 1 # nur die bewertbare Anforderung zählt
class TestBestPracticeOnly:
def test_pure_bp_covered_is_met_recommendation_bucket(self):
evals = [_ce("art20_format", OPT, True, "C1")]
res = aggregate_obligation("art20_format", evals)
assert res.status == "MET"
assert res.bucket == "EMPFEHLUNG"
def test_pure_bp_not_covered_is_open_never_failed(self):
evals = [_ce("art20_format", OPT, False, "C1", crit="JSON/CSV")]
res = aggregate_obligation("art20_format", evals)
assert res.status == "OPEN"
assert res.bucket == "EMPFEHLUNG"
assert len(res.recommendations) == 1
class TestRecommendationsWithinLm:
def test_unmet_bp_in_lm_obligation_becomes_recommendation(self):
# objection_direct_marketing: LM erfüllt + 3 BP teils offen
evals = [
_ce("obj_dm", LM, True, "SEC-8410", "Art. 21(2)", "Recht"),
_ce("obj_dm", BP, False, "SEC-8410", "", "Kontaktweg"),
_ce("obj_dm", BP, True, "SEC-8410", "", "kostenlos"),
]
res = aggregate_obligation("obj_dm", evals)
assert res.status == "MET" and res.bucket == "PFLICHT"
assert len(res.recommendations) == 1
assert res.recommendations[0]["criterion"] == "Kontaktweg"
class TestAdapterAndSummary:
def test_evals_from_tiered_zips_and_skips_no_obligation(self):
tc = [
{"criterion": "Recht", "compliance_tier": "LEGAL_MINIMUM",
"legal_basis": "Art. 21(1)", "obligation_id": "obj_gen"},
{"criterion": "Weg", "compliance_tier": "BEST_PRACTICE",
"legal_basis": "", "obligation_id": "obj_gen"},
{"criterion": "ohne", "compliance_tier": "OPTIONAL"}, # kein obligation_id → skip
]
detail = [{"met": True}, {"met": False}, {"met": True}]
evals = evals_from_tiered("AUTH-2051", tc, detail, conditional="x")
assert len(evals) == 2
assert evals[0].met is True and evals[0].conditional == "x"
assert evals[1].tier == BP and evals[1].met is False
def test_aggregate_obligations_groups_by_id(self):
evals = [
_ce("a", LM, True, "C1", "b"),
_ce("a", LM, True, "C2", "b"),
_ce("b", LM, False, "C3", "b"),
]
results = {r.obligation_id: r for r in aggregate_obligations(evals)}
assert set(results) == {"a", "b"}
assert results["a"].status == "MET"
assert results["b"].status == "FAILED"
def test_summarize_counts_buckets_and_failures(self):
evals = [
_ce("a", LM, False, "C1", "b"), # FAILED Pflicht
_ce("c", OPT, False, "C3", crit="x"), # OPEN Empfehlung
]
s = summarize(aggregate_obligations(evals))
assert s["obligations"] == 2
assert s["pflicht_failed"] == 1
assert s["buckets"]["PFLICHT"] == 1
assert s["buckets"]["EMPFEHLUNG"] == 1
@@ -0,0 +1,57 @@
"""Unit-Tests für die minimalen Applicability-Prädikate."""
from compliance.services.obligation_applicability import (
applicable, direct_marketing, has_third_country_transfer,
uses_legitimate_interest,
)
class TestThirdCountry:
def test_drittland_present(self):
assert has_third_country_transfer("übermittlung in ein drittland erfolgt") is True
def test_scc_present(self):
assert has_third_country_transfer("auf basis der standardvertragsklauseln") is True
def test_absent(self):
assert has_third_country_transfer("verarbeitung nur innerhalb deutschlands") is False
class TestLegitimateInterest:
def test_present(self):
assert uses_legitimate_interest("auf grundlage unseres berechtigten interesses") is True
def test_absent(self):
assert uses_legitimate_interest("nur auf grundlage ihrer einwilligung") is False
class TestDirectMarketing:
def test_newsletter(self):
assert direct_marketing("anmeldung zum newsletter möglich") is True
def test_direktwerbung(self):
assert direct_marketing("daten für direktwerbung genutzt") is True
def test_absent(self):
assert direct_marketing("wir versenden keine werblichen inhalte ohne basis") is True # 'werbliche' trifft
def test_truly_absent(self):
assert direct_marketing("reine vertragsabwicklung") is False
class TestApplicableHook:
def test_known_predicate_true(self):
assert applicable("has_third_country_transfer", "Transfer in die USA") is True
def test_known_predicate_false_triggers_na(self):
assert applicable("has_third_country_transfer", "nur in der EU") is False
def test_public_task_alias(self):
assert applicable("legitimate_interest_or_public_task",
"zur ausübung öffentlicher gewalt") is True
def test_unknown_predicate_returns_none(self):
# profiling noch nicht modelliert → None → Aufrufer behält anwendbar
assert applicable("profiling", "irgendein text") is None
def test_case_insensitive(self):
assert applicable("uses_legitimate_interest", "BERECHTIGTES INTERESSE") is True
@@ -0,0 +1,92 @@
"""Unit-Tests für die reinen Helfer der Obligation Discovery Pipeline (scripts/obligation_discovery/_core.py)."""
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "scripts" / "obligation_discovery"))
from _core import ( # noqa: E402
centroid, cosine, greedy_cluster, merge_edges, parse_req, validate_registry,
)
class TestParseReq:
def test_list_passthrough(self):
assert parse_req(["a", "b"]) == ["a", "b"]
def test_python_repr_string(self):
assert parse_req("['x', 'y']") == ["x", "y"]
def test_json_string(self):
assert parse_req('["x", "y"]') == ["x", "y"]
def test_plain_string(self):
assert parse_req("just text") == ["just text"]
class TestCosine:
def test_identical(self):
assert cosine([1.0, 2.0, 3.0], [1.0, 2.0, 3.0]) > 0.999
def test_orthogonal(self):
assert abs(cosine([1.0, 0.0], [0.0, 1.0])) < 1e-9
def test_empty(self):
assert cosine([], [1.0]) == 0.0
class TestGreedyCluster:
def test_near_vectors_cluster_far_separate(self):
vecs = [[1.0, 0.0], [0.99, 0.01], [0.0, 1.0]]
clusters = greedy_cluster(vecs, 0.9)
assert len(clusters) == 2
assert clusters[0]["members"] == [0, 1]
assert clusters[1]["members"] == [2]
def test_deterministic(self):
vecs = [[1.0, 0.0], [0.5, 0.5], [0.99, 0.0]]
assert greedy_cluster(vecs, 0.8) == greedy_cluster(vecs, 0.8)
def test_none_vector_isolated(self):
clusters = greedy_cluster([[1.0, 0.0], None], 0.5)
assert clusters[1]["members"] == [1] and clusters[1]["seed"] is None
class TestCentroid:
def test_mean(self):
assert centroid([0, 1], [[0.0, 2.0], [2.0, 4.0]]) == [1.0, 3.0]
class TestValidateRegistry:
def _reg(self, obls, rels=None):
return {"obligations": obls, "relationships": rels or []}
def test_lm_without_legal_basis_fails(self):
r = self._reg([{"id": "x", "tier": "LEGAL_MINIMUM", "legal_basis": [], "member_controls": ["C1"]}])
v = validate_registry(r)
assert v["lm_without_legal_basis"] == ["x"] and v["passed"] is False
def test_clean_passes(self):
r = self._reg([{"id": "x", "tier": "LEGAL_MINIMUM", "legal_basis": [{"source": "CRA"}],
"member_controls": ["C1"], "provenance": {"source_meta_cluster": "M0"}}])
assert validate_registry(r)["passed"] is True
def test_over8_per_review_unit_flagged(self):
obls = [{"id": f"o{i}", "tier": "BEST_PRACTICE", "member_controls": ["C"],
"provenance": {"source_meta_cluster": "M0"}} for i in range(9)]
v = validate_registry(self._reg(obls))
assert v["over8_per_review_unit"] == {"M0": 9} and v["passed"] is False
def test_empty_member_controls_flagged(self):
v = validate_registry(self._reg([{"id": "x", "tier": "BEST_PRACTICE", "member_controls": []}]))
assert v["empty_member_controls"] == ["x"] and v["passed"] is False
class TestMergeEdges:
def test_dedup_and_semantic_only(self):
existing = [{"type": "supports", "from": "a", "to": "b"}]
proposed = [{"type": "supports", "from": "a", "to": "b"}, # dup
{"type": "depends_on", "from": "c", "to": "d"}, # new
{"type": "out_of_scope", "clusters": [1]}] # not semantic
merged, added = merge_edges(existing, proposed)
assert added == 1
assert {"type": "depends_on", "from": "c", "to": "d"} in merged

Some files were not shown because too many files have changed in this diff Show More