"""Typed, read-only verification requests shared by every worker backend.""" from __future__ import annotations import hashlib import re import shlex import subprocess import sys import time from enum import Enum from pathlib import Path from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator from afk_developer.planner.task_model import VerificationAttemptEvent from afk_developer.scheduler.lint_baseline import compare_ruff_baseline class VerificationKind(str, Enum): PYTEST = "pytest" RUFF_CHECK = "ruff_check" RUFF_FORMAT_CHECK = "ruff_format_check" GIT_STATUS = "git_status" GIT_DIFF_CHECK = "git_diff_check" GIT_LOG = "git_log" GIT_SHOW = "git_show" FILE_SHA256 = "file_sha256" BASELINE_COMPARE = "baseline_compare" class VerificationOutcomeCode(str, Enum): PASSED = "verification_passed" COMMAND_FAILED = "verification_command_failed" POLICY_REJECTED = "verification_policy_rejected" TOOL_FAILED = "verification_tool_failed" class VerificationRequest(BaseModel): """A limited read-only verification action, never an arbitrary shell command.""" model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) kind: VerificationKind paths: list[str] = Field(default_factory=list, max_length=100) extra_safe_args: list[str] = Field(default_factory=list, max_length=20) timeout_seconds: int = Field(default=60, ge=1, le=3600) project_name: str | None = Field(default=None, max_length=128) @field_validator("paths", "extra_safe_args") @classmethod def _reject_empty_values(cls, values: list[str]) -> list[str]: if any(not isinstance(value, str) or not value.strip() for value in values): raise ValueError("paths and extra_safe_args cannot contain empty values") return values class VerificationOutcome(BaseModel): """A normalized verifier result suitable for an agent tool response and task state.""" code: VerificationOutcomeCode output: str = "" command: list[str] = Field(default_factory=list) return_code: int | None = None elapsed_seconds: float = 0.0 @property def passed(self) -> bool: return self.code is VerificationOutcomeCode.PASSED @property def is_infrastructure_failure(self) -> bool: return self.code in { VerificationOutcomeCode.POLICY_REJECTED, VerificationOutcomeCode.TOOL_FAILED, } def to_tool_text(self) -> str: prefix = self.code.value.upper() detail = self.output.strip() or "No verifier output." return f"{prefix}: {detail}" def verification_attempt_event( request: VerificationRequest | dict, outcome: VerificationOutcome, *, artifact_dir: Path | str | None = None, event_index: int = 1, ) -> VerificationAttemptEvent: """Build bounded, runner-owned telemetry for one typed verification call.""" if isinstance(request, VerificationRequest): kind = request.kind.value path_count = len(request.paths) else: raw_kind = request.get("kind", "invalid") kind = raw_kind.value if isinstance(raw_kind, VerificationKind) else str(raw_kind) raw_paths = request.get("paths", []) path_count = len(raw_paths) if isinstance(raw_paths, list) else 0 output = outcome.output output_artifact_path = "" if artifact_dir is not None: output_path = Path(artifact_dir) / f"verification-{event_index:03d}.log" while output_path.exists(): event_index += 1 output_path = Path(artifact_dir) / f"verification-{event_index:03d}.log" try: output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text(output, encoding="utf-8", newline="") if len(str(output_path)) <= 4_096: output_artifact_path = str(output_path) except OSError: pass return VerificationAttemptEvent( kind=kind, command=subprocess.list2cmdline(outcome.command)[:2_000], normalized_path_count=path_count, elapsed_seconds=outcome.elapsed_seconds, outcome_code=outcome.code.value, return_code=outcome.return_code, output_sha256=hashlib.sha256(output.encode("utf-8")).hexdigest(), output_character_count=len(output), output_truncated=len(output) > 4_000, output_head=output[:2_000], output_tail=output[-2_000:] if len(output) > 2_000 else "", output_artifact_path=output_artifact_path, rejection_reason=output[:1_000] if not outcome.passed else "", ) VERIFICATION_TOOL_SCHEMA = { "type": "object", "additionalProperties": False, "properties": { "kind": { "type": "string", "enum": [kind.value for kind in VerificationKind], "description": ( "The fixed read-only verification operation to run. file_sha256 hashes " "project files. baseline_compare compares AFK's saved Ruff lint baseline only; " "it does not validate Git revisions, environments, or file integrity." ), }, "paths": { "type": "array", "items": {"type": "string"}, "description": ( "Optional project-relative paths for pytest, Ruff, or file_sha256 verification." ), }, "extra_safe_args": { "type": "array", "items": {"type": "string"}, "description": ( "Narrowly allowlisted read-only options for pytest or Ruff. pytest also " "accepts a marker selection pair: -m , where the " "expression is limited to word characters, spaces, and/or/not. Git " "operations construct their own fixed commands; git_log also accepts the " "canonical compatibility form --oneline -n <1-20>." ), }, "timeout_seconds": { "type": "integer", "minimum": 1, "description": "Requested timeout, capped by the configured AFK shell timeout.", }, "project_name": { "type": "string", "description": ( "Ignored for baseline_compare: AFK always supplies the current task's " "own project automatically, regardless of any value given here." ), }, }, "required": ["kind"], } _PYTEST_SAFE_ARGS = { "-q", "-v", "-x", "--collect-only", "--disable-warnings", "--tb=auto", "--tb=line", "--tb=long", "--tb=native", "--tb=no", "--tb=short", } _RUFF_CHECK_SAFE_ARGS = {"--output-format=json", "--preview"} _RUFF_FORMAT_SAFE_ARGS = {"--diff", "--preview"} _UNSAFE_TOKEN_MARKERS = (";", "|", "&", ">", "<", "\n", "\r", "`", "\x00") _MARKER_EXPRESSION_PATTERN = re.compile(r"^[\w\s]+$") _PROJECT_NAME_PATTERN = re.compile(r"^[A-Za-z0-9_-]+$") _GIT_LOG_DEFAULT_LIMIT = 20 _GIT_LOG_LIMIT_PATTERN = re.compile(r"^[1-9]\d*$") _GIT_SHOW_PRESENTATION_ARGS = frozenset({"--stat", "--oneline", "-1"}) class _VerificationPolicyError(ValueError): pass def run_verification_request( request: VerificationRequest | dict, project_dir: Path | str, *, max_timeout_seconds: int = 60, projects_dir: Path | str | None = None, python_executable: Path | str | None = None, default_project_name: str = "", ) -> VerificationOutcome: """Execute one fixed read-only verification request without invoking a shell.""" started = time.monotonic() try: verified_request = _coerce_request(request) if default_project_name and verified_request.kind is VerificationKind.BASELINE_COMPARE: # The model has no principled way to know AFK's internal per-phase state # key, so its own guess (e.g. a human-facing distribution name) is never # trusted here -- the caller's real plan.project_name always wins. verified_request = verified_request.model_copy( update={"project_name": default_project_name} ) project_root = Path(project_dir).resolve() if not project_root.is_dir(): raise _VerificationPolicyError(f"Project directory does not exist: {project_root}") command = _build_command( verified_request, project_root, max_timeout_seconds, python_executable=python_executable, ) effective_timeout_seconds = min( verified_request.timeout_seconds, max_timeout_seconds, ) except _VerificationPolicyError as exc: return _outcome(VerificationOutcomeCode.POLICY_REJECTED, str(exc), started) if verified_request.kind is VerificationKind.FILE_SHA256: return _run_file_sha256( verified_request, project_root, started, effective_timeout_seconds, ) if verified_request.kind is VerificationKind.BASELINE_COMPARE: return _run_baseline_compare( verified_request, project_root, projects_dir, started, ) try: result = subprocess.run( command, cwd=str(project_root), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=effective_timeout_seconds, shell=False, ) except subprocess.TimeoutExpired: return _outcome( VerificationOutcomeCode.TOOL_FAILED, f"Verification timed out after {effective_timeout_seconds}s.", started, command, ) except OSError as exc: return _outcome( VerificationOutcomeCode.TOOL_FAILED, f"Could not start verification tool: {exc}", started, command, ) output = _command_output(result) code = ( VerificationOutcomeCode.PASSED if result.returncode == 0 else VerificationOutcomeCode.COMMAND_FAILED ) return _outcome(code, output, started, command, result.returncode) def parse_legacy_verification_command(command: str) -> VerificationRequest | None: """Parse the prior string API into a strict typed request without executing it.""" if not isinstance(command, str) or not command.strip(): return None if any(marker in command for marker in _UNSAFE_TOKEN_MARKERS): return None try: tokens = shlex.split(command, posix=False) except ValueError: return None if not tokens: return None executable = Path(tokens[0].strip('"')).name.lower() arguments = [token.strip('"') for token in tokens[1:]] if executable in {"git", "git.exe"}: return _parse_legacy_git(arguments) if executable not in {"python", "python.exe", "py", "py.exe"}: return None if len(arguments) < 2 or arguments[0].lower() != "-m": return None module = arguments[1].lower() remaining = arguments[2:] if module == "pytest": return _make_legacy_request(VerificationKind.PYTEST, remaining) if module != "ruff" or not remaining: return None action = remaining[0].lower() if action == "check": return _make_legacy_request(VerificationKind.RUFF_CHECK, remaining[1:]) if action == "format" and "--check" in {value.lower() for value in remaining[1:]}: without_check = [value for value in remaining[1:] if value.lower() != "--check"] return _make_legacy_request(VerificationKind.RUFF_FORMAT_CHECK, without_check) return None def _parse_legacy_git(arguments: list[str]) -> VerificationRequest | None: if not arguments: return None action = arguments[0].lower() kind_by_action = { "status": VerificationKind.GIT_STATUS, "diff": VerificationKind.GIT_DIFF_CHECK, "log": VerificationKind.GIT_LOG, "show": VerificationKind.GIT_SHOW, } kind = kind_by_action.get(action) if kind is None: return None try: request = VerificationRequest(kind=kind, extra_safe_args=arguments[1:]) _validate_safe_args(request) except (ValidationError, _VerificationPolicyError): return None return request def _make_legacy_request( kind: VerificationKind, arguments: list[str], ) -> VerificationRequest | None: safe_args: list[str] = [] paths: list[str] = [] index = 0 while index < len(arguments): argument = arguments[index] if ( kind is VerificationKind.PYTEST and argument.lower() == "-m" and index + 1 < len(arguments) ): safe_args.append(argument) safe_args.append(arguments[index + 1]) index += 2 continue if argument.startswith("-"): safe_args.append(argument) else: paths.append(argument) index += 1 try: request = VerificationRequest(kind=kind, paths=paths, extra_safe_args=safe_args) _validate_safe_args(request) except (ValidationError, _VerificationPolicyError): return None return request def _coerce_request(request: VerificationRequest | dict) -> VerificationRequest: try: return ( request if isinstance(request, VerificationRequest) else VerificationRequest.model_validate(request) ) except ValidationError as exc: detail = exc.errors(include_url=False)[0].get("msg", "invalid request") raise _VerificationPolicyError(f"Invalid verification request: {detail}") from exc def _build_command( request: VerificationRequest, project_root: Path, max_timeout_seconds: int, *, python_executable: Path | str | None = None, ) -> list[str]: if max_timeout_seconds < 1: raise _VerificationPolicyError( "The configured verification timeout must be at least one second." ) normalized_paths = _normalize_paths(project_root, request.paths) _validate_safe_args(request) python = str(python_executable or sys.executable) if request.kind is VerificationKind.PYTEST: return [python, "-m", "pytest", *request.extra_safe_args, *normalized_paths] if request.kind is VerificationKind.RUFF_CHECK: return [python, "-m", "ruff", "check", *request.extra_safe_args, *normalized_paths] if request.kind is VerificationKind.RUFF_FORMAT_CHECK: return [ python, "-m", "ruff", "format", "--check", *request.extra_safe_args, *normalized_paths, ] if request.kind is VerificationKind.GIT_STATUS: _require_no_paths(request, normalized_paths) return ["git", "status", "--short"] if request.kind is VerificationKind.GIT_DIFF_CHECK: _require_no_paths(request, normalized_paths) return ["git", "diff", "--check"] if request.kind is VerificationKind.GIT_LOG: _require_no_paths(request, normalized_paths) return ["git", "log", "--oneline", "-n", str(_git_log_limit(request.extra_safe_args))] if request.kind is VerificationKind.GIT_SHOW: _require_no_paths(request, normalized_paths) return ["git", "show", "--stat", "--oneline", "-1"] if request.kind is VerificationKind.FILE_SHA256: if not normalized_paths: raise _VerificationPolicyError("file_sha256 requires at least one project file path.") return ["sha256", *normalized_paths] if request.kind is VerificationKind.BASELINE_COMPARE: _require_no_paths(request, normalized_paths) if not request.project_name or not _PROJECT_NAME_PATTERN.fullmatch(request.project_name): raise _VerificationPolicyError( "baseline_compare requires a project_name containing only letters, digits, hyphens, or underscores." ) return [] raise _VerificationPolicyError(f"Unsupported verification kind: {request.kind}") def _normalize_paths(project_root: Path, paths: list[str]) -> list[str]: normalized: list[str] = [] for raw_path in paths: candidate = Path(raw_path) if candidate.is_absolute() or ".." in candidate.parts: raise _VerificationPolicyError( f"Verification paths must be project-relative and cannot traverse parents: {raw_path}" ) resolved = (project_root / candidate).resolve() try: relative = resolved.relative_to(project_root) except ValueError as exc: raise _VerificationPolicyError( f"Verification path resolves outside the project: {raw_path}" ) from exc normalized.append(relative.as_posix() or ".") return normalized def _pytest_args_are_safe(arguments: list[str]) -> bool: """Validate pytest options in order, since -m takes a paired marker expression.""" index = 0 while index < len(arguments): value = arguments[index].lower() if value in _PYTEST_SAFE_ARGS or ( value.startswith("--maxfail=") and value.removeprefix("--maxfail=").isdigit() ): index += 1 continue if value == "-m": if index + 1 >= len(arguments) or not _MARKER_EXPRESSION_PATTERN.fullmatch( arguments[index + 1] ): return False index += 2 continue return False return True def _validate_safe_args(request: VerificationRequest) -> None: if any( any(marker in value for marker in _UNSAFE_TOKEN_MARKERS) for value in request.extra_safe_args ): raise _VerificationPolicyError("Verification options cannot contain shell syntax.") normalized_arguments = [value.lower() for value in request.extra_safe_args] arguments = set(normalized_arguments) if request.kind is VerificationKind.PYTEST: valid = _pytest_args_are_safe(request.extra_safe_args) elif request.kind is VerificationKind.RUFF_CHECK: valid = arguments <= _RUFF_CHECK_SAFE_ARGS elif request.kind is VerificationKind.RUFF_FORMAT_CHECK: valid = arguments <= _RUFF_FORMAT_SAFE_ARGS elif request.kind is VerificationKind.GIT_STATUS: valid = normalized_arguments in ([], ["--short"], ["--porcelain"]) elif request.kind is VerificationKind.GIT_DIFF_CHECK: valid = normalized_arguments in ([], ["--check"]) elif request.kind is VerificationKind.GIT_LOG: try: _git_log_limit(request.extra_safe_args) valid = True except _VerificationPolicyError: valid = False elif request.kind is VerificationKind.GIT_SHOW: valid = _git_show_is_safe(normalized_arguments) else: valid = not arguments if not valid: raise _VerificationPolicyError( f"The requested options are not permitted for {request.kind.value}." ) def _git_log_limit(arguments: list[str]) -> int: """Return the requested bounded log count from the sole supported compatibility form.""" if not arguments: return _GIT_LOG_DEFAULT_LIMIT normalized = [value.lower() for value in arguments] if ( len(normalized) != 3 or normalized[:2] != ["--oneline", "-n"] or not _GIT_LOG_LIMIT_PATTERN.fullmatch(normalized[2]) ): raise _VerificationPolicyError( "git_log accepts only the compatibility form --oneline -n <1-20>." ) limit = int(normalized[2]) if limit > _GIT_LOG_DEFAULT_LIMIT: raise _VerificationPolicyError( f"git_log may request at most {_GIT_LOG_DEFAULT_LIMIT} entries." ) return limit def _git_show_is_safe(arguments: list[str]) -> bool: """Accept only harmless presentation forms for AFK's fixed HEAD inspection. The verifier always runs ``git show --stat --oneline -1``. Supporting models sometimes repeat all or part of that display form, and may append the equivalent literal ``HEAD`` revision. Normalize those forms without allowing arbitrary revisions, pathspecs, or formatting options. """ if not arguments: return True if arguments.count("head") > 1: return False if "head" in arguments and arguments[-1] != "head": return False presentation = [argument for argument in arguments if argument != "head"] return ( len(presentation) == len(set(presentation)) and set(presentation) <= _GIT_SHOW_PRESENTATION_ARGS ) def _require_no_paths(request: VerificationRequest, normalized_paths: list[str]) -> None: if normalized_paths: raise _VerificationPolicyError(f"{request.kind.value} does not accept file paths.") def _run_baseline_compare( request: VerificationRequest, project_root: Path, projects_dir: Path | str | None, started: float, ) -> VerificationOutcome: if projects_dir is None: return _outcome( VerificationOutcomeCode.TOOL_FAILED, "The AFK state projects directory is unavailable for baseline comparison.", started, ) assert request.project_name is not None baseline_path = Path(projects_dir) / request.project_name / "lint-baseline.json" if not baseline_path.is_file(): return _outcome( VerificationOutcomeCode.POLICY_REJECTED, "No immutable lint baseline exists for this task. Use ruff_check for strict-mode " "verification; baseline_compare is available only when AFK prepared a baseline.", started, ) output = compare_ruff_baseline(baseline_path, project_root, request.project_name) if output.startswith("Error:"): return _outcome(VerificationOutcomeCode.TOOL_FAILED, output, started) if "Introduced diagnostics: 0" in output: return _outcome(VerificationOutcomeCode.PASSED, output, started) return _outcome(VerificationOutcomeCode.COMMAND_FAILED, output, started) def _run_file_sha256( request: VerificationRequest, project_root: Path, started: float, timeout_seconds: int, ) -> VerificationOutcome: normalized_paths = _normalize_paths(project_root, request.paths) deadline = started + timeout_seconds lines: list[str] = [] for relative_path in normalized_paths: if time.monotonic() >= deadline: return _outcome( VerificationOutcomeCode.TOOL_FAILED, f"File hashing timed out after {timeout_seconds}s.", started, ["sha256", *normalized_paths], ) path = project_root / relative_path if not path.is_file(): return _outcome( VerificationOutcomeCode.COMMAND_FAILED, f"File does not exist or is not a regular file: {relative_path}", started, ["sha256", *normalized_paths], 1, ) digest = hashlib.sha256() try: with path.open("rb") as handle: while chunk := handle.read(1024 * 1024): digest.update(chunk) if time.monotonic() >= deadline: return _outcome( VerificationOutcomeCode.TOOL_FAILED, f"File hashing timed out after {timeout_seconds}s.", started, ["sha256", *normalized_paths], ) except OSError as exc: return _outcome( VerificationOutcomeCode.TOOL_FAILED, f"Could not hash file {relative_path}: {exc}", started, ["sha256", *normalized_paths], ) lines.append(f"{digest.hexdigest().upper()} {relative_path}") return _outcome( VerificationOutcomeCode.PASSED, "\n".join(lines), started, ["sha256", *normalized_paths], 0, ) def _command_output(result: subprocess.CompletedProcess[str]) -> str: output: list[str] = [] if result.stdout: output.append(result.stdout.strip()) if result.stderr: output.append(f"[stderr]\n{result.stderr.strip()}") if result.returncode != 0: output.append(f"[exit code: {result.returncode}]") return "\n".join(output) if output else f"Verification completed (exit {result.returncode})." def _outcome( code: VerificationOutcomeCode, output: str, started: float, command: list[str] | None = None, return_code: int | None = None, ) -> VerificationOutcome: return VerificationOutcome( code=code, output=output, command=command or [], return_code=return_code, elapsed_seconds=time.monotonic() - started, )