forked from AutoForgeAI/autoforge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquality_gates.py
More file actions
474 lines (389 loc) · 14 KB
/
quality_gates.py
File metadata and controls
474 lines (389 loc) · 14 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
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
"""
Quality Gates Module
====================
Provides quality checking functionality for the Autocoder system.
Runs lint, type-check, and custom scripts before allowing features
to be marked as passing.
Supports:
- ESLint/Biome for JavaScript/TypeScript
- ruff/flake8 for Python
- Custom scripts via .autocoder/quality-checks.sh
"""
import json
import os
import platform
import shutil
import subprocess
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import TypedDict
class QualityCheckResult(TypedDict):
"""Result of a single quality check."""
name: str
passed: bool
output: str
duration_ms: int
class QualityGateResult(TypedDict):
"""Result of all quality checks combined."""
passed: bool
timestamp: str
checks: dict[str, QualityCheckResult]
summary: str
def _run_command(cmd: list[str], cwd: Path, timeout: int = 60) -> tuple[int, str, int]:
"""
Run a command and return (exit_code, output, duration_ms).
Args:
cmd: Command and arguments as a list
cwd: Working directory
timeout: Timeout in seconds
Returns:
(exit_code, combined_output, duration_ms)
"""
start = time.time()
try:
result = subprocess.run(
cmd,
cwd=cwd,
capture_output=True,
text=True,
timeout=timeout,
)
duration_ms = int((time.time() - start) * 1000)
output = result.stdout + result.stderr
return result.returncode, output.strip(), duration_ms
except subprocess.TimeoutExpired:
duration_ms = int((time.time() - start) * 1000)
return 124, f"Command timed out after {timeout}s", duration_ms
except FileNotFoundError:
cmd_name = cmd[0] if cmd else "<empty command>"
return 127, f"Command not found: {cmd_name}", 0
except Exception as e:
return 1, str(e), 0
def _detect_js_linter(project_dir: Path) -> tuple[str, list[str]] | None:
"""
Detect the JavaScript/TypeScript linter to use.
Returns:
(name, command) tuple, or None if no linter detected
"""
# Check for ESLint using shutil.which for Windows shim support
eslint_path = shutil.which("eslint")
if eslint_path:
return ("eslint", [eslint_path, ".", "--max-warnings=0"])
# Check for eslint in node_modules/.bin (fallback for non-global installs)
node_eslint = project_dir / "node_modules/.bin/eslint"
if node_eslint.exists():
return ("eslint", [str(node_eslint), ".", "--max-warnings=0"])
# Check for Biome using shutil.which for Windows shim support
biome_path = shutil.which("biome")
if biome_path:
return ("biome", [biome_path, "lint", "."])
# Check for biome in node_modules/.bin (fallback for non-global installs)
node_biome = project_dir / "node_modules/.bin/biome"
if node_biome.exists():
return ("biome", [str(node_biome), "lint", "."])
# Check for package.json lint script
package_json = project_dir / "package.json"
if package_json.exists():
try:
data = json.loads(package_json.read_text())
scripts = data.get("scripts", {})
if "lint" in scripts:
return ("npm_lint", ["npm", "run", "lint"])
except (json.JSONDecodeError, OSError):
pass
return None
def _detect_python_linter(project_dir: Path) -> tuple[str, list[str]] | None:
"""
Detect the Python linter to use.
Returns:
(name, command) tuple, or None if no linter detected
"""
# Check for ruff using shutil.which
ruff_path = shutil.which("ruff")
if ruff_path:
return ("ruff", [ruff_path, "check", "."])
# Check for flake8 using shutil.which
flake8_path = shutil.which("flake8")
if flake8_path:
return ("flake8", [flake8_path, "."])
# Check in virtual environment for ruff (both Unix and Windows paths)
venv_ruff_paths = [
project_dir / "venv/bin/ruff",
project_dir / "venv/Scripts/ruff.exe"
]
for venv_ruff in venv_ruff_paths:
if venv_ruff.exists():
return ("ruff", [str(venv_ruff), "check", "."])
# Check in virtual environment for flake8 (both Unix and Windows paths)
venv_flake8_paths = [
project_dir / "venv/bin/flake8",
project_dir / "venv/Scripts/flake8.exe"
]
for venv_flake8 in venv_flake8_paths:
if venv_flake8.exists():
return ("flake8", [str(venv_flake8), "."])
return None
def _detect_type_checker(project_dir: Path) -> tuple[str, list[str]] | None:
"""
Detect the type checker to use.
Returns:
(name, command) tuple, or None if no type checker detected
"""
# TypeScript
if (project_dir / "tsconfig.json").exists():
if (project_dir / "node_modules/.bin/tsc").exists():
return ("tsc", ["node_modules/.bin/tsc", "--noEmit"])
if shutil.which("npx"):
# Use --no-install to fail fast if tsc is not locally installed
# rather than prompting/auto-downloading
return ("tsc", ["npx", "--no-install", "tsc", "--noEmit"])
# Python (mypy)
if (project_dir / "pyproject.toml").exists() or (project_dir / "setup.py").exists():
if shutil.which("mypy"):
return ("mypy", ["mypy", "."])
venv_mypy_paths = [
project_dir / "venv/bin/mypy",
project_dir / "venv/Scripts/mypy.exe",
project_dir / "venv/Scripts/mypy",
]
for venv_mypy in venv_mypy_paths:
if venv_mypy.exists():
return ("mypy", [str(venv_mypy), "."])
return None
def run_lint_check(project_dir: Path) -> QualityCheckResult:
"""
Run lint check on the project.
Automatically detects the appropriate linter based on project type.
Args:
project_dir: Path to the project directory
Returns:
QualityCheckResult with lint results
"""
# Try JS/TS linter first
linter = _detect_js_linter(project_dir)
if linter is None:
# Try Python linter
linter = _detect_python_linter(project_dir)
if linter is None:
return {
"name": "lint",
"passed": True,
"output": "No linter detected, skipping lint check",
"duration_ms": 0,
}
name, cmd = linter
exit_code, output, duration_ms = _run_command(cmd, project_dir)
# Truncate output if too long
if len(output) > 5000:
output = output[:5000] + "\n... (truncated)"
return {
"name": f"lint ({name})",
"passed": exit_code == 0,
"output": output if output else "No issues found",
"duration_ms": duration_ms,
}
def run_type_check(project_dir: Path) -> QualityCheckResult:
"""
Run type check on the project.
Automatically detects the appropriate type checker based on project type.
Args:
project_dir: Path to the project directory
Returns:
QualityCheckResult with type check results
"""
checker = _detect_type_checker(project_dir)
if checker is None:
return {
"name": "type_check",
"passed": True,
"output": "No type checker detected, skipping type check",
"duration_ms": 0,
}
name, cmd = checker
exit_code, output, duration_ms = _run_command(cmd, project_dir, timeout=120)
# Truncate output if too long
if len(output) > 5000:
output = output[:5000] + "\n... (truncated)"
return {
"name": f"type_check ({name})",
"passed": exit_code == 0,
"output": output if output else "No type errors found",
"duration_ms": duration_ms,
}
def run_custom_script(
project_dir: Path,
script_path: str | None = None,
explicit_config: bool = False,
) -> QualityCheckResult | None:
"""
Run a custom quality check script.
Args:
project_dir: Path to the project directory
script_path: Path to the script (relative to project), defaults to .autocoder/quality-checks.sh
explicit_config: If True, user explicitly configured this script, so missing = error
Returns:
QualityCheckResult, or None if default script doesn't exist
"""
user_configured = script_path is not None or explicit_config
if script_path is None:
script_path = ".autocoder/quality-checks.sh"
script_full_path = (project_dir / script_path).resolve()
project_dir_resolved = project_dir.resolve()
# Validate script path is inside project directory to prevent path traversal
try:
script_full_path.relative_to(project_dir_resolved)
except ValueError:
return {
"name": "custom_script",
"passed": False,
"output": f"Security error: script path '{script_path}' is outside project directory",
"duration_ms": 0,
}
if not script_full_path.exists():
if user_configured:
# User explicitly configured a script that doesn't exist - return error
return {
"name": "custom_script",
"passed": False,
"output": f"Configured script not found: {script_path}",
"duration_ms": 0,
}
# Default script doesn't exist - that's OK, skip silently
return None
# Make sure it's executable
try:
script_full_path.chmod(0o755)
except OSError:
pass
# Determine the appropriate command and runner based on platform and script extension
script_str = str(script_full_path)
script_ext = script_full_path.suffix.lower()
# Platform detection
is_windows = os.name == "nt" or platform.system() == "Windows"
if is_windows:
# Windows: check script extension and use appropriate runner
if script_ext == ".ps1":
command = ["powershell.exe", "-File", script_str]
elif script_ext in [".bat", ".cmd"]:
command = ["cmd", "/c", script_str]
else:
# For .sh files on Windows, try bash first, then sh
if shutil.which("bash"):
command = ["bash", script_str]
elif shutil.which("sh"):
command = ["sh", script_str]
else:
# Fall back to cmd for unknown extensions
command = ["cmd", "/c", script_str]
else:
# Unix-like: prefer bash, fall back to sh
if shutil.which("bash"):
command = ["bash", script_str]
elif shutil.which("sh"):
command = ["sh", script_str]
else:
# Last resort: try to execute directly
command = [script_str]
exit_code, output, duration_ms = _run_command(
command,
project_dir,
timeout=300, # 5 minutes for custom scripts
)
# Truncate output if too long
if len(output) > 10000:
output = output[:10000] + "\n... (truncated)"
return {
"name": "custom_script",
"passed": exit_code == 0,
"output": output if output else "Script completed successfully",
"duration_ms": duration_ms,
}
def verify_quality(
project_dir: Path,
do_lint: bool = True,
do_type_check: bool = True,
do_custom: bool = True,
custom_script_path: str | None = None,
) -> QualityGateResult:
"""
Run all configured quality checks.
Args:
project_dir: Path to the project directory
do_lint: Whether to run lint check
do_type_check: Whether to run type check
do_custom: Whether to run custom script
custom_script_path: Path to custom script (optional)
Returns:
QualityGateResult with all check results
"""
checks: dict[str, QualityCheckResult] = {}
all_passed = True
if do_lint:
lint_result = run_lint_check(project_dir)
checks["lint"] = lint_result
if not lint_result["passed"]:
all_passed = False
if do_type_check:
type_result = run_type_check(project_dir)
checks["type_check"] = type_result
if not type_result["passed"]:
all_passed = False
if do_custom:
custom_result = run_custom_script(
project_dir,
custom_script_path,
explicit_config=custom_script_path is not None,
)
if custom_result is not None:
checks["custom_script"] = custom_result
if not custom_result["passed"]:
all_passed = False
# Build summary
passed_count = sum(1 for c in checks.values() if c["passed"])
total_count = len(checks)
failed_names = [name for name, c in checks.items() if not c["passed"]]
if all_passed:
summary = f"All {total_count} quality checks passed"
else:
summary = f"{passed_count}/{total_count} checks passed. Failed: {', '.join(failed_names)}"
return {
"passed": all_passed,
"timestamp": datetime.now(timezone.utc).isoformat(),
"checks": checks,
"summary": summary,
}
def load_quality_config(project_dir: Path) -> dict:
"""
Load quality gates configuration from .autocoder/config.json.
Args:
project_dir: Path to the project directory
Returns:
Quality gates config dict with defaults applied
"""
defaults = {
"enabled": True,
"strict_mode": True,
"checks": {
"lint": True,
"type_check": True,
"unit_tests": False,
"custom_script": None,
},
}
config_path = project_dir / ".autocoder" / "config.json"
if not config_path.exists():
return defaults
try:
data = json.loads(config_path.read_text())
quality_config = data.get("quality_gates", {})
# Merge with defaults
result = defaults.copy()
for key in ["enabled", "strict_mode"]:
if key in quality_config:
result[key] = quality_config[key]
if "checks" in quality_config:
result["checks"] = {**defaults["checks"], **quality_config["checks"]}
return result
except (json.JSONDecodeError, OSError):
return defaults