import hashlib import os import subprocess import sys from contextvars import ContextVar from dataclasses import dataclass, field from pathlib import Path from time import perf_counter from afk_developer.config import LintMode from afk_developer.planner.task_model import ReviewCommandEvidence from afk_developer.scheduler.lint_baseline import ( LintBaseline, LintBaselineError, format_diagnostic_summary, introduced_diagnostics, run_ruff_json, validate_ruff_baseline, ) # Callers thread config.max_shell_timeout in; this only covers direct/legacy calls. DEFAULT_TEST_TIMEOUT_SECONDS = 300 @dataclass class ReviewResult: passed: bool tests_passed: bool lint_passed: bool files_exist: bool = True diff_passed: bool = True files_missing: list[str] = None format_applied: bool = False format_output: str = "" test_output: str = "" lint_output: str = "" diff_output: str = "" summary: str = "" lint_mode: str = LintMode.STRICT.value local_lint_passed: bool = True baseline_diagnostic_count: int = 0 introduced_diagnostic_count: int = 0 baseline_loaded: bool = False formatting_files: list[str] = None scope_passed: bool = True artifact_contract_passed: bool = True required_artifacts_passed: bool = True changed_file_count: int = 0 changed_line_count: int = 0 ownership_passed: bool = True unreported_untracked_files: list[str] = None contract_passed: bool = True command_evidence: list[ReviewCommandEvidence] = field(default_factory=list) @dataclass class LintCheckResult: passed: bool output: str mode: LintMode local_passed: bool = True baseline_diagnostic_count: int = 0 introduced_diagnostic_count: int = 0 baseline_loaded: bool = False @dataclass class _CommandEvidenceRecorder: diagnostic_dir: Path records: list[ReviewCommandEvidence] = field(default_factory=list) _COMMAND_EVIDENCE: ContextVar[_CommandEvidenceRecorder | None] = ContextVar( "review_command_evidence", default=None ) def review_task( project_dir: Path | str, linter: str, test_framework: str, files_changed: list[str] | None = None, apply_format: bool = True, lint_mode: LintMode | str = LintMode.STRICT, lint_baseline: LintBaseline | None = None, max_changed_files: int = 0, max_changed_lines: int = 0, require_raw_contract_artifacts: bool = False, required_artifacts: list[str] | None = None, excluded_test_files: list[str] | None = None, reported_files: list[str] | None = None, python_executable: str | Path | None = None, diagnostic_dir: Path | str | None = None, disallow_unscoped_pytest: bool = False, test_timeout: int = DEFAULT_TEST_TIMEOUT_SECONDS, ) -> ReviewResult: recorder = _CommandEvidenceRecorder(Path(diagnostic_dir).resolve()) if diagnostic_dir else None token = _COMMAND_EVIDENCE.set(recorder) try: result = _review_task( project_dir, linter, test_framework, files_changed, apply_format, lint_mode, lint_baseline, max_changed_files, max_changed_lines, require_raw_contract_artifacts, required_artifacts, excluded_test_files, reported_files, python_executable, disallow_unscoped_pytest, test_timeout, ) finally: _COMMAND_EVIDENCE.reset(token) if recorder is not None: result.command_evidence = recorder.records return result def _review_task( project_dir: Path | str, linter: str, test_framework: str, files_changed: list[str] | None = None, apply_format: bool = True, lint_mode: LintMode | str = LintMode.STRICT, lint_baseline: LintBaseline | None = None, max_changed_files: int = 0, max_changed_lines: int = 0, require_raw_contract_artifacts: bool = False, required_artifacts: list[str] | None = None, excluded_test_files: list[str] | None = None, reported_files: list[str] | None = None, python_executable: str | Path | None = None, disallow_unscoped_pytest: bool = False, test_timeout: int = DEFAULT_TEST_TIMEOUT_SECONDS, ) -> ReviewResult: project_dir = Path(project_dir) mode = LintMode(lint_mode) format_applied = False format_output = "" tests_passed = True test_output = "" lint_passed = True lint_output = "" files_exist = True files_missing: list[str] = [] diff_passed = True diff_output = "" unreported_untracked_files = _unreported_untracked_files( project_dir, reported_files ) ownership_passed = not unreported_untracked_files owned_files = _normalize_owned_files(project_dir, files_changed or []) task_files = [path for path in owned_files if path.suffix == ".py"] owned_test_files = sorted( path.as_posix() for path in owned_files if path.suffix == ".py" and path.name.startswith("test_") and path.parts and path.parts[0] == "tests" ) has_scoped_python_files = files_changed is None or bool(task_files) changed_file_count, changed_line_count = _worktree_change_scope(project_dir) scope_passed = (not max_changed_files or changed_file_count <= max_changed_files) and ( not max_changed_lines or changed_line_count <= max_changed_lines ) artifact_contract_passed = not require_raw_contract_artifacts or ( any(path.as_posix().startswith("tests/fixtures/") for path in owned_files) and any( path.as_posix().startswith("tests/test_") and path.suffix == ".py" for path in owned_files ) ) required_artifact_failures = validate_required_artifacts(project_dir, required_artifacts or []) if required_artifact_failures: files_exist = False files_missing.extend(required_artifact_failures) if files_changed is not None: if not files_changed: files_exist = False files_missing = ["(no files were created or modified)"] else: files_missing.extend(_outside_project_files(project_dir, files_changed)) for fp in owned_files: if not (project_dir / fp).exists(): files_missing.append(fp.as_posix()) if files_missing: files_exist = False if linter and apply_format and has_scoped_python_files: format_applied, format_output = _auto_format( project_dir, linter, task_files, **_python_override_kwargs(python_executable), ) if linter and has_scoped_python_files: lint = _run_linter( project_dir, linter, task_files, mode, lint_baseline, **_python_override_kwargs(python_executable), ) lint_passed = lint.passed lint_output = lint.output else: lint_output = ( "Scoped lint skipped: task owns no Python files." if linter and files_changed is not None else "" ) lint = LintCheckResult(True, lint_output, mode) if test_framework: if excluded_test_files: tests_passed, test_output = _run_tests( project_dir, test_framework, excluded_test_files=excluded_test_files, timeout=test_timeout, **_python_override_kwargs(python_executable), ) elif disallow_unscoped_pytest and test_framework.lower() == "pytest": if owned_test_files: tests_passed, test_output = _run_tests( project_dir, test_framework, test_files=owned_test_files, timeout=test_timeout, **_python_override_kwargs(python_executable), ) else: test_output = "Scoped pytest skipped: task owns no test files." else: tests_passed, test_output = _run_tests( project_dir, test_framework, timeout=test_timeout, **_python_override_kwargs(python_executable), ) diff_passed, diff_output = _run_diff_check(project_dir) passed = ( tests_passed and lint_passed and files_exist and diff_passed and scope_passed and artifact_contract_passed and ownership_passed ) if passed: summary = "Review passed: all tests and lint checks passed." if format_applied: summary += " Files auto-formatted." else: parts = [] if not tests_passed: parts.append("Tests FAILED.") if not lint_passed: parts.append(f"Lint FAILED ({mode.value}).") if not files_exist: parts.append(f"Files missing: {', '.join(files_missing)}.") if not diff_passed: parts.append("Git diff check FAILED.") if not scope_passed: parts.append( f"Mutation scope exceeded: {changed_file_count} files/{changed_line_count} lines." ) if not artifact_contract_passed: parts.append( "Corpus raw-output mutation requires both a fixture and focused test artifact." ) if not ownership_passed: parts.append( "Unreported untracked files: " f"{', '.join(unreported_untracked_files)}." ) if required_artifact_failures: parts.append( "Required artifacts missing or empty: " f"{', '.join(required_artifact_failures)}." ) summary = " ".join(parts) return ReviewResult( passed=passed, tests_passed=tests_passed, lint_passed=lint_passed, files_exist=files_exist, diff_passed=diff_passed, files_missing=files_missing, format_applied=format_applied, format_output=_bounded_output(format_output), test_output=_bounded_output(test_output), lint_output=_bounded_output(lint_output), diff_output=_bounded_output(diff_output), summary=summary, lint_mode=mode.value, local_lint_passed=lint.local_passed, baseline_diagnostic_count=lint.baseline_diagnostic_count, introduced_diagnostic_count=lint.introduced_diagnostic_count, baseline_loaded=lint.baseline_loaded, formatting_files=[path.as_posix() for path in task_files] if format_applied else [], scope_passed=scope_passed, artifact_contract_passed=artifact_contract_passed, required_artifacts_passed=not required_artifact_failures, changed_file_count=changed_file_count, changed_line_count=changed_line_count, ownership_passed=ownership_passed, unreported_untracked_files=unreported_untracked_files, ) def validate_required_artifacts(project_dir: Path | str, required_artifacts: list[str]) -> list[str]: """Return exact contract paths that are absent, non-files, or empty.""" root = Path(project_dir).resolve() failures: list[str] = [] for raw_path in required_artifacts: candidate = (root / raw_path).resolve() try: candidate.relative_to(root) except ValueError: failures.append(raw_path) continue if not candidate.is_file() or candidate.stat().st_size == 0: failures.append(raw_path) return failures def verify_red_regression_tests( project_dir: Path | str, test_framework: str, test_files: list[str] ) -> tuple[bool, str]: """Verify exact pytest regressions are red before their paired repair runs.""" if not test_files: return True, "No red-regression tests declared." if test_framework.lower() != "pytest": return False, "Red-regression tasks currently require pytest." root = Path(project_dir) for test_file in test_files: if not (root / test_file).is_file(): return False, f"Declared red-regression test is missing: {test_file}." try: result = _run_text_command( f'"{sys.executable}" -m pytest "{test_file}" -q --tb=short 2>&1', root, 300 ) except subprocess.TimeoutExpired: return False, f"Red-regression test timed out: {test_file}." output = _command_output(result) if result.returncode == 0: return ( False, ( f"Red-regression test passed unexpectedly: {test_file}.\n\n" f"Focused pytest output:\n{output[-2000:]}" ), ) normalized_output = output.lower() import_collection_error = ( result.returncode == 2 and "error collecting" in normalized_output and ( "modulenotfounderror" in normalized_output or "importerror while importing test module" in normalized_output ) ) if result.returncode != 1 and not import_collection_error: return ( False, ( f"Red-regression test did not produce a test failure: {test_file}.\n\n" f"Focused pytest output:\n{output[-2000:]}" ), ) return True, "Declared red-regression tests fail as expected before repair." def _worktree_change_scope(project_dir: Path) -> tuple[int, int]: """Return changed-file and added/removed-line totals without trusting agent output.""" try: result = _run_text_command("git diff --numstat HEAD", project_dir, 30) paths: set[str] = set() lines = 0 for row in (result.stdout or "").splitlines(): added, removed, path = row.split("\t", 2) paths.add(path) if added.isdigit(): lines += int(added) if removed.isdigit(): lines += int(removed) untracked = _run_text_command("git ls-files --others --exclude-standard", project_dir, 30) for raw_path in (untracked.stdout or "").splitlines(): candidate = project_dir / raw_path if candidate.is_file(): paths.add(raw_path) try: lines += len(candidate.read_text(encoding="utf-8").splitlines()) except UnicodeDecodeError: lines += 1 return len(paths), lines except (ValueError, OSError): return 0, 0 def _unreported_untracked_files( project_dir: Path, reported_files: list[str] | None ) -> list[str]: """Return untracked files the worker did not claim in its completion result. ``None`` means no worker declaration is available (for direct reviewer use and read-only baselines), whereas an empty list is an explicit claim that the worker created nothing. This distinguishes normal review callers from a mutating worker that leaves diagnostic probes behind. """ if reported_files is None: return [] try: result = _run_text_command("git ls-files --others --exclude-standard", project_dir, 30) except (subprocess.TimeoutExpired, OSError): return [] reported = {path.as_posix() for path in _normalize_owned_files(project_dir, reported_files)} return sorted( raw_path for raw_path in (result.stdout or "").splitlines() if raw_path and raw_path not in reported ) def _run_text_command( command: str, project_dir: Path, timeout: int ) -> subprocess.CompletedProcess[str]: environment = os.environ.copy() environment["PYTHONDONTWRITEBYTECODE"] = "1" started_at = perf_counter() result = subprocess.run( command, shell=True, cwd=str(project_dir), env=environment, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, ) _capture_command_evidence(command, result, elapsed_seconds=perf_counter() - started_at) return result def _capture_command_evidence( command: str, result: subprocess.CompletedProcess[str], *, elapsed_seconds: float, ) -> None: recorder = _COMMAND_EVIDENCE.get() if recorder is None: return output = _combined_output(result) output_index = len(recorder.records) + 1 output_path = recorder.diagnostic_dir / f"command-{output_index:03d}.log" while output_path.exists(): output_index += 1 output_path = recorder.diagnostic_dir / f"command-{output_index:03d}.log" try: output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text(output, encoding="utf-8", newline="") artifact_path = str(output_path) except OSError: artifact_path = "" recorder.records.append( ReviewCommandEvidence( command=command, exit_code=result.returncode, elapsed_seconds=elapsed_seconds, output_sha256=hashlib.sha256(output.encode("utf-8")).hexdigest(), output_character_count=len(output), output_truncated=len(output) > 4_000, output_head=output[:2000], output_tail=output[-2000:] if len(output) > 2000 else "", output_artifact_path=artifact_path, ) ) def _auto_format( project_dir: Path, linter: str, task_files: list[Path] | None = None, *, python_executable: str | Path | None = None, ) -> tuple[bool, str]: if not task_files: return False, "" cmd = _format_command(linter, task_files, python_executable=python_executable) if not cmd: return False, "" try: result = _run_text_command(cmd, project_dir, 60) output = (result.stdout or "").strip() or (result.stderr or "").strip() or "" return result.returncode == 0, output except subprocess.TimeoutExpired: return False, "Format timed out" except Exception as e: return False, f"Format error: {e}" def _run_linter( project_dir: Path, linter: str, task_files: list[Path] | None = None, lint_mode: LintMode = LintMode.STRICT, lint_baseline: LintBaseline | None = None, *, python_executable: str | Path | None = None, ) -> LintCheckResult: if linter.lower() == "ruff": return _run_ruff_linter( project_dir, task_files or [], lint_mode, lint_baseline, python_executable=python_executable, ) if lint_mode is LintMode.BASELINE: return LintCheckResult( False, f"Baseline lint mode is not supported for {linter}. Use strict mode.", lint_mode, local_passed=False, ) commands: dict[str, str] = { "flake8": "flake8 .", "eslint": "npx eslint . --ext .js,.ts,.tsx,.jsx", "pylint": "pylint $(git ls-files '*.py')", } cmd = commands.get(linter.lower(), "") if not cmd: return LintCheckResult( False, f"No linter command configured for: {linter}", lint_mode, local_passed=False, ) try: result = _run_text_command(cmd, project_dir, 120) output = (result.stdout or "").strip() or (result.stderr or "").strip() or "(no output)" return LintCheckResult(result.returncode == 0, output, lint_mode) except subprocess.TimeoutExpired: return LintCheckResult(False, f"Linter {linter} timed out", lint_mode, local_passed=False) except Exception as e: return LintCheckResult( False, f"Linter {linter} error: {e}", lint_mode, local_passed=False, ) def _run_ruff_linter( project_dir: Path, task_files: list[Path], lint_mode: LintMode, lint_baseline: LintBaseline | None, *, python_executable: str | Path | None = None, ) -> LintCheckResult: python = str(python_executable or sys.executable) if task_files: local_result = _run_text_command(_ruff_command(task_files, python_executable=python), project_dir, 120) local_output = _command_output(local_result) local_passed = local_result.returncode == 0 else: local_output = "No task-owned Python files to lint." local_passed = True if lint_mode is LintMode.STRICT: global_result = _run_text_command(_ruff_command(python_executable=python), project_dir, 120) global_output = _command_output(global_result) return LintCheckResult( local_passed and global_result.returncode == 0, _combine_lint_output(local_output, global_output, local_passed), lint_mode, local_passed=local_passed, ) if lint_baseline is None: return LintCheckResult( False, "Baseline lint mode requires a compatible saved Ruff baseline.", lint_mode, local_passed=local_passed, ) try: lint_run = run_ruff_json( project_dir, **_python_override_kwargs(python_executable), ) validate_ruff_baseline( lint_baseline, project_dir, lint_baseline.project_name, lint_run.version, ) introduced = introduced_diagnostics(lint_baseline, lint_run) except LintBaselineError as exc: return LintCheckResult( False, f"Baseline lint unavailable: {exc}", lint_mode, local_passed=local_passed, ) baseline_count = lint_baseline.diagnostic_count introduced_count = len(introduced) if introduced_count: baseline_output = ( f"Baseline Ruff: {baseline_count} existing, {introduced_count} introduced.\n" f"{format_diagnostic_summary(introduced)}" ) return LintCheckResult( False, _combine_lint_output(local_output, baseline_output, local_passed), lint_mode, local_passed=local_passed, baseline_diagnostic_count=baseline_count, introduced_diagnostic_count=introduced_count, baseline_loaded=True, ) return LintCheckResult( True, _combine_lint_output( local_output, f"Baseline Ruff: {baseline_count} existing, 0 introduced.", local_passed, ), lint_mode, local_passed=local_passed, baseline_diagnostic_count=baseline_count, baseline_loaded=True, ) def _format_command( linter: str, task_files: list[Path], *, python_executable: str | Path | None = None ) -> str: if linter.lower() == "ruff": python = python_executable or sys.executable paths = _quoted_paths(task_files) return ( f'"{python}" -m ruff check --fix --select I {paths} && ' f'"{python}" -m ruff format {paths}' ) if linter.lower() == "eslint": return f"npx prettier --write {_quoted_paths(task_files)} 2>&1" return "" def _ruff_command( task_files: list[Path] | None = None, *, python_executable: str | Path | None = None ) -> str: target = _quoted_paths(task_files) if task_files else "." return f'"{python_executable or sys.executable}" -m ruff check {target}' def _quoted_paths(paths: list[Path]) -> str: return " ".join(f'"{path.as_posix()}"' for path in paths) def _python_override_kwargs(python_executable: str | Path | None) -> dict[str, str | Path]: return {"python_executable": python_executable} if python_executable is not None else {} def _command_output(result: subprocess.CompletedProcess[str]) -> str: return _bounded_output(_combined_output(result)) def _combined_output(result: subprocess.CompletedProcess[str]) -> str: stdout = (result.stdout or "").strip() stderr = (result.stderr or "").strip() parts = [stdout] if stdout else [] if stderr: parts.append(f"[stderr]\n{stderr}") return "\n".join(parts) or "(no output)" def _bounded_output(output: str, limit: int = 4000) -> str: if len(output) <= limit: return output side = limit // 2 omitted = len(output) - (side * 2) return f"{output[:side]}\n... <{omitted} characters omitted> ...\n{output[-side:]}" def _combine_lint_output(local_output: str, global_output: str, local_passed: bool) -> str: if local_passed: return global_output return f"Task-owned Ruff check failed:\n{local_output}\n\n{global_output}" def _normalize_owned_files(project_dir: Path, files_changed: list[str]) -> list[Path]: normalized: set[Path] = set() project_root = project_dir.resolve() for raw_path in files_changed: candidate = Path(raw_path) if candidate.is_absolute(): resolved = candidate.resolve() else: resolved = (project_root / candidate).resolve() try: relative = resolved.relative_to(project_root) except ValueError: continue normalized.add(relative) return sorted(normalized, key=lambda path: path.as_posix()) def _outside_project_files(project_dir: Path, files_changed: list[str]) -> list[str]: project_root = project_dir.resolve() outside: list[str] = [] for raw_path in files_changed: candidate = Path(raw_path) resolved = ( candidate.resolve() if candidate.is_absolute() else (project_root / candidate).resolve() ) try: resolved.relative_to(project_root) except ValueError: outside.append(str(raw_path)) return outside def _run_diff_check(project_dir: Path) -> tuple[bool, str]: try: repository = _run_text_command("git rev-parse --is-inside-work-tree", project_dir, 30) except (subprocess.TimeoutExpired, OSError) as exc: return False, f"Could not determine Git repository state: {exc}" if repository.returncode != 0: return True, "Git diff check skipped outside a Git worktree." try: result = _run_text_command("git diff --check", project_dir, 30) except (subprocess.TimeoutExpired, OSError) as exc: return False, f"Git diff check failed to run: {exc}" return result.returncode == 0, _command_output(result) def _run_tests( project_dir: Path, test_framework: str, *, excluded_test_files: list[str] | None = None, test_files: list[str] | None = None, python_executable: str | Path | None = None, timeout: int = DEFAULT_TEST_TIMEOUT_SECONDS, ) -> tuple[bool, str]: python = python_executable or sys.executable commands: dict[str, str] = { "pytest": f'"{python}" -m pytest -x --tb=short 2>&1', "unittest": f'"{python}" -m unittest discover -v 2>&1', "jest": "npx jest --passWithNoTests 2>&1", "vitest": "npx vitest run 2>&1", "mocha": "npx mocha 2>&1", } # Exit codes that indicate "no tests" rather than "tests failed" NO_TESTS_CODES: dict[str, set[int]] = { "pytest": {5}, "unittest": {0}, # unittest returns 0 if no tests found } no_tests_ok = NO_TESTS_CODES.get(test_framework.lower(), set()) cmd = commands.get(test_framework.lower(), "") if test_files and test_framework.lower() == "pytest": selected = " ".join(f'"{path}"' for path in test_files) cmd = cmd.replace("-x --tb=short", f"-x --tb=short {selected}") if excluded_test_files and test_framework.lower() == "pytest": cmd = cmd.replace("-x --tb=short", "-x --tb=short " + " ".join( f'--ignore="{path}"' for path in excluded_test_files )) if not cmd: cmd = test_framework try: result = _run_text_command(cmd, project_dir, timeout) output = _command_output(result) if result.returncode == 0: return True, output if result.returncode in no_tests_ok: return True, output + "\n(no tests found — ok)" return False, output except subprocess.TimeoutExpired: return False, f"Tests timed out for: {test_framework} (after {timeout}s)" except Exception as e: return False, f"Test runner error: {e}"