-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvalidator.py
More file actions
254 lines (207 loc) · 7.89 KB
/
validator.py
File metadata and controls
254 lines (207 loc) · 7.89 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
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
"""Validation gates between pipeline stages.
Each validator returns a list of error strings. Empty list = valid.
"""
import logging
from pathlib import Path
from typing import List
from agent.schemas.core import Component
logger = logging.getLogger(__name__)
class ValidationError(Exception):
"""Raised when validation fails with fatal errors."""
def __init__(self, errors: List[str]):
self.errors = errors
super().__init__(f"{len(errors)} validation error(s): {errors[0]}")
def validate_discovery(
components: List[Component],
repo_root: Path,
) -> List[str]:
"""Validate discovery output before graph building.
Checks:
- No duplicate component names
- All root_paths exist in the repo
- All internal dependency references resolve to known components
- No self-dependencies
"""
errors: List[str] = []
names: dict[str, int] = {}
for comp in components:
# Duplicate names
if comp.name in names:
errors.append(
f"Duplicate component name '{comp.name}' "
f"(roots: {components[names[comp.name]].root_path}, {comp.root_path})"
)
names[comp.name] = len(names)
# Root path exists
root = repo_root / comp.root_path if comp.root_path else repo_root
if not root.exists():
errors.append(
f"Component '{comp.name}' root_path does not exist: {comp.root_path}"
)
# Self-dependency
if comp.name in comp.internal_dependencies:
errors.append(f"Component '{comp.name}' depends on itself")
# Internal deps resolve
name_set = {c.name for c in components}
for comp in components:
for dep in comp.internal_dependencies:
if dep not in name_set:
errors.append(
f"Component '{comp.name}' has unresolved internal dependency: '{dep}'"
)
return errors
def validate_graph(
components: List[Component],
depth_order: List[List[str]],
) -> List[str]:
"""Validate dependency graph after building.
Checks:
- Every component appears in exactly one depth level
- Topological ordering is valid (no dep on a later depth)
- No cycles detected (would have failed topological sort)
"""
errors: List[str] = []
name_set = {c.name for c in components}
# Every component should appear in exactly one depth level
all_ordered = set()
for level in depth_order:
for name in level:
if name in all_ordered:
errors.append(f"Component '{name}' appears in multiple depth levels")
all_ordered.add(name)
missing = name_set - all_ordered
if missing:
errors.append(f"Components missing from depth order: {missing}")
# Validate topological property: for each component at depth N,
# all its dependencies should be at depth < N
depth_map: dict[str, int] = {}
for depth, level in enumerate(depth_order):
for name in level:
depth_map[name] = depth
dep_map = {c.name: c.internal_dependencies for c in components}
for name, depth in depth_map.items():
for dep in dep_map.get(name, []):
if dep in depth_map and depth_map[dep] >= depth:
errors.append(
f"Topological violation: '{name}' (depth {depth}) "
f"depends on '{dep}' (depth {depth_map[dep]})"
)
return errors
def validate_analysis(
components: List[Component],
analyses_dir: Path,
repo_root: Path,
) -> List[str]:
"""Validate post-analysis output.
Citations now live in sidecar ``{component}.citations.json`` files
produced by the citation extractor (the ``## Citations`` block is
stripped from the Markdown after extraction to avoid duplication).
Checks:
- Every component has a corresponding analysis .md file
- Every component has a corresponding .citations.json file with a
non-empty citations array
- Cited files exist in the repository (spot check)
- Cited line ranges are plausible (start <= end, within file length)
"""
errors: List[str] = []
for comp in components:
# Check for analysis file
analysis_file = analyses_dir / f"{comp.name}.md"
if not analysis_file.exists():
errors.append(f"Missing analysis file for component '{comp.name}'")
continue
# Spot-check citations from the sidecar JSON
citations_file = analyses_dir / f"{comp.name}.citations.json"
citation_errors = _validate_citations_sidecar(
citations_file, comp.name, repo_root
)
errors.extend(citation_errors)
return errors
def _validate_citations_sidecar(
sidecar_path: Path,
component_name: str,
repo_root: Path,
max_spot_checks: int = 5,
) -> List[str]:
"""Validate citations from the ``{component}.citations.json`` sidecar.
Performs lightweight checks:
- Sidecar file exists
- JSON is parseable
- Contains a non-empty ``citations`` array
- Spot-checks up to max_spot_checks citations for file existence and
line plausibility.
"""
import json
import re
errors: List[str] = []
if not sidecar_path.exists():
errors.append(
f"[{component_name}] Missing sidecar file: {sidecar_path.name}"
)
return errors
try:
payload = json.loads(sidecar_path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
errors.append(
f"[{component_name}] Invalid JSON in {sidecar_path.name}: {exc}"
)
return errors
if not isinstance(payload, dict):
errors.append(
f"[{component_name}] {sidecar_path.name} must be a JSON object, "
f"got {type(payload).__name__}"
)
return errors
data = payload.get("citations", [])
if not isinstance(data, list):
errors.append(
f"[{component_name}] 'citations' must be a JSON array, "
f"got {type(data).__name__}"
)
return errors
if len(data) == 0:
errors.append(
f"[{component_name}] citations array is empty (expected 10+)"
)
return errors
# Spot-check a sample of citations
import random
sample = (
data[:max_spot_checks]
if len(data) <= max_spot_checks
else random.sample(data, max_spot_checks)
)
for i, cite in enumerate(sample):
file_path = cite.get("file_path", "")
start_line = cite.get("start_line", 0)
end_line = cite.get("end_line", 0)
if not file_path:
errors.append(f"[{component_name}] Citation [{i}] missing file_path")
continue
# Strip /tmp/*/project/ prefix if present
cleaned = re.sub(r"^/tmp/[^/]+/project/", "", file_path)
full_path = repo_root / cleaned
if not full_path.exists():
errors.append(f"[{component_name}] Citation file not found: {cleaned}")
continue
# Check line plausibility
if isinstance(start_line, int) and isinstance(end_line, int):
if start_line < 1 or end_line < start_line:
errors.append(
f"[{component_name}] Invalid line range {start_line}-{end_line} "
f"in {cleaned}"
)
else:
# Check against actual file length
try:
line_count = sum(
1 for _ in open(full_path, encoding="utf-8", errors="replace")
)
if start_line > line_count:
errors.append(
f"[{component_name}] Citation start_line {start_line} > "
f"file length {line_count} in {cleaned}"
)
except OSError:
pass # Skip if we can't read the file
return errors