-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator.py
More file actions
214 lines (185 loc) · 7.81 KB
/
Copy pathvalidator.py
File metadata and controls
214 lines (185 loc) · 7.81 KB
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
"""
AXIOM — core/validator.py
Schema contract layer. Sits between every agent handoff.
No record passes between agents without validation.
Agent 4 output gets split here — two separate models, two separate paths.
"""
import json
import os
import sys
from typing import Any, Dict, Optional, Tuple, Union
from pydantic import ValidationError
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from config import AGENT_IDS
from core.models import (
TechniqueRecord, EvidenceRecord, ReviewRecord, ErrorRecord,
PlanRecord, FeedbackEvent, ChainAgentOutput, ChainRecord,
SchemaValidationError, ScoringInput,
)
from core.db import log_error
# ─────────────────────────────────────────────
# INTERNAL: build and persist a schema error
# ─────────────────────────────────────────────
def _reject(
source_agent: str,
payload: Dict[str, Any],
validation_error: ValidationError,
) -> SchemaValidationError:
missing = []
invalid = []
for err in validation_error.errors():
loc = " → ".join(str(l) for l in err["loc"])
msg = f"{loc}: {err['msg']}"
if err["type"] in ("value_error.missing", "type_error.none.not_allowed"):
missing.append(msg)
else:
invalid.append(msg)
error_record = SchemaValidationError(
source_agent=source_agent,
missing_fields=missing,
invalid_values=invalid,
rejected_record=payload,
)
# Persist to error queue — never silently dropped
db_error = ErrorRecord(
source_agent=source_agent,
error_type="SCHEMA_VALIDATION_FAILED",
reason="; ".join(missing + invalid),
payload=payload,
status="pending",
)
try:
log_error(db_error)
except Exception as e:
# If DB is unavailable, write to stderr — never suppress
print(f"[AXIOM][VALIDATOR] Failed to persist error: {e}", file=sys.stderr)
return error_record
# ─────────────────────────────────────────────
# PUBLIC: validate_* functions
# Each returns (model_instance | None, error | None)
# ─────────────────────────────────────────────
def validate_technique(
payload: Dict[str, Any],
source_agent: str = AGENT_IDS["score"],
) -> Tuple[Optional[TechniqueRecord], Optional[SchemaValidationError]]:
try:
return TechniqueRecord(**payload), None
except ValidationError as e:
return None, _reject(source_agent, payload, e)
def validate_scoring_input(
payload: Dict[str, Any],
source_agent: str = AGENT_IDS["ingest"],
) -> Tuple[Optional[ScoringInput], Optional[SchemaValidationError]]:
try:
return ScoringInput(**payload), None
except ValidationError as e:
return None, _reject(source_agent, payload, e)
def validate_evidence(
payload: Dict[str, Any],
source_agent: str = AGENT_IDS["feedback"],
) -> Tuple[Optional[EvidenceRecord], Optional[SchemaValidationError]]:
try:
return EvidenceRecord(**payload), None
except ValidationError as e:
return None, _reject(source_agent, payload, e)
def validate_review(
payload: Dict[str, Any],
source_agent: str = AGENT_IDS["score"],
) -> Tuple[Optional[ReviewRecord], Optional[SchemaValidationError]]:
try:
return ReviewRecord(**payload), None
except ValidationError as e:
return None, _reject(source_agent, payload, e)
def validate_plan(
payload: Dict[str, Any],
source_agent: str = AGENT_IDS["plan"],
) -> Tuple[Optional[PlanRecord], Optional[SchemaValidationError]]:
try:
return PlanRecord(**payload), None
except ValidationError as e:
return None, _reject(source_agent, payload, e)
def validate_feedback_event(
payload: Dict[str, Any],
source_agent: str = AGENT_IDS["feedback"],
) -> Tuple[Optional[FeedbackEvent], Optional[SchemaValidationError]]:
try:
return FeedbackEvent(**payload), None
except ValidationError as e:
return None, _reject(source_agent, payload, e)
# ─────────────────────────────────────────────
# AGENT 4 — PARSER-ENFORCED SPLIT
# This is a security boundary, not a formatting preference.
# Two models. Two paths. No bleed.
# ─────────────────────────────────────────────
class ChainOutputSplit:
"""
Result of parsing Agent 4 output.
validated_chain → routed to DB (trusted)
proposals → routed to Agent 1 ingestion queue (untrusted)
error → routed to error queue
"""
def __init__(
self,
validated_chain: Optional[ChainRecord],
proposals: list,
error: Optional[SchemaValidationError],
):
self.validated_chain = validated_chain
self.proposals = proposals
self.error = error
@property
def is_valid(self) -> bool:
return self.validated_chain is not None and self.error is None
def validate_chain_output(
payload: Dict[str, Any],
source_agent: str = AGENT_IDS["chain"],
) -> ChainOutputSplit:
"""
Parse and validate Agent 4 output.
Enforces structural split between trusted chain and proposal funnel.
Input must contain:
- "validated_chain": ChainRecord
- "proposals": list of ChainProposal (may be empty)
These are validated independently.
Proposals are NEVER routed to trusted chain output.
"""
try:
output = ChainAgentOutput(**payload)
except ValidationError as e:
err = _reject(source_agent, payload, e)
return ChainOutputSplit(validated_chain=None, proposals=[], error=err)
# validated_chain is trusted — already validated by ChainAgentOutput
# proposals are untrusted — validated structurally but routed separately
return ChainOutputSplit(
validated_chain=output.validated_chain,
proposals=output.proposals,
error=None,
)
# ─────────────────────────────────────────────
# OPTIONAL: auto-fix layer (safe casts only)
# Allowed: type casting, enum correction if exact match
# NOT allowed: guessing fields, inventing values
# ─────────────────────────────────────────────
def try_normalize(payload: Dict[str, Any]) -> Dict[str, Any]:
"""
Attempt safe, deterministic normalization of a payload before validation.
Only corrects what can be fixed without inventing values.
"""
normalized = dict(payload)
# Float fields: cast string → float if clean
float_fields = ["confidence", "detection_risk", "planner_score",
"execution_evidence", "source_quality", "source_consensus",
"environment_match", "recency", "stability",
"state_change_risk"]
for field in float_fields:
if field in normalized and isinstance(normalized[field], str):
try:
normalized[field] = float(normalized[field])
except ValueError:
pass # Leave as-is; validation will reject it
# Enum fields: strip whitespace and lowercase for status-like fields
enum_fields = ["status", "event_type", "plan_mode", "step_type"]
for field in enum_fields:
if field in normalized and isinstance(normalized[field], str):
normalized[field] = normalized[field].strip().lower().replace(" ", "_")
return normalized