import hashlib import sys from pathlib import Path from types import SimpleNamespace from afk_developer.scheduler.tools.schemas import build_tool_schemas, to_openai_tool_definitions from afk_developer.scheduler.tools.shell import run_verification_command from afk_developer.scheduler.verification import ( VERIFICATION_TOOL_SCHEMA, VerificationKind, VerificationOutcomeCode, VerificationRequest, parse_legacy_verification_command, run_verification_request, verification_attempt_event, ) def test_typed_pytest_request_uses_active_interpreter_without_a_shell( tmp_path, monkeypatch ) -> None: calls: list[tuple[list[str], dict]] = [] def fake_run(command, **kwargs): calls.append((command, kwargs)) return SimpleNamespace(returncode=0, stdout="1 passed", stderr="") monkeypatch.setattr("afk_developer.scheduler.verification.subprocess.run", fake_run) outcome = run_verification_request( VerificationRequest( kind=VerificationKind.PYTEST, paths=["tests/test_example.py"], extra_safe_args=["-q"], ), tmp_path, max_timeout_seconds=90, ) assert outcome.code is VerificationOutcomeCode.PASSED assert calls == [ ( [sys.executable, "-m", "pytest", "-q", "tests/test_example.py"], { "cwd": str(tmp_path.resolve()), "capture_output": True, "text": True, "encoding": "utf-8", "errors": "replace", "timeout": 60, "shell": False, }, ) ] def test_file_sha256_hashes_project_files_without_a_subprocess(tmp_path, monkeypatch) -> None: contract = tmp_path / "tests" / "acceptance" / "contract.py" contract.parent.mkdir(parents=True) contract.write_bytes(b"frozen contract\r\n") monkeypatch.setattr( "afk_developer.scheduler.verification.subprocess.run", lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("must not run")), ) outcome = run_verification_request( {"kind": "file_sha256", "paths": ["tests/acceptance/contract.py"]}, tmp_path, ) expected = hashlib.sha256(contract.read_bytes()).hexdigest().upper() assert outcome.code is VerificationOutcomeCode.PASSED assert outcome.output == f"{expected} tests/acceptance/contract.py" assert outcome.command == ["sha256", "tests/acceptance/contract.py"] assert outcome.return_code == 0 def test_file_sha256_reports_file_read_errors_as_tool_failures(tmp_path, monkeypatch) -> None: contract = tmp_path / "contract.py" contract.write_bytes(b"frozen contract\n") def fail_open(_path, *_args, **_kwargs): raise PermissionError("access denied") monkeypatch.setattr(Path, "open", fail_open) outcome = run_verification_request( {"kind": "file_sha256", "paths": ["contract.py"]}, tmp_path, ) assert outcome.code is VerificationOutcomeCode.TOOL_FAILED assert outcome.output == "Could not hash file contract.py: access denied" assert outcome.command == ["sha256", "contract.py"] assert outcome.return_code is None def test_verification_attempt_event_records_bounded_runner_owned_evidence(tmp_path) -> None: outcome = run_verification_request( {"kind": "file_sha256", "paths": ["missing.py"]}, tmp_path, ) event = verification_attempt_event( {"kind": "file_sha256", "paths": ["missing.py"]}, outcome, artifact_dir=tmp_path / "evidence", ) assert event.kind == "file_sha256" assert event.normalized_path_count == 1 assert event.outcome_code == VerificationOutcomeCode.COMMAND_FAILED.value assert event.return_code == 1 assert event.elapsed_seconds >= 0 assert event.output_character_count == len(outcome.output) assert event.output_sha256 == hashlib.sha256(outcome.output.encode("utf-8")).hexdigest() assert Path(event.output_artifact_path).read_bytes() == outcome.output.encode("utf-8") assert event.output_head == outcome.output assert not event.output_truncated assert event.rejection_reason == outcome.output def test_file_sha256_honors_the_bounded_timeout(tmp_path, monkeypatch) -> None: contract = tmp_path / "contract.py" contract.write_bytes(b"frozen contract\n") clock = iter([0.0, 2.0, 2.0]) monkeypatch.setattr( "afk_developer.scheduler.verification.time.monotonic", lambda: next(clock), ) outcome = run_verification_request( {"kind": "file_sha256", "paths": ["contract.py"], "timeout_seconds": 1}, tmp_path, ) assert outcome.code is VerificationOutcomeCode.TOOL_FAILED assert outcome.output == "File hashing timed out after 1s." assert outcome.command == ["sha256", "contract.py"] def test_typed_pytest_request_accepts_collect_only(tmp_path, monkeypatch) -> None: calls: list[list[str]] = [] def fake_run(command, **_kwargs): calls.append(command) return SimpleNamespace(returncode=0, stdout="5 tests collected", stderr="") monkeypatch.setattr("afk_developer.scheduler.verification.subprocess.run", fake_run) outcome = run_verification_request( {"kind": "pytest", "extra_safe_args": ["--collect-only", "-q"]}, tmp_path, ) assert outcome.passed assert calls == [[sys.executable, "-m", "pytest", "--collect-only", "-q"]] def test_typed_pytest_request_accepts_a_marker_selection_pair(tmp_path, monkeypatch) -> None: calls: list[list[str]] = [] def fake_run(command, **_kwargs): calls.append(command) return SimpleNamespace(returncode=0, stdout="1 passed", stderr="") monkeypatch.setattr("afk_developer.scheduler.verification.subprocess.run", fake_run) outcome = run_verification_request( {"kind": "pytest", "extra_safe_args": ["-m", "integration", "-q"]}, tmp_path, ) assert outcome.passed assert calls == [[sys.executable, "-m", "pytest", "-m", "integration", "-q"]] def test_typed_pytest_request_rejects_a_marker_missing_its_value_or_unsafe_expression( tmp_path, monkeypatch ) -> None: monkeypatch.setattr( "afk_developer.scheduler.verification.subprocess.run", lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("must not execute")), ) for extra_safe_args in ( ["-m"], ["-m", "integration and __import__('os')"], ): outcome = run_verification_request( {"kind": "pytest", "extra_safe_args": extra_safe_args}, tmp_path, ) assert outcome.code is VerificationOutcomeCode.POLICY_REJECTED def test_typed_pytest_request_uses_an_explicit_target_interpreter(tmp_path, monkeypatch) -> None: calls: list[list[str]] = [] target_python = tmp_path / "target-python" def fake_run(command, **_kwargs): calls.append(command) return SimpleNamespace(returncode=0, stdout="1 passed", stderr="") monkeypatch.setattr("afk_developer.scheduler.verification.subprocess.run", fake_run) outcome = run_verification_request( VerificationRequest(kind=VerificationKind.PYTEST), tmp_path, python_executable=target_python, ) assert outcome.code is VerificationOutcomeCode.PASSED assert calls == [[str(target_python), "-m", "pytest"]] def test_typed_ruff_requests_are_scoped_and_read_only(tmp_path, monkeypatch) -> None: commands: list[list[str]] = [] def fake_run(command, **_kwargs): commands.append(command) return SimpleNamespace(returncode=0, stdout="ok", stderr="") monkeypatch.setattr("afk_developer.scheduler.verification.subprocess.run", fake_run) check = run_verification_request( { "kind": "ruff_check", "paths": ["package/module.py"], "extra_safe_args": ["--output-format=json"], }, tmp_path, ) format_check = run_verification_request( { "kind": "ruff_format_check", "paths": ["package/module.py"], "extra_safe_args": ["--diff"], }, tmp_path, ) assert check.passed assert format_check.passed assert commands == [ [ sys.executable, "-m", "ruff", "check", "--output-format=json", "package/module.py", ], [ sys.executable, "-m", "ruff", "format", "--check", "--diff", "package/module.py", ], ] def test_typed_git_inspection_uses_fixed_safe_arguments(tmp_path, monkeypatch) -> None: commands: list[list[str]] = [] def fake_run(command, **_kwargs): commands.append(command) return SimpleNamespace(returncode=0, stdout="clean", stderr="") monkeypatch.setattr("afk_developer.scheduler.verification.subprocess.run", fake_run) outcome = run_verification_request({"kind": "git_diff_check"}, tmp_path) assert outcome.passed assert commands == [["git", "diff", "--check"]] def test_typed_git_log_accepts_a_bounded_canonical_compatibility_form( tmp_path, monkeypatch ) -> None: commands: list[list[str]] = [] def fake_run(command, **_kwargs): commands.append(command) return SimpleNamespace(returncode=0, stdout="recent commits", stderr="") monkeypatch.setattr("afk_developer.scheduler.verification.subprocess.run", fake_run) outcome = run_verification_request( { "kind": "git_log", "extra_safe_args": ["--oneline", "-n", "12"], }, tmp_path, ) assert outcome.passed assert commands == [["git", "log", "--oneline", "-n", "12"]] def test_typed_git_log_rejects_unbounded_or_noncanonical_options(tmp_path, monkeypatch) -> None: monkeypatch.setattr( "afk_developer.scheduler.verification.subprocess.run", lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("must not execute")), ) for extra_safe_args in ( ["--oneline", "-n", "21"], ["--oneline", "-n", "0"], ["--all"], ["--oneline", "--max-count=12"], ): outcome = run_verification_request( {"kind": "git_log", "extra_safe_args": extra_safe_args}, tmp_path, ) assert outcome.code is VerificationOutcomeCode.POLICY_REJECTED def test_typed_git_show_normalizes_common_fixed_head_presentation_forms( tmp_path, monkeypatch ) -> None: commands: list[list[str]] = [] def fake_run(command, **_kwargs): commands.append(command) return SimpleNamespace(returncode=0, stdout="latest commit", stderr="") monkeypatch.setattr("afk_developer.scheduler.verification.subprocess.run", fake_run) for extra_safe_args in ( [], ["--stat"], ["--stat", "--oneline", "-1", "HEAD"], ): outcome = run_verification_request( {"kind": "git_show", "extra_safe_args": extra_safe_args}, tmp_path, ) assert outcome.passed assert commands == [["git", "show", "--stat", "--oneline", "-1"]] * 3 def test_typed_git_show_rejects_noncanonical_revisions_and_options(tmp_path, monkeypatch) -> None: monkeypatch.setattr( "afk_developer.scheduler.verification.subprocess.run", lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("must not execute")), ) for extra_safe_args in ( ["HEAD~1"], ["--format=%B"], ["--stat", "--stat"], ["HEAD", "--stat"], ): outcome = run_verification_request( {"kind": "git_show", "extra_safe_args": extra_safe_args}, tmp_path, ) assert outcome.code is VerificationOutcomeCode.POLICY_REJECTED def test_typed_verification_caps_requested_timeout_at_the_runner_limit( tmp_path, monkeypatch ) -> None: calls: list[dict] = [] def fake_run(_command, **kwargs): calls.append(kwargs) return SimpleNamespace(returncode=0, stdout="1 passed", stderr="") monkeypatch.setattr("afk_developer.scheduler.verification.subprocess.run", fake_run) outcome = run_verification_request( {"kind": "pytest", "timeout_seconds": 120}, tmp_path, max_timeout_seconds=60, ) assert outcome.passed assert calls[0]["timeout"] == 60 def test_legacy_worker_exposes_the_shared_typed_verification_schema() -> None: tool_definitions = to_openai_tool_definitions( build_tool_schemas(read_only=True, has_evidence_roots=False) ) verifier = next( definition for definition in tool_definitions if definition["function"]["name"] == "run_verification" ) assert verifier["function"]["parameters"] == VERIFICATION_TOOL_SCHEMA def test_typed_verification_rejects_mutation_shell_syntax_and_outside_paths( tmp_path, monkeypatch ) -> None: monkeypatch.setattr( "afk_developer.scheduler.verification.subprocess.run", lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("must not execute")), ) requests = [ {"kind": "ruff_check", "paths": ["changed.py"], "extra_safe_args": ["--fix"]}, {"kind": "ruff_format_check", "paths": ["changed.py"], "extra_safe_args": ["--fix"]}, {"kind": "pytest", "paths": ["../outside.py"]}, {"kind": "pytest", "extra_safe_args": ["-q; Remove-Item important-file"]}, {"kind": "git_status", "paths": ["README.md"]}, ] for request in requests: outcome = run_verification_request(request, tmp_path, max_timeout_seconds=60) assert outcome.code is VerificationOutcomeCode.POLICY_REJECTED def test_legacy_parser_accepts_absolute_interpreter_for_supported_quality_gates() -> None: request = parse_legacy_verification_command(f'"{sys.executable}" -m pytest -q') assert request is not None assert request.kind is VerificationKind.PYTEST assert request.extra_safe_args == ["-q"] git_log = parse_legacy_verification_command("git log --oneline -n 12") assert git_log is not None assert git_log.kind is VerificationKind.GIT_LOG assert git_log.extra_safe_args == ["--oneline", "-n", "12"] assert parse_legacy_verification_command("git commit -m unsafe") is None assert parse_legacy_verification_command("git log --oneline -n 21") is None assert parse_legacy_verification_command("python -m ruff check --fix .") is None assert parse_legacy_verification_command("python -m pytest -q; git status") is None def test_legacy_parser_accepts_a_pytest_marker_selection_pair() -> None: request = parse_legacy_verification_command("python -m pytest -m integration -q") assert request is not None assert request.kind is VerificationKind.PYTEST assert request.extra_safe_args == ["-m", "integration", "-q"] assert parse_legacy_verification_command("python -m pytest -m") is None def test_legacy_compatibility_shim_never_executes_a_shell_command(tmp_path, monkeypatch) -> None: calls: list[dict] = [] def fake_run(_command, **kwargs): calls.append(kwargs) return SimpleNamespace(returncode=0, stdout="ok", stderr="") monkeypatch.setattr("afk_developer.scheduler.verification.subprocess.run", fake_run) result = run_verification_command(f'"{sys.executable}" -m pytest -q', str(tmp_path)) assert result.startswith("VERIFICATION_PASSED:") assert calls[0]["shell"] is False def test_baseline_compare_rejects_missing_baseline_with_strict_mode_alternative( tmp_path: Path, ) -> None: outcome = run_verification_request( {"kind": "baseline_compare", "project_name": "example"}, tmp_path, projects_dir=tmp_path / "state", ) assert outcome.code is VerificationOutcomeCode.POLICY_REJECTED assert "ruff_check" in outcome.output