"""Trusted, read-only acceptance validation for explicitly profiled AFK tasks.""" from __future__ import annotations import hashlib import subprocess from pathlib import Path from afk_developer.backends.models import ( AcceptanceFinding, AcceptanceOutcome, AcceptanceValidationResult, ) from afk_developer.config import Config from afk_developer.evidence import EvidencePacket, EvidencePacketError, EvidencePacketStore from afk_developer.planner.task_model import AcceptanceProfile, TaskNode def validate_profiled_task( *, task: TaskNode, config: Config, project_dir: Path | str, ) -> AcceptanceValidationResult: """Run the trusted validator owned by the task's explicit acceptance profile.""" if task.acceptance_profile is AcceptanceProfile.NONE: return AcceptanceValidationResult( outcome=AcceptanceOutcome.PASS, summary="No acceptance profile is required for this task.", ) if task.acceptance_profile is AcceptanceProfile.CORPUS_RAW_OUTPUT: return _validate_corpus_raw_output(task, config, Path(project_dir)) return AcceptanceValidationResult( outcome=AcceptanceOutcome.VALIDATOR_ERROR, summary=( f"Acceptance profile '{task.acceptance_profile.value}' has no trusted validator " "implementation." ), ) def _validate_corpus_raw_output( task: TaskNode, config: Config, project_dir: Path, ) -> AcceptanceValidationResult: if not task.evidence_packet_id or task.evidence_revision is None: return _missing_evidence( "No immutable evidence packet is attached to this corpus/raw-output task." ) store = EvidencePacketStore(config.projects_dir) try: packet = store.load_packet( project_name=_packet_coordinates(task.evidence_packet_id)[0], task_id=_packet_coordinates(task.evidence_packet_id)[1], revision=task.evidence_revision, ) if packet.packet_id != task.evidence_packet_id: return _missing_evidence( "The task evidence packet ID does not match the persisted revision." ) if packet.fingerprint != task.evidence_fingerprint: return _missing_evidence( "The task evidence fingerprint does not match the persisted packet." ) store.validate_packet_sources(packet) except EvidencePacketError as exc: return _missing_evidence(f"Evidence packet validation failed: {exc}") except Exception as exc: return AcceptanceValidationResult( outcome=AcceptanceOutcome.VALIDATOR_ERROR, summary=f"Could not load the evidence packet: {exc}", ) if not packet.raw_output_contracts: return _missing_evidence( "The evidence packet has no source-backed raw_output_contracts for deterministic comparison." ) findings = _compare_raw_output_contracts(packet, project_dir) if findings: return AcceptanceValidationResult( outcome=AcceptanceOutcome.FINDINGS, summary=f"Corpus/raw-output validation found {len(findings)} mismatch(es).", findings=findings, ) return AcceptanceValidationResult( outcome=AcceptanceOutcome.PASS, summary=( "Corpus/raw-output validation passed: every declared artifact exactly matches its " "source-backed raw excerpt." ), ) def _packet_coordinates(packet_id: str) -> tuple[str, str]: """Return packet owner coordinates from a canonical immutable packet ID.""" try: project_name, task_id, revision = packet_id.rsplit("/", 2) except ValueError as exc: raise EvidencePacketError( "Evidence packet ID is not a canonical project/task/revision identifier." ) from exc if not project_name or not task_id or not revision.startswith("revision-"): raise EvidencePacketError( "Evidence packet ID is not a canonical project/task/revision identifier." ) return project_name, task_id def _missing_evidence(question: str) -> AcceptanceValidationResult: return AcceptanceValidationResult( outcome=AcceptanceOutcome.BLOCKED_MISSING_EVIDENCE, summary="Acceptance validation is blocked by missing or invalid evidence.", research_question=question, ) def _compare_raw_output_contracts( packet: EvidencePacket, project_dir: Path, ) -> list[AcceptanceFinding]: project_root = project_dir.resolve() findings: list[AcceptanceFinding] = [] for contract in packet.raw_output_contracts: source = packet.sources[contract.source_index] expected = source.excerpt.encode("utf-8") target = (project_root / contract.output_path).resolve() source_reference = _source_reference(source) if not target.is_relative_to(project_root): findings.append( _finding( kind="OUTPUT_PATH_ESCAPE", output_path=contract.output_path, expected="A project-relative generated artifact path.", actual="The contract path resolved outside the target project.", source_reference=source_reference, ) ) continue if not target.is_file(): findings.append( _finding( kind="MISSING_RAW_OUTPUT", output_path=contract.output_path, expected=_snippet(expected), actual="Generated artifact is missing.", source_reference=source_reference, ) ) continue expected_eol = _expected_eol(expected) declared_eol = _git_declared_eol(project_root, contract.output_path) if expected_eol and declared_eol is not None and declared_eol != expected_eol: findings.append( _finding( kind="RAW_OUTPUT_EOL_POLICY", output_path=contract.output_path, expected=( f"Git attributes must declare eol={expected_eol} so the exact raw fixture " "survives checkout and merge." ), actual=( f"git check-attr reports eol={declared_eol or 'unspecified'} for the artifact." ), source_reference=source_reference, ) ) actual = target.read_bytes() if actual != expected: findings.append( _finding( kind="RAW_OUTPUT_MISMATCH", output_path=contract.output_path, expected=_snippet(expected), actual=_snippet(actual), source_reference=source_reference, ) ) return findings def _expected_eol(content: bytes) -> str: if b"\r\n" in content: return "crlf" if b"\n" in content: return "lf" return "" def _git_declared_eol(project_root: Path, output_path: str) -> str | None: """Return a tracked checkout EOL policy, or ``None`` outside a Git worktree.""" if not (project_root / ".git").exists(): return None try: completed = subprocess.run( ["git", "-C", str(project_root), "check-attr", "eol", "--", output_path], capture_output=True, check=False, text=True, timeout=10, ) except (OSError, subprocess.TimeoutExpired): return "" if completed.returncode != 0: return "" value = completed.stdout.strip().rsplit(": ", 1)[-1] return value if value in {"lf", "crlf"} else "" def _finding( *, kind: str, output_path: str, expected: str, actual: str, source_reference: str, ) -> AcceptanceFinding: fingerprint_input = "\n".join((kind, output_path, expected, actual, source_reference)) finding_id = hashlib.sha256(fingerprint_input.encode("utf-8")).hexdigest()[:16].upper() return AcceptanceFinding( id=f"AFK-{kind.replace('_', '-')}-{finding_id}", summary=f"{kind.replace('_', ' ').title()} for {output_path}.", expected=expected, actual=actual, source_reference=source_reference, affected_paths=[output_path], suggested_regression=( f"Add an exact raw-output regression for {output_path} against the approved evidence excerpt." ), ) def _source_reference(source) -> str: return ( f"{source.root}/{source.relative_path} " f"markers={source.start_marker!r}..{source.end_marker!r} occurrence={source.occurrence}" ) def _snippet(contents: bytes) -> str: limit = 400 text = contents[:limit].decode("utf-8", errors="replace") return f"{text}{'…' if len(contents) > limit else ''}"