import hashlib from pathlib import Path from afk_developer.scheduler import reviewer from afk_developer.scheduler.lint_baseline import LintBaseline, RuffLintRun class _CompletedProcess: returncode = 0 stdout = "ok" stderr = "" class _MissingOutputProcess: returncode = 0 stdout = None stderr = None def test_reviewer_runs_python_tools_via_the_active_interpreter(tmp_path, monkeypatch): commands: list[str] = [] environments: list[dict[str, str]] = [] def fake_run(command, **kwargs): commands.append(command) environments.append(kwargs["env"]) return _CompletedProcess() monkeypatch.setattr(reviewer.subprocess, "run", fake_run) assert reviewer._auto_format(tmp_path, "ruff", [Path("changed.py")])[0] assert reviewer._run_linter(tmp_path, "ruff").passed assert reviewer._run_tests(tmp_path, "pytest")[0] assert all(reviewer.sys.executable in command for command in commands) assert any("ruff check --fix --select I" in command for command in commands) assert any("-m ruff format" in command for command in commands) assert any("-m ruff check" in command for command in commands) assert any("-m pytest" in command for command in commands) assert all(environment["PYTHONDONTWRITEBYTECODE"] == "1" for environment in environments) def test_reviewer_runs_python_tools_via_an_explicit_target_interpreter(tmp_path, monkeypatch): commands: list[str] = [] target_python = tmp_path / "target-python" def fake_run(command, **_kwargs): commands.append(command) return _CompletedProcess() monkeypatch.setattr(reviewer.subprocess, "run", fake_run) assert reviewer._auto_format( tmp_path, "ruff", [Path("changed.py")], python_executable=target_python )[0] assert reviewer._run_linter(tmp_path, "ruff", python_executable=target_python).passed assert reviewer._run_tests(tmp_path, "pytest", python_executable=target_python)[0] assert all(str(target_python) in command for command in commands) def test_reviewer_excludes_declared_red_pytest_file_from_baseline(tmp_path, monkeypatch): commands: list[str] = [] def fake_run(command, **_kwargs): commands.append(command) return _CompletedProcess() monkeypatch.setattr(reviewer.subprocess, "run", fake_run) assert reviewer._run_tests( tmp_path, "pytest", excluded_test_files=["tests/test_red_regression.py"] )[0] assert '--ignore="tests/test_red_regression.py"' in commands[0] def test_red_regression_verifier_requires_an_actual_test_failure(tmp_path, monkeypatch): test_file = tmp_path / "tests" / "test_red_regression.py" test_file.parent.mkdir() test_file.write_text("def test_red(): pass\n", encoding="utf-8") class _FailingProcess: returncode = 1 stdout = "1 failed in 0.01s" stderr = "" monkeypatch.setattr(reviewer.subprocess, "run", lambda *_args, **_kwargs: _FailingProcess()) assert reviewer.verify_red_regression_tests( tmp_path, "pytest", ["tests/test_red_regression.py"] ) == (True, "Declared red-regression tests fail as expected before repair.") def test_red_regression_verifier_accepts_import_collection_error(tmp_path): test_file = tmp_path / "tests" / "test_import_contract.py" test_file.parent.mkdir() test_file.write_text("import afk_red_witness_package_that_does_not_exist\n", encoding="utf-8") assert reviewer.verify_red_regression_tests( tmp_path, "pytest", ["tests/test_import_contract.py"] ) == (True, "Declared red-regression tests fail as expected before repair.") def test_red_regression_verifier_rejects_non_test_pytest_errors(tmp_path, monkeypatch): test_file = tmp_path / "tests" / "test_red_regression.py" test_file.parent.mkdir() test_file.write_text("def test_red(): pass\n", encoding="utf-8") class _InternalErrorProcess: returncode = 3 stdout = "INTERNALERROR: setup failed" stderr = "" monkeypatch.setattr( reviewer.subprocess, "run", lambda *_args, **_kwargs: _InternalErrorProcess() ) assert reviewer.verify_red_regression_tests( tmp_path, "pytest", ["tests/test_red_regression.py"] ) == ( False, ( "Red-regression test did not produce a test failure: " "tests/test_red_regression.py.\n\n" "Focused pytest output:\nINTERNALERROR: setup failed" ), ) def test_reviewer_accepts_a_serialized_project_path(tmp_path, monkeypatch): monkeypatch.setattr(reviewer, "_auto_format", lambda *_args: (False, "")) monkeypatch.setattr( reviewer, "_run_linter", lambda *_args: reviewer.LintCheckResult(True, "", reviewer.LintMode.STRICT), ) monkeypatch.setattr(reviewer, "_run_tests", lambda *_args, **_kwargs: (True, "")) (tmp_path / "result.txt").write_text("done", encoding="utf-8") result = reviewer.review_task(str(tmp_path), "ruff", "pytest", ["result.txt"]) assert result.passed def test_read_only_review_does_not_apply_formatting(tmp_path, monkeypatch): monkeypatch.setattr( reviewer, "_auto_format", lambda *_args: (_ for _ in ()).throw(AssertionError("Formatting must not run")), ) monkeypatch.setattr( reviewer, "_run_linter", lambda *_args: reviewer.LintCheckResult(True, "", reviewer.LintMode.STRICT), ) monkeypatch.setattr(reviewer, "_run_tests", lambda *_args, **_kwargs: (True, "")) result = reviewer.review_task(tmp_path, "ruff", "pytest", apply_format=False) assert result.passed assert not result.format_applied def test_review_skips_pytest_when_unscoped_runs_are_disallowed_without_owned_tests( tmp_path, monkeypatch ): monkeypatch.setattr(reviewer, "_auto_format", lambda *_args, **_kwargs: (False, "")) monkeypatch.setattr( reviewer, "_run_linter", lambda *_args, **_kwargs: reviewer.LintCheckResult( True, "", reviewer.LintMode.STRICT ), ) monkeypatch.setattr( reviewer, "_run_tests", lambda *_args, **_kwargs: (_ for _ in ()).throw( AssertionError("Unscoped pytest must not run") ), ) monkeypatch.setattr(reviewer, "_run_diff_check", lambda *_args: (True, "")) (tmp_path / "package.py").write_text("VALUE = 1\n", encoding="utf-8") result = reviewer.review_task( tmp_path, "ruff", "pytest", ["package.py"], disallow_unscoped_pytest=True, ) assert result.passed assert result.tests_passed assert result.test_output == "Scoped pytest skipped: task owns no test files." def test_review_skips_python_tools_for_scoped_non_python_task(tmp_path, monkeypatch): monkeypatch.setattr( reviewer, "_auto_format", lambda *_args, **_kwargs: (_ for _ in ()).throw( AssertionError("Scoped non-Python task must not run a formatter") ), ) monkeypatch.setattr( reviewer, "_run_linter", lambda *_args, **_kwargs: (_ for _ in ()).throw( AssertionError("Scoped non-Python task must not run Ruff") ), ) monkeypatch.setattr( reviewer, "_run_tests", lambda *_args, **_kwargs: (_ for _ in ()).throw( AssertionError("Scoped non-Python task must not run pytest") ), ) monkeypatch.setattr(reviewer, "_run_diff_check", lambda *_args: (True, "")) (tmp_path / "README.md").write_text("# Project\n", encoding="utf-8") result = reviewer.review_task( tmp_path, "ruff", "pytest", ["README.md"], disallow_unscoped_pytest=True, ) assert result.passed assert not result.format_applied assert result.lint_output == "Scoped lint skipped: task owns no Python files." assert result.test_output == "Scoped pytest skipped: task owns no test files." def test_review_runs_only_owned_tests_when_unscoped_pytest_is_disallowed( tmp_path, monkeypatch ): selected_test_files: list[str] = [] def fake_run_tests(*_args, **kwargs): selected_test_files.extend(kwargs["test_files"]) return True, "focused tests passed" monkeypatch.setattr(reviewer, "_auto_format", lambda *_args, **_kwargs: (False, "")) monkeypatch.setattr( reviewer, "_run_linter", lambda *_args, **_kwargs: reviewer.LintCheckResult( True, "", reviewer.LintMode.STRICT ), ) monkeypatch.setattr(reviewer, "_run_tests", fake_run_tests) monkeypatch.setattr(reviewer, "_run_diff_check", lambda *_args: (True, "")) owned_test = tmp_path / "tests" / "test_owned.py" owned_test.parent.mkdir() owned_test.write_text("def test_owned():\n assert True\n", encoding="utf-8") (owned_test.parent / "test_protected.py").write_text( "def test_protected():\n assert False\n", encoding="utf-8" ) result = reviewer.review_task( tmp_path, "ruff", "pytest", ["tests/test_owned.py"], disallow_unscoped_pytest=True, ) assert result.passed assert selected_test_files == ["tests/test_owned.py"] def test_reviewer_handles_missing_subprocess_streams(tmp_path, monkeypatch): monkeypatch.setattr( reviewer.subprocess, "run", lambda *_args, **_kwargs: _MissingOutputProcess() ) result = reviewer._run_linter(tmp_path, "flake8") assert result.passed assert result.output == "(no output)" def test_review_preserves_output_head_tail_and_full_command_artifact(tmp_path, monkeypatch): full_output = "HEAD\n" + ("middle\n" * 1000) + "TAIL" class _FailingProcess: returncode = 1 stdout = full_output stderr = "" monkeypatch.setattr(reviewer, "_auto_format", lambda *_args, **_kwargs: (False, "")) monkeypatch.setattr( reviewer, "_run_linter", lambda *_args, **_kwargs: reviewer.LintCheckResult( True, "", reviewer.LintMode.STRICT ), ) monkeypatch.setattr(reviewer, "_run_diff_check", lambda *_args: (True, "")) monkeypatch.setattr(reviewer, "_worktree_change_scope", lambda *_args: (1, 1)) monkeypatch.setattr(reviewer.subprocess, "run", lambda *_args, **_kwargs: _FailingProcess()) (tmp_path / "result.py").write_text("value = 1\n", encoding="utf-8") result = reviewer.review_task( tmp_path, "ruff", "pytest", ["result.py"], diagnostic_dir=tmp_path / "diagnostics", ) assert not result.passed assert "HEAD" in result.test_output assert "TAIL" in result.test_output assert "characters omitted" in result.test_output assert len(result.command_evidence) == 1 evidence = result.command_evidence[0] assert evidence.exit_code == 1 assert evidence.elapsed_seconds >= 0 assert evidence.output_sha256 == hashlib.sha256(full_output.encode("utf-8")).hexdigest() assert evidence.output_character_count == len(full_output) assert evidence.output_truncated assert evidence.output_head.startswith("HEAD") assert evidence.output_tail.endswith("TAIL") artifact_bytes = Path(evidence.output_artifact_path).read_bytes() assert artifact_bytes == full_output.encode("utf-8") assert hashlib.sha256(artifact_bytes).hexdigest() == evidence.output_sha256 assert len(artifact_bytes) == evidence.output_character_count def test_repeated_reviews_append_command_artifacts(tmp_path, monkeypatch): outputs = iter(["first review", "second review"]) def fake_run(*_args, **_kwargs): return reviewer.subprocess.CompletedProcess([], 1, stdout=next(outputs), stderr="") monkeypatch.setattr(reviewer, "_auto_format", lambda *_args, **_kwargs: (False, "")) monkeypatch.setattr( reviewer, "_run_linter", lambda *_args, **_kwargs: reviewer.LintCheckResult( True, "", reviewer.LintMode.STRICT ), ) monkeypatch.setattr(reviewer, "_run_diff_check", lambda *_args: (True, "")) monkeypatch.setattr(reviewer, "_worktree_change_scope", lambda *_args: (1, 1)) monkeypatch.setattr(reviewer.subprocess, "run", fake_run) (tmp_path / "result.py").write_text("value = 1\n", encoding="utf-8") diagnostic_dir = tmp_path / "diagnostics" first = reviewer.review_task( tmp_path, "ruff", "pytest", ["result.py"], diagnostic_dir=diagnostic_dir ) second = reviewer.review_task( tmp_path, "ruff", "pytest", ["result.py"], diagnostic_dir=diagnostic_dir ) first_path = Path(first.command_evidence[0].output_artifact_path) second_path = Path(second.command_evidence[0].output_artifact_path) assert first_path != second_path assert first_path.read_text(encoding="utf-8") == "first review" assert second_path.read_text(encoding="utf-8") == "second review" def test_review_fails_when_git_diff_check_reports_whitespace_errors(tmp_path, monkeypatch): monkeypatch.setattr(reviewer, "_auto_format", lambda *_args: (False, "")) monkeypatch.setattr( reviewer, "_run_linter", lambda *_args: reviewer.LintCheckResult(True, "", reviewer.LintMode.STRICT), ) monkeypatch.setattr(reviewer, "_run_tests", lambda *_args, **_kwargs: (True, "")) monkeypatch.setattr(reviewer, "_run_diff_check", lambda *_args: (False, "trailing whitespace")) result = reviewer.review_task(tmp_path, "ruff", "pytest") assert not result.passed assert not result.diff_passed assert result.diff_output == "trailing whitespace" def test_review_rejects_excessive_mutation_scope(tmp_path, monkeypatch): monkeypatch.setattr(reviewer, "_auto_format", lambda *_args: (False, "")) monkeypatch.setattr( reviewer, "_run_linter", lambda *_args: reviewer.LintCheckResult(True, "", reviewer.LintMode.STRICT), ) monkeypatch.setattr(reviewer, "_run_tests", lambda *_args, **_kwargs: (True, "")) monkeypatch.setattr(reviewer, "_worktree_change_scope", lambda *_args: (7, 450)) (tmp_path / "result.txt").write_text("done", encoding="utf-8") result = reviewer.review_task( tmp_path, "ruff", "pytest", ["result.txt"], max_changed_files=6, max_changed_lines=400, ) assert not result.passed assert not result.scope_passed assert "Mutation scope exceeded" in result.summary def test_review_rejects_unreported_untracked_worker_probe(tmp_path, monkeypatch): monkeypatch.setattr(reviewer, "_auto_format", lambda *_args: (False, "")) monkeypatch.setattr( reviewer, "_run_linter", lambda *_args: reviewer.LintCheckResult(True, "", reviewer.LintMode.STRICT), ) monkeypatch.setattr(reviewer, "_run_tests", lambda *_args, **_kwargs: (True, "")) monkeypatch.setattr(reviewer, "_run_diff_check", lambda *_args: (True, "")) probe = tmp_path / "scratch_probe.py" probe.write_text("print('probe')\n", encoding="utf-8") monkeypatch.setattr( reviewer, "_run_text_command", lambda command, *_args: type( "Result", (), {"stdout": "scratch_probe.py\n" if "ls-files" in command else ""}, )(), ) result = reviewer.review_task( tmp_path, "ruff", "pytest", ["tests/test_feature.py", "scratch_probe.py"], reported_files=["tests/test_feature.py"], ) assert not result.passed assert not result.ownership_passed assert result.unreported_untracked_files == ["scratch_probe.py"] assert "Unreported untracked files: scratch_probe.py." in result.summary def test_corpus_review_requires_fixture_and_focused_test(tmp_path, monkeypatch): monkeypatch.setattr(reviewer, "_auto_format", lambda *_args: (False, "")) monkeypatch.setattr( reviewer, "_run_linter", lambda *_args: reviewer.LintCheckResult(True, "", reviewer.LintMode.STRICT), ) monkeypatch.setattr(reviewer, "_run_tests", lambda *_args, **_kwargs: (True, "")) (tmp_path / "implementation.py").write_text("value = 1\n", encoding="utf-8") result = reviewer.review_task( tmp_path, "ruff", "pytest", ["implementation.py"], require_raw_contract_artifacts=True, ) assert not result.passed assert not result.artifact_contract_passed def test_baseline_lint_allows_preexisting_task_owned_diagnostics(tmp_path, monkeypatch): baseline = LintBaseline( schema_version=1, project_name="example", project_path=str(tmp_path.resolve()).replace("\\", "/").casefold(), linter="ruff", linter_version="0.0.0", command="ruff check", captured_at="2026-01-01T00:00:00+00:00", git_head=None, diagnostic_fingerprints=["existing"], ) monkeypatch.setattr( reviewer, "_run_text_command", lambda *_args: type( "RuffFailure", (), {"returncode": 1, "stdout": "legacy.py:1:1 F401", "stderr": ""} )(), ) monkeypatch.setattr( reviewer, "run_ruff_json", lambda *_args: RuffLintRun("0.0.0", ["existing"], [{"code": "F401"}]), ) monkeypatch.setattr(reviewer, "validate_ruff_baseline", lambda *_args: None) result = reviewer._run_ruff_linter( tmp_path, [Path("legacy.py")], reviewer.LintMode.BASELINE, baseline, ) assert result.passed assert not result.local_passed assert result.introduced_diagnostic_count == 0 def test_review_uses_the_supplied_test_timeout(tmp_path, monkeypatch): """The full-suite reviewer budget must be configurable, not a 300s constant.""" seen: list[tuple[str, int]] = [] def fake_run(command, _project_dir, timeout): seen.append((command, timeout)) return _CompletedProcess() monkeypatch.setattr(reviewer, "_run_text_command", fake_run) monkeypatch.setattr(reviewer, "_run_diff_check", lambda *_args: (True, "")) monkeypatch.setattr( reviewer, "_run_linter", lambda *_args, **_kwargs: reviewer.LintCheckResult(True, "", reviewer.LintMode.STRICT), ) (tmp_path / "package.py").write_text("VALUE = 1\n", encoding="utf-8") reviewer.review_task( tmp_path, "ruff", "pytest", ["package.py"], apply_format=False, test_timeout=1800, ) assert [timeout for command, timeout in seen if "pytest" in command] == [1800] def test_review_test_timeout_defaults_to_the_documented_constant(tmp_path, monkeypatch): seen: list[tuple[str, int]] = [] def fake_run(command, _project_dir, timeout): seen.append((command, timeout)) return _CompletedProcess() monkeypatch.setattr(reviewer, "_run_text_command", fake_run) monkeypatch.setattr(reviewer, "_run_diff_check", lambda *_args: (True, "")) monkeypatch.setattr( reviewer, "_run_linter", lambda *_args, **_kwargs: reviewer.LintCheckResult(True, "", reviewer.LintMode.STRICT), ) (tmp_path / "package.py").write_text("VALUE = 1\n", encoding="utf-8") reviewer.review_task(tmp_path, "ruff", "pytest", ["package.py"], apply_format=False) assert [timeout for command, timeout in seen if "pytest" in command] == [ reviewer.DEFAULT_TEST_TIMEOUT_SECONDS ]