File size: 3,368 Bytes
d2a5f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Artifact Validation Gateway — Vitalis FSI

Intercepts and validates the structural integrity of ArchitectureArtifacts
prior to ledger insertion. Prevents schema drift and ensures downstream CI compatibility.
"""

from typing import Any, Dict, List
from src.cognition._constants import logger
from src.cognition.artifact import ArchitectureArtifact

class ArtifactValidator:
    """Enforces absolute adherence to the ArchitectureArtifact schema."""
    
    @staticmethod
    def validate_artifact(artifact: Any) -> bool:
        if not isinstance(artifact, dict):
            logger.error("Validation Failed: Artifact is not a dictionary.")
            return False
            
        required_keys = {
            "components": list,
            "boundaries": list,
            "data_flows": list,
            "patterns": list,
            "risks": list,
            "rationale": str,
            "constraints": list
        }
        
        for key, expected_type in required_keys.items():
            if key not in artifact:
                logger.error("Validation Failed: Missing critical key '%s'.", key)
                return False
            if not isinstance(artifact[key], expected_type):
                logger.error("Validation Failed: Key '%s' expected %s, got %s.", 
                             key, expected_type.__name__, type(artifact[key]).__name__)
                return False
                
        # Deep validation of risk schema
        for risk in artifact.get("risks", []):
            if not ArtifactValidator._validate_risk(risk):
                return False
                
        logger.debug("Artifact structure verified successfully.")
        return True

    @staticmethod
    def _validate_risk(risk: Dict[str, Any]) -> bool:
        required_risk_keys = {"id": str, "description": str, "severity": str, "mitigation": str}
        for key, expected_type in required_risk_keys.items():
            if key not in risk or not isinstance(risk[key], expected_type):
                logger.error("Validation Failed: Malformed risk object on key '%s'.", key)
                return False
        
        if risk["severity"] not in ["LOW", "MEDIUM", "HIGH", "CRITICAL"]:
            logger.error("Validation Failed: Invalid risk severity level '%s'.", risk["severity"])
            return False
            
        return True

    def validate(self, artifact):
        """
        Validate a generated code artifact.
        Returns (bool, str) — (passed, reason)
        """
        if artifact is None:
            return False, "Null artifact"
        code = getattr(artifact, "code", str(artifact))
        if not code or not code.strip():
            return False, "Empty code body"
        # Basic syntax check
        try:
            compile(code, "<artifact>", "exec")
            return True, "Syntax OK"
        except SyntaxError as e:
            return False, f"SyntaxError: {e}"
    def validate(self, artifact):
        if artifact is None:
            return False, "Null artifact"
        code = getattr(artifact, "code", str(artifact))
        if not code or not code.strip():
            return False, "Empty code body"
        try:
            compile(code, "<artifact>", "exec")
            return True, "Syntax OK"
        except SyntaxError as e:
            return False, f"SyntaxError: {e}"