#!/usr/bin/env python3 """ Core Immutability Validation Script Enforces Commandment #1: ZERO CORE CHANGES Validates that protected core paths have not been modified without approval. Protected Paths: - /src/core/database/ - Database mixins, connections - /src/core/multitenancy/ - Tenant isolation logic - /src/core/services/base*.py - Base service classes - /src/core/security/ - Authentication, RBAC, audit Usage: # Check current changes python scripts/validation/check_core_immutability.py # Check specific commit range python scripts/validation/check_core_immutability.py --since HEAD~5 # CI mode (exit code 1 on violations) python scripts/validation/check_core_immutability.py --ci Author: Platform Architecture Team Date: January 10, 2026 Version: 1.0 """ import os import sys import argparse import subprocess from pathlib import Path from typing import List, Set, Optional from dataclasses import dataclass @dataclass class Violation: """Represents a core immutability violation""" file_path: str change_type: str # added, modified, deleted protected_category: str severity: str # critical, warning class CoreImmutabilityChecker: """ Validates that protected core paths are not modified without approval. Per Commandment #1: ZERO CORE CHANGES All customization must be via config/tenant settings/workflow packs only. """ # Protected paths that trigger violations PROTECTED_PATHS: dict = { "src/core/database/": "Database Layer", "src/core/multitenancy/": "Multi-Tenancy Layer", "src/core/services/base": "Base Services", "src/core/security/": "Security Layer", "src/core/repositories/base": "Base Repositories", } # Allowed paths within protected areas (config-only changes) ALLOWED_EXCEPTIONS: Set[str] = { "src/core/database/migrations/", "src/core/security/secrets.py", # Env loading only } # Files that require ADMIN approval ADMIN_APPROVAL_REQUIRED: Set[str] = { "src/core/multitenancy/tenant.py", "src/core/security/rbac.py", "src/core/security/audit.py", "src/core/services/base_service.py", } def __init__(self, since: Optional[str] = None, ci_mode: bool = False): self.since = since self.ci_mode = ci_mode self.violations: List[Violation] = [] self.warnings: List[str] = [] self.base_path = Path(__file__).parent.parent.parent def check(self) -> bool: """ Check for core immutability violations. Returns: True if no violations, False otherwise """ print("\nšŸ”’ COMMANDMENT #1: ZERO CORE CHANGES") print("=" * 60) print("Checking for modifications to protected core paths...") print() # Get changed files changed_files = self._get_changed_files() if not changed_files: print("āœ… No uncommitted changes detected.") return True print(f"šŸ“ Found {len(changed_files)} changed files") print() # Check each changed file for file_path, change_type in changed_files: self._check_file(file_path, change_type) # Print results self._print_results() # Return based on violations if self.violations: if self.ci_mode: sys.exit(1) return False return True def _get_changed_files(self) -> List[tuple]: """Get list of changed files from git""" try: # Get staged changes staged_cmd = ["git", "diff", "--cached", "--name-status"] staged_result = subprocess.run( staged_cmd, capture_output=True, text=True, cwd=self.base_path ) # Get unstaged changes unstaged_cmd = ["git", "diff", "--name-status"] unstaged_result = subprocess.run( unstaged_cmd, capture_output=True, text=True, cwd=self.base_path ) # Parse results changed_files = [] for line in (staged_result.stdout + unstaged_result.stdout).strip().split('\n'): if line: parts = line.split('\t') if len(parts) >= 2: change_type = parts[0][0] # A, M, D file_path = parts[-1] # Map change type type_map = {'A': 'added', 'M': 'modified', 'D': 'deleted'} change_type = type_map.get(change_type, 'modified') changed_files.append((file_path, change_type)) # If since is specified, also check commit range if self.since: range_cmd = ["git", "diff", "--name-status", self.since] range_result = subprocess.run( range_cmd, capture_output=True, text=True, cwd=self.base_path ) for line in range_result.stdout.strip().split('\n'): if line: parts = line.split('\t') if len(parts) >= 2: change_type = parts[0][0] file_path = parts[-1] type_map = {'A': 'added', 'M': 'modified', 'D': 'deleted'} change_type = type_map.get(change_type, 'modified') changed_files.append((file_path, change_type)) # Deduplicate return list(set(changed_files)) except Exception as e: print(f"āš ļø Warning: Could not get git changes: {e}") return [] def _check_file(self, file_path: str, change_type: str) -> None: """Check if a file modification violates core immutability""" # Check if in allowed exceptions for exception in self.ALLOWED_EXCEPTIONS: if file_path.startswith(exception): return # Check against protected paths for protected_path, category in self.PROTECTED_PATHS.items(): if file_path.startswith(protected_path): # Determine severity severity = "critical" if file_path in self.ADMIN_APPROVAL_REQUIRED: severity = "critical" self.violations.append(Violation( file_path=file_path, change_type=change_type, protected_category=category, severity=severity )) return # Check for base class modifications if "base" in file_path.lower() and file_path.startswith("src/core/"): self.warnings.append( f"āš ļø Potential base class modification: {file_path}" ) def _print_results(self) -> None: """Print validation results""" print() print("-" * 60) if self.violations: print() print("āŒ CORE IMMUTABILITY VIOLATIONS DETECTED") print() print("The following protected files have been modified:") print() for v in self.violations: severity_icon = "🚨" if v.severity == "critical" else "āš ļø" print(f" {severity_icon} [{v.change_type.upper()}] {v.file_path}") print(f" Category: {v.protected_category}") print() print() print("šŸ“‹ RESOLUTION OPTIONS:") print() print(" 1. REVERT changes to protected files:") print(" git checkout -- ") print() print(" 2. If changes are REQUIRED, get ADMIN approval:") print(" - Document reason in PR description") print(" - Add label 'core-change-approved'") print(" - Architecture review required") print() print(" 3. Use CONFIG-BASED approach instead:") print(" - config/app.yml for app settings") print(" - governance.tenants table for tenant config") print(" - Feature flags for gradual rollouts") print() elif self.warnings: print() print("āš ļø WARNINGS (review recommended):") print() for warning in self.warnings: print(f" {warning}") print() print("āœ… No critical violations found.") else: print() print("āœ… COMMANDMENT #1 PASSED: No core immutability violations") print() print("All changes are in allowed paths:") print(" - apps/*/ → Application modules") print(" - config/ → Configuration files") print(" - tests/ → Test files") print(" - docs/ → Documentation") print(" - scripts/ → Utility scripts") def main(): parser = argparse.ArgumentParser( description="Check for core immutability violations (Commandment #1)" ) parser.add_argument( "--since", help="Git commit reference to check from (e.g., HEAD~5, main)" ) parser.add_argument( "--ci", action="store_true", help="CI mode: exit with code 1 on violations" ) args = parser.parse_args() checker = CoreImmutabilityChecker( since=args.since, ci_mode=args.ci ) success = checker.check() if not success and args.ci: sys.exit(1) if __name__ == "__main__": main()