"""Validated, immutable evidence packets for high-risk acceptance work.""" from __future__ import annotations import hashlib import json import mmap import os from datetime import datetime, timezone from enum import Enum from pathlib import Path from tempfile import NamedTemporaryFile from typing import TYPE_CHECKING, Any, Literal from pydantic import ( BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator, ) from afk_developer.planner.task_model import AttemptUsage, TaskLifecyclePhase, TaskNode, TaskStatus if TYPE_CHECKING: from afk_developer.backends.models import ResearchProposalResult from afk_developer.config import Config EVIDENCE_PACKET_SCHEMA_VERSION = 2 LEGACY_EVIDENCE_PACKET_SCHEMA_VERSION = 1 MAX_EVIDENCE_SOURCES = 100 MAX_EXCERPT_CHARS = 60_000 _SAFE_COMPONENT_CHARS = frozenset( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_." ) class EvidencePacketError(ValueError): """Raised when proposed evidence cannot become a trusted packet.""" class EvidencePacketDuplicateError(EvidencePacketError): """Raised when a supplement repeats already-validated source evidence.""" class EvidenceConclusion(str, Enum): """Whether immutable evidence establishes or rules out a bounded implementation.""" SUPPORTED = "supported" INSUFFICIENT = "insufficient" class EvidenceSourceProposal(BaseModel): """A model-proposed locator; trusted code derives every observed value.""" model_config = ConfigDict(extra="forbid") root: str = Field(min_length=1, max_length=4096) relative_path: str = Field(min_length=1, max_length=4096) start_marker: str = Field(min_length=1, max_length=10_000) end_marker: str = Field(min_length=1, max_length=10_000) occurrence: int = Field(default=0, ge=0) @field_validator("root", "relative_path") @classmethod def _strip_location_values(cls, value: str) -> str: """Normalize path-like values without altering literal boundary markers.""" return value.strip() class EvidenceSource(EvidenceSourceProposal): """A verified source excerpt, bounded by literal markers in an approved root.""" sha256: str = Field(pattern=r"^[0-9a-f]{64}$") excerpt: str = Field(min_length=1, max_length=MAX_EXCERPT_CHARS) class ObservedRule(BaseModel): """A concise structural or behavioral rule directly supported by sources.""" model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) category: str = Field(min_length=1, max_length=128) statement: str = Field(min_length=1, max_length=4_000) source_indices: list[int] = Field(min_length=1, max_length=MAX_EVIDENCE_SOURCES) @field_validator("source_indices") @classmethod def _require_unique_indices(cls, values: list[int]) -> list[int]: if any(value < 0 for value in values) or len(set(values)) != len(values): raise ValueError("source_indices must contain unique non-negative values") return values class SupportBoundary(BaseModel): """The supported contract and explicit exclusions derived from evidence.""" model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) supported_forms: list[str] = Field(min_length=1, max_length=100) exclusions: list[str] = Field(default_factory=list, max_length=100) @field_validator("supported_forms", "exclusions") @classmethod def _reject_empty_items(cls, values: list[str]) -> list[str]: if any(not value.strip() for value in values): raise ValueError("support-boundary entries cannot be empty") return values class RawOutputContract(BaseModel): """One exact raw artifact expected from a source-backed corpus excerpt.""" model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) output_path: str = Field(min_length=1, max_length=4096) source_index: int = Field(ge=0) @field_validator("output_path") @classmethod def _require_project_relative_path(cls, value: str) -> str: path = Path(value) if path.is_absolute() or ".." in path.parts: raise ValueError("output_path must be project-relative and cannot traverse parents") return path.as_posix() class EvidencePacketDraft(BaseModel): """The structured facts a researcher proposes before trusted serialization.""" model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) sources: list[EvidenceSourceProposal] = Field(min_length=1, max_length=MAX_EVIDENCE_SOURCES) facts: list[str] = Field(min_length=1, max_length=200) observed_rules: list[ObservedRule] = Field(min_length=1, max_length=200) support_boundary: SupportBoundary conclusion: EvidenceConclusion = EvidenceConclusion.SUPPORTED raw_output_contracts: list[RawOutputContract] = Field(default_factory=list, max_length=100) unanswered_questions: list[str] = Field(default_factory=list, max_length=100) parent_revision: int | None = Field(default=None, ge=1) @field_validator("facts", "unanswered_questions") @classmethod def _reject_empty_text(cls, values: list[str]) -> list[str]: if any(not value.strip() for value in values): raise ValueError("evidence facts and questions cannot be empty") return values @model_validator(mode="after") def _validate_conclusion(self) -> "EvidencePacketDraft": if self.conclusion is EvidenceConclusion.INSUFFICIENT: if self.raw_output_contracts: raise ValueError("insufficient evidence cannot declare raw-output contracts") if not self.support_boundary.exclusions: raise ValueError("insufficient evidence requires explicit exclusions") return self class ResearcherMetadata(BaseModel): """The configured read-only route used to produce one evidence proposal.""" model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) role: Literal["researcher"] = "researcher" endpoint: str = Field(min_length=1, max_length=128) model: str = Field(min_length=1, max_length=256) reasoning_effort: str = Field(default="", max_length=32) usage: AttemptUsage = Field(default_factory=AttemptUsage) class EvidencePacket(BaseModel): """Canonical, immutable evidence artifact consumed by later validation phases.""" model_config = ConfigDict(extra="forbid") schema_version: Literal[ LEGACY_EVIDENCE_PACKET_SCHEMA_VERSION, EVIDENCE_PACKET_SCHEMA_VERSION ] = EVIDENCE_PACKET_SCHEMA_VERSION packet_id: str project_name: str task_id: str revision: int = Field(ge=1) created_at: datetime approved_roots: list[str] = Field(min_length=1, max_length=MAX_EVIDENCE_SOURCES) sources: list[EvidenceSource] = Field(min_length=1, max_length=MAX_EVIDENCE_SOURCES) facts: list[str] = Field(min_length=1, max_length=200) observed_rules: list[ObservedRule] = Field(min_length=1, max_length=200) support_boundary: SupportBoundary conclusion: EvidenceConclusion = EvidenceConclusion.SUPPORTED raw_output_contracts: list[RawOutputContract] = Field(default_factory=list, max_length=100) unanswered_questions: list[str] = Field(default_factory=list, max_length=100) parent_revision: int | None = Field(default=None, ge=1) researcher: ResearcherMetadata fingerprint: str = Field(pattern=r"^[0-9a-f]{64}$") EVIDENCE_PACKET_DRAFT_TOOL_SCHEMA: dict[str, Any] = { "type": "object", "additionalProperties": False, "properties": { "sources": { "type": "array", "items": { "type": "object", "additionalProperties": False, "properties": { "root": {"type": "string"}, "relative_path": {"type": "string"}, "start_marker": {"type": "string"}, "end_marker": {"type": "string"}, "occurrence": {"type": "integer", "minimum": 0}, }, "required": ["root", "relative_path", "start_marker", "end_marker"], }, }, "facts": {"type": "array", "items": {"type": "string"}}, "observed_rules": { "type": "array", "items": { "type": "object", "additionalProperties": False, "properties": { "category": {"type": "string"}, "statement": {"type": "string"}, "source_indices": {"type": "array", "items": {"type": "integer"}}, }, "required": ["category", "statement", "source_indices"], }, }, "support_boundary": { "type": "object", "additionalProperties": False, "properties": { "supported_forms": {"type": "array", "items": {"type": "string"}}, "exclusions": {"type": "array", "items": {"type": "string"}}, }, "required": ["supported_forms", "exclusions"], }, "conclusion": {"type": "string", "enum": [item.value for item in EvidenceConclusion]}, "raw_output_contracts": { "type": "array", "items": { "type": "object", "additionalProperties": False, "properties": { "output_path": {"type": "string"}, "source_index": {"type": "integer", "minimum": 0}, }, "required": ["output_path", "source_index"], }, }, "unanswered_questions": {"type": "array", "items": {"type": "string"}}, "parent_revision": {"type": "integer", "minimum": 1}, }, "required": ["sources", "facts", "observed_rules", "support_boundary"], } def normalize_evidence_roots( roots: list[str] | tuple[str, ...], *, project_dir: Path | None = None, ) -> list[str]: """Return canonical external evidence roots selected by a human at the CLI.""" project_root = project_dir.resolve() if project_dir is not None else None normalized: set[str] = set() for raw_root in roots: candidate = Path(raw_root).expanduser().resolve() if not candidate.is_dir(): raise EvidencePacketError(f"Evidence root is not a directory: {candidate}") if project_root and (candidate == project_root or candidate.is_relative_to(project_root)): raise EvidencePacketError( f"Evidence roots must be external to the target project; received {candidate}." ) normalized.add(str(candidate)) if not normalized: raise EvidencePacketError("At least one external evidence root is required.") return sorted(normalized) class EvidencePacketStore: """Creates and validates atomic evidence revisions below AFK's state directory.""" def __init__(self, projects_dir: Path | str): self.projects_dir = Path(projects_dir) def create_packet( self, *, project_name: str, task_id: str, approved_roots: list[str], draft: EvidencePacketDraft | dict[str, Any], researcher: ResearcherMetadata | dict[str, Any], ) -> EvidencePacket: self._validate_component("project_name", project_name) self._validate_component("task_id", task_id) normalized_roots = normalize_evidence_roots(approved_roots) try: trusted_draft = ( draft if isinstance(draft, EvidencePacketDraft) else EvidencePacketDraft.model_validate(draft) ) trusted_researcher = ( researcher if isinstance(researcher, ResearcherMetadata) else ResearcherMetadata.model_validate(researcher) ) except ValidationError as exc: raise EvidencePacketError(f"Invalid evidence packet proposal: {exc}") from exc latest = self._load_latest_packet(project_name, task_id) if latest is None and trusted_draft.parent_revision is not None: trusted_draft = trusted_draft.model_copy(update={"parent_revision": None}) self._validate_parent_revision(trusted_draft.parent_revision, latest) sources = self._validate_sources(trusted_draft.sources, normalized_roots) self._validate_rule_sources(trusted_draft.observed_rules, len(sources)) self._validate_raw_output_contracts(trusted_draft.raw_output_contracts, len(sources)) if latest is not None and not _source_evidence_keys(sources) - _source_evidence_keys( latest.sources ): raise EvidencePacketDuplicateError( "An evidence supplement must add a newly verified source excerpt, not only new conclusions." ) revision = 1 if latest is None else latest.revision + 1 packet = EvidencePacket( packet_id=f"{project_name}/{task_id}/revision-{revision}", project_name=project_name, task_id=task_id, revision=revision, created_at=datetime.now(timezone.utc), approved_roots=normalized_roots, sources=sources, facts=trusted_draft.facts, observed_rules=trusted_draft.observed_rules, support_boundary=trusted_draft.support_boundary, conclusion=trusted_draft.conclusion, raw_output_contracts=trusted_draft.raw_output_contracts, unanswered_questions=trusted_draft.unanswered_questions, parent_revision=trusted_draft.parent_revision, researcher=trusted_researcher, fingerprint="0" * 64, ) packet.fingerprint = self._fingerprint(packet) if latest and latest.fingerprint == packet.fingerprint: raise EvidencePacketDuplicateError( "Evidence packet adds no new evidence; its fingerprint repeats the latest revision." ) target = self.packet_path(project_name, task_id, revision) self._atomic_create(target, packet) return packet def load_packet( self, *, project_name: str, task_id: str, revision: int, ) -> EvidencePacket: path = self.packet_path(project_name, task_id, revision) if not path.is_file(): raise EvidencePacketError(f"Evidence packet does not exist: {path}") try: packet = EvidencePacket.model_validate_json(path.read_text(encoding="utf-8")) except (OSError, ValidationError) as exc: raise EvidencePacketError(f"Invalid evidence packet artifact: {path}: {exc}") from exc if packet.project_name != project_name or packet.task_id != task_id: raise EvidencePacketError( "Evidence packet project/task identifiers do not match its path." ) if packet.revision != revision or packet.fingerprint != self._fingerprint(packet): raise EvidencePacketError("Evidence packet fingerprint or revision validation failed.") return packet def validate_packet_sources(self, packet: EvidencePacket) -> None: """Fail if a packet source was altered after the immutable packet was created.""" roots = normalize_evidence_roots(packet.approved_roots) proposals = [ EvidenceSourceProposal( root=source.root, relative_path=source.relative_path, start_marker=source.start_marker, end_marker=source.end_marker, occurrence=source.occurrence, ) for source in packet.sources ] refreshed = self._validate_sources(proposals, roots) for stored, current in zip(packet.sources, refreshed, strict=True): if stored.sha256 != current.sha256 or stored.excerpt != current.excerpt: raise EvidencePacketError( f"Evidence source changed since packet creation: {stored.relative_path}" ) def apply_to_task(self, task: TaskNode, packet: EvidencePacket) -> None: """Attach a validated immutable packet reference without copying evidence into the plan.""" if task.id != packet.task_id: raise EvidencePacketError("Cannot attach a packet to a different task.") if task.evidence_fingerprint == packet.fingerprint: raise EvidencePacketError( "The evidence packet fingerprint is already attached to this task." ) if task.evidence_revision is not None and packet.revision <= task.evidence_revision: raise EvidencePacketError( "Evidence packet revisions must advance the task evidence state." ) task.evidence_packet_id = packet.packet_id task.evidence_revision = packet.revision task.evidence_fingerprint = packet.fingerprint task.lifecycle_phase = TaskLifecyclePhase.READY_TO_IMPLEMENT def persist_research_result( self, *, config: Config, project_name: str, task: TaskNode, result: ResearchProposalResult, ) -> EvidencePacket: """Trust-serialize a successful proposal; callers retain control of when research runs.""" if result.status is not TaskStatus.PASSED or result.draft is None: raise EvidencePacketError( "A researcher result without a proposal cannot create evidence." ) route = config.route_for("researcher") endpoint = config.endpoint_for("researcher") packet = self.create_packet( project_name=project_name, task_id=task.id, approved_roots=task.evidence_roots, draft=result.draft, researcher=ResearcherMetadata( endpoint=endpoint.name, model=route.model, reasoning_effort=route.reasoning_effort, usage=AttemptUsage( prompt_tokens=result.usage.prompt_tokens, completion_tokens=result.usage.completion_tokens, total_tokens=result.usage.total_tokens, cache_read_tokens=result.usage.cache_read_tokens, cache_write_tokens=result.usage.cache_write_tokens, reasoning_tokens=result.usage.reasoning_tokens, api_calls=result.usage.api_calls, agent_turns=result.usage.agent_turns, copilot_prompts_submitted=result.usage.copilot_prompts_submitted, copilot_nano_aiu=result.usage.copilot_nano_aiu, ), ), ) self.apply_to_task(task, packet) return packet @staticmethod def prepare_task_research(task: TaskNode) -> None: """Mark a configured task ready for a separately orchestrated research call.""" if not task.evidence_roots: raise EvidencePacketError("Task research requires human-approved evidence roots.") task.lifecycle_phase = TaskLifecyclePhase.RESEARCHING def packet_path(self, project_name: str, task_id: str, revision: int) -> Path: self._validate_component("project_name", project_name) self._validate_component("task_id", task_id) if revision < 1: raise EvidencePacketError("Evidence packet revisions must be positive.") return self.projects_dir / project_name / "evidence" / task_id / f"revision-{revision}.json" def _load_latest_packet(self, project_name: str, task_id: str) -> EvidencePacket | None: directory = self.packet_path(project_name, task_id, 1).parent revisions: list[int] = [] for candidate in directory.glob("revision-*.json") if directory.is_dir() else (): suffix = candidate.stem.removeprefix("revision-") if suffix.isdigit() and int(suffix) > 0: revisions.append(int(suffix)) if not revisions: return None return self.load_packet( project_name=project_name, task_id=task_id, revision=max(revisions), ) @staticmethod def _validate_component(name: str, value: str) -> None: if ( not value or len(value) > 128 or any(char not in _SAFE_COMPONENT_CHARS for char in value) ): raise EvidencePacketError( f"{name} must use only letters, digits, hyphens, underscores, and periods." ) @staticmethod def _validate_parent_revision( parent_revision: int | None, latest: EvidencePacket | None, ) -> None: if latest is None and parent_revision is not None: raise EvidencePacketError("The first evidence revision cannot name a parent revision.") if latest is not None and parent_revision != latest.revision: raise EvidencePacketError( f"The next evidence revision must name parent revision {latest.revision}." ) @staticmethod def _validate_rule_sources(rules: list[ObservedRule], source_count: int) -> None: for rule in rules: if any(index >= source_count for index in rule.source_indices): raise EvidencePacketError("An observed rule refers to a missing evidence source.") @staticmethod def _validate_raw_output_contracts( contracts: list[RawOutputContract], source_count: int, ) -> None: output_paths = [contract.output_path for contract in contracts] if len(set(output_paths)) != len(output_paths): raise EvidencePacketError("Raw output contracts cannot repeat an output path.") if any(contract.source_index >= source_count for contract in contracts): raise EvidencePacketError("A raw output contract refers to a missing evidence source.") @staticmethod def _validate_sources( proposals: list[EvidenceSourceProposal], approved_roots: list[str], ) -> list[EvidenceSource]: sources: list[EvidenceSource] = [] seen: set[tuple[str, str, str, str, int]] = set() approved = set(approved_roots) for proposal in proposals: root = Path(proposal.root).resolve() if str(root) not in approved: raise EvidencePacketError("A proposed source root is not in the approved root set.") requested = Path(proposal.relative_path) if requested.is_absolute() or ".." in requested.parts: raise EvidencePacketError( "Evidence source paths must be project-relative to an approved root." ) candidate = (root / requested).resolve() if not candidate.is_relative_to(root) or not candidate.is_file(): raise EvidencePacketError( f"Evidence source is not a file inside its approved root: {proposal.relative_path}" ) source_key = ( str(root), requested.as_posix(), proposal.start_marker, proposal.end_marker, proposal.occurrence, ) if source_key in seen: raise EvidencePacketError("Evidence packet contains a duplicate source locator.") seen.add(source_key) excerpt = _extract_file_excerpt(candidate, proposal) if len(excerpt) > MAX_EXCERPT_CHARS: raise EvidencePacketError( f"Evidence excerpt exceeds the {MAX_EXCERPT_CHARS} character safety limit." ) source_data = proposal.model_dump() source_data.update( { "root": str(root), "relative_path": requested.as_posix(), "sha256": _sha256_file(candidate), "excerpt": excerpt, } ) sources.append(EvidenceSource.model_validate(source_data)) return sources @staticmethod def _fingerprint(packet: EvidencePacket) -> str: values = packet.model_dump( mode="json", exclude={ "created_at", "fingerprint", "packet_id", "parent_revision", "researcher", "revision", }, ) if packet.schema_version == LEGACY_EVIDENCE_PACKET_SCHEMA_VERSION: values.pop("conclusion", None) encoded = json.dumps(values, sort_keys=True, separators=(",", ":"), ensure_ascii=True) return hashlib.sha256(encoded.encode("utf-8")).hexdigest() @staticmethod def _atomic_create(path: Path, packet: EvidencePacket) -> None: path.parent.mkdir(parents=True, exist_ok=True) payload = json.dumps(packet.model_dump(mode="json"), indent=2, sort_keys=True) + "\n" with NamedTemporaryFile( "w", encoding="utf-8", dir=path.parent, prefix=".revision-", suffix=".tmp", delete=False, ) as handle: handle.write(payload) handle.flush() os.fsync(handle.fileno()) temporary_path = Path(handle.name) try: os.link(temporary_path, path) except FileExistsError as exc: raise EvidencePacketError(f"Evidence revision is already immutable: {path}") from exc except OSError as exc: raise EvidencePacketError( f"Could not atomically create evidence packet: {exc}" ) from exc finally: temporary_path.unlink(missing_ok=True) def _extract_marked_excerpt(contents: str, proposal: EvidenceSourceProposal) -> str: cursor = 0 start = -1 for _ in range(proposal.occurrence + 1): start = contents.find(proposal.start_marker, cursor) if start < 0: raise EvidencePacketError( f"Start marker was not found in evidence source: {proposal.start_marker!r}" ) cursor = start + len(proposal.start_marker) end = contents.find(proposal.end_marker, cursor) if end < 0: raise EvidencePacketError( f"End marker was not found after the start marker: {proposal.end_marker!r}" ) end += len(proposal.end_marker) return contents[start:end] def _extract_file_excerpt(candidate: Path, proposal: EvidenceSourceProposal) -> str: """Extract an evidence span without loading a multi-gigabyte corpus export.""" start_marker = proposal.start_marker.encode("utf-8") end_marker = proposal.end_marker.encode("utf-8") try: with ( candidate.open("rb") as handle, mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as contents, ): cursor = 0 start = -1 for _ in range(proposal.occurrence + 1): start = contents.find(start_marker, cursor) if start < 0: raise EvidencePacketError( f"Start marker was not found in evidence source: {proposal.start_marker!r}" ) cursor = start + len(start_marker) end = contents.find(end_marker, cursor) if end < 0: raise EvidencePacketError( f"End marker was not found after the start marker: {proposal.end_marker!r}" ) excerpt = ( contents[start : end + len(end_marker)] .decode("utf-8", errors="replace") .replace("\r\n", "\n") .replace("\r", "\n") ) except OSError as exc: raise EvidencePacketError(f"Could not read evidence source: {candidate}: {exc}") from exc return excerpt def _sha256_file(candidate: Path) -> str: digest = hashlib.sha256() with candidate.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _source_evidence_keys(sources: list[EvidenceSource]) -> set[tuple[object, ...]]: return { ( source.root, source.relative_path, source.sha256, source.start_marker, source.end_marker, source.occurrence, source.excerpt, ) for source in sources }