Files
breakpilot-compliance/backend-compliance/compliance/db/regulation_models.py
Sharang Parnerkar 3320ef94fc refactor: phase 0 guardrails + phase 1 step 2 (models.py split)
Squash of branch refactor/phase0-guardrails-and-models-split — 4 commits,
81 files, 173/173 pytest green, OpenAPI contract preserved (360 paths /
484 operations).

## Phase 0 — Architecture guardrails

Three defense-in-depth layers to keep the architecture rules enforced
regardless of who opens Claude Code in this repo:

  1. .claude/settings.json PreToolUse hook on Write/Edit blocks any file
     that would exceed the 500-line hard cap. Auto-loads in every Claude
     session in this repo.
  2. scripts/githooks/pre-commit (install via scripts/install-hooks.sh)
     enforces the LOC cap locally, freezes migrations/ without
     [migration-approved], and protects guardrail files without
     [guardrail-change].
  3. .gitea/workflows/ci.yaml gains loc-budget + guardrail-integrity +
     sbom-scan (syft+grype) jobs, adds mypy --strict for the new Python
     packages (compliance/{services,repositories,domain,schemas}), and
     tsc --noEmit for admin-compliance + developer-portal.

Per-language conventions documented in AGENTS.python.md, AGENTS.go.md,
AGENTS.typescript.md at the repo root — layering, tooling, and explicit
"what you may NOT do" lists. Root CLAUDE.md is prepended with the six
non-negotiable rules. Each of the 10 services gets a README.md.

scripts/check-loc.sh enforces soft 300 / hard 500 and surfaces the
current baseline of 205 hard + 161 soft violations so Phases 1-4 can
drain it incrementally. CI gates only CHANGED files in PRs so the
legacy baseline does not block unrelated work.

## Deprecation sweep

47 files. Pydantic V1 regex= -> pattern= (2 sites), class Config ->
ConfigDict in source_policy_router.py (schemas.py intentionally skipped;
it is the Phase 1 Step 3 split target). datetime.utcnow() ->
datetime.now(timezone.utc) everywhere including SQLAlchemy default=
callables. All DB columns already declare timezone=True, so this is a
latent-bug fix at the Python side, not a schema change.

DeprecationWarning count dropped from 158 to 35.

## Phase 1 Step 1 — Contract test harness

tests/contracts/test_openapi_baseline.py diffs the live FastAPI /openapi.json
against tests/contracts/openapi.baseline.json on every test run. Fails on
removed paths, removed status codes, or new required request body fields.
Regenerate only via tests/contracts/regenerate_baseline.py after a
consumer-updated contract change. This is the safety harness for all
subsequent refactor commits.

## Phase 1 Step 2 — models.py split (1466 -> 85 LOC shim)

compliance/db/models.py is decomposed into seven sibling aggregate modules
following the existing repo pattern (dsr_models.py, vvt_models.py, ...):

  regulation_models.py       (134) — Regulation, Requirement
  control_models.py          (279) — Control, Mapping, Evidence, Risk
  ai_system_models.py        (141) — AISystem, AuditExport
  service_module_models.py   (176) — ServiceModule, ModuleRegulation, ModuleRisk
  audit_session_models.py    (177) — AuditSession, AuditSignOff
  isms_governance_models.py  (323) — ISMSScope, Context, Policy, Objective, SoA
  isms_audit_models.py       (468) — Finding, CAPA, MgmtReview, InternalAudit,
                                     AuditTrail, Readiness

models.py becomes an 85-line re-export shim in dependency order so
existing imports continue to work unchanged. Schema is byte-identical:
__tablename__, column definitions, relationship strings, back_populates,
cascade directives all preserved.

All new sibling files are under the 500-line hard cap; largest is
isms_audit_models.py at 468. No file in compliance/db/ now exceeds
the hard cap.

## Phase 1 Step 3 — infrastructure only

backend-compliance/compliance/{schemas,domain,repositories}/ packages
are created as landing zones with docstrings. compliance/domain/
exports DomainError / NotFoundError / ConflictError / ValidationError /
PermissionError — the base classes services will use to raise
domain-level errors instead of HTTPException.

PHASE1_RUNBOOK.md at backend-compliance/PHASE1_RUNBOOK.md documents
the nine-step execution plan for Phase 1: snapshot baseline,
characterization tests, split models.py (this commit), split schemas.py
(next), extract services, extract repositories, mypy --strict, coverage.

## Verification

  backend-compliance/.venv-phase1: uv python install 3.12 + pip -r requirements.txt
  PYTHONPATH=. pytest compliance/tests/ tests/contracts/
  -> 173 passed, 0 failed, 35 warnings, OpenAPI 360/484 unchanged

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 13:18:29 +02:00

135 lines
6.3 KiB
Python

"""
Regulation & Requirement models — extracted from compliance/db/models.py.
The foundational compliance aggregate: regulations (GDPR, AI Act, CRA, ...) and
the individual requirements they contain. Re-exported from
``compliance.db.models`` for backwards compatibility.
DO NOT change __tablename__, column names, or relationship strings.
"""
import uuid
import enum
from datetime import datetime, timezone
from sqlalchemy import (
Column, String, Text, Integer, Boolean, DateTime, Date,
ForeignKey, Enum, JSON, Index,
)
from sqlalchemy.orm import relationship
from classroom_engine.database import Base
# ============================================================================
# ENUMS
# ============================================================================
class RegulationTypeEnum(str, enum.Enum):
"""Type of regulation/standard."""
EU_REGULATION = "eu_regulation" # Directly applicable EU law
EU_DIRECTIVE = "eu_directive" # Requires national implementation
DE_LAW = "de_law" # German national law
BSI_STANDARD = "bsi_standard" # BSI technical guidelines
INDUSTRY_STANDARD = "industry_standard" # ISO, OWASP, etc.
# ============================================================================
# MODELS
# ============================================================================
class RegulationDB(Base):
"""
Represents a regulation, directive, or standard.
Examples: GDPR, AI Act, CRA, BSI-TR-03161
"""
__tablename__ = 'compliance_regulations'
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
code = Column(String(20), unique=True, nullable=False, index=True) # e.g., "GDPR", "AIACT"
name = Column(String(200), nullable=False) # Short name
full_name = Column(Text) # Full official name
regulation_type = Column(Enum(RegulationTypeEnum), nullable=False)
source_url = Column(String(500)) # EUR-Lex URL or similar
local_pdf_path = Column(String(500)) # Local PDF if available
effective_date = Column(Date) # When it came into force
description = Column(Text) # Brief description
is_active = Column(Boolean, default=True)
# Timestamps
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
# Relationships
requirements = relationship("RequirementDB", back_populates="regulation", cascade="all, delete-orphan")
def __repr__(self):
return f"<Regulation {self.code}: {self.name}>"
class RequirementDB(Base):
"""
Individual requirement from a regulation.
Examples: GDPR Art. 32(1)(a), AI Act Art. 9, BSI-TR O.Auth_1
"""
__tablename__ = 'compliance_requirements'
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
regulation_id = Column(String(36), ForeignKey('compliance_regulations.id'), nullable=False, index=True)
# Requirement identification
article = Column(String(50), nullable=False) # e.g., "Art. 32", "O.Auth_1"
paragraph = Column(String(20)) # e.g., "(1)(a)"
requirement_id_external = Column(String(50)) # External ID (e.g., BSI ID)
title = Column(String(300), nullable=False) # Requirement title
description = Column(Text) # Brief description
requirement_text = Column(Text) # Original text from regulation
# Breakpilot-specific interpretation and implementation
breakpilot_interpretation = Column(Text) # How Breakpilot interprets this
implementation_status = Column(String(30), default="not_started") # not_started, in_progress, implemented, verified
implementation_details = Column(Text) # How we implemented it
code_references = Column(JSON) # List of {"file": "...", "line": ..., "description": "..."}
documentation_links = Column(JSON) # List of internal doc links
# Evidence for auditors
evidence_description = Column(Text) # What evidence proves compliance
evidence_artifacts = Column(JSON) # List of {"type": "...", "path": "...", "description": "..."}
# Audit-specific fields
auditor_notes = Column(Text) # Notes from auditor review
audit_status = Column(String(30), default="pending") # pending, in_review, approved, rejected
last_audit_date = Column(DateTime)
last_auditor = Column(String(100))
is_applicable = Column(Boolean, default=True) # Applicable to Breakpilot?
applicability_reason = Column(Text) # Why/why not applicable
priority = Column(Integer, default=2) # 1=Critical, 2=High, 3=Medium
# Source document reference
source_page = Column(Integer) # Page number in source document
source_section = Column(String(100)) # Section in source document
# Timestamps
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
# Relationships
regulation = relationship("RegulationDB", back_populates="requirements")
control_mappings = relationship("ControlMappingDB", back_populates="requirement", cascade="all, delete-orphan")
__table_args__ = (
Index('ix_requirement_regulation_article', 'regulation_id', 'article'),
Index('ix_requirement_audit_status', 'audit_status'),
Index('ix_requirement_impl_status', 'implementation_status'),
)
def __repr__(self):
return f"<Requirement {self.article} {self.paragraph or ''}>"
__all__ = ["RegulationTypeEnum", "RegulationDB", "RequirementDB"]