Spaces:
Paused

File size: 10,239 Bytes
8eb630b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#!/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 -- <file>")
            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()