"""Immutable, content-addressed local discovery checkpoints. Checkpoints cache verified local facts and their source manifest, never LLM responses, changed code, task branches, or review outcomes. They are opt-in through ``TaskNode.discovery_contract`` and can be shared only by an explicit contract cache key plus an exact current input fingerprint. """ from __future__ import annotations import hashlib import json from datetime import datetime, timezone from pathlib import Path from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator from afk_developer.fsutil import atomic_write_text from afk_developer.planner.task_model import DiscoveryContract CHECKPOINT_SCHEMA_VERSION = 1 DISCOVERY_POLICY_VERSION = "local-source-manifest-v1" MAX_INPUT_FILES = 100 MAX_INPUT_BYTES = 8_000_000 MAX_SUMMARY_CHARS = 4_000 class DiscoveryCheckpointError(ValueError): """A checkpoint cannot safely be created, loaded, or reused.""" class DiscoveryInput(BaseModel): """One exact project file that anchored cached local conclusions.""" model_config = ConfigDict(extra="forbid") path: str sha256: str = Field(pattern=r"^[0-9a-f]{64}$") class DiscoveryCheckpoint(BaseModel): """A compact, auditable result of a bounded local discovery stage.""" model_config = ConfigDict(extra="forbid") schema_version: int = CHECKPOINT_SCHEMA_VERSION fingerprint: str = Field(pattern=r"^[0-9a-f]{64}$") cache_key: str created_at: datetime inputs: list[DiscoveryInput] = Field(min_length=1, max_length=MAX_INPUT_FILES) evidence_fingerprint: str = "" canonical_paths: list[str] = Field(default_factory=list, max_length=100) canonical_symbols: list[str] = Field(default_factory=list, max_length=100) conclusions: list[str] = Field(min_length=1, max_length=100) exclusions: list[str] = Field(default_factory=list, max_length=50) allowed_output_paths: list[str] = Field(min_length=1, max_length=100) approved_next_action: str = Field(min_length=1, max_length=2_000) summary: str = Field(min_length=1, max_length=MAX_SUMMARY_CHARS) source_task_id: str = Field(min_length=1, max_length=200) source_attempt_id: str = Field(default="", max_length=200) @field_validator("canonical_paths", "allowed_output_paths") @classmethod def _require_relative_paths(cls, values: list[str]) -> list[str]: for value in values: path = Path(value) if ( not value or "\\" in value or path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts) ): raise ValueError("checkpoint paths must be safe project-relative POSIX paths") return values class DiscoveryCheckpointDraft(BaseModel): """Untrusted researcher proposal for a bounded local discovery checkpoint.""" model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) source_paths: list[str] = Field(min_length=1, max_length=MAX_INPUT_FILES) canonical_paths: list[str] = Field(default_factory=list, max_length=100) canonical_symbols: list[str] = Field(default_factory=list, max_length=100) conclusions: list[str] = Field(min_length=1, max_length=100) approved_next_action: str = Field(min_length=1, max_length=2_000) summary: str = Field(min_length=1, max_length=MAX_SUMMARY_CHARS) @field_validator("source_paths", "canonical_paths") @classmethod def _require_safe_paths(cls, values: list[str]) -> list[str]: if len(set(values)) != len(values): raise ValueError("discovery proposal paths must be unique") for value in values: path = Path(value) if ( not value or "\\" in value or path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts) ): raise ValueError("discovery proposal paths must be safe project-relative POSIX paths") return values @field_validator("conclusions", "canonical_symbols") @classmethod def _require_non_empty_entries(cls, values: list[str]) -> list[str]: if any(not value.strip() for value in values): raise ValueError("discovery proposal entries must be non-empty") return values def resolve_inputs(contract: DiscoveryContract, project_dir: Path) -> list[DiscoveryInput]: """Hash declared exact input files without following paths outside the project.""" root = project_dir.resolve() inputs: list[DiscoveryInput] = [] total_bytes = 0 for relative in sorted(contract.input_paths): candidate = root / relative try: resolved = candidate.resolve(strict=True) resolved.relative_to(root) except (FileNotFoundError, ValueError, OSError) as exc: raise DiscoveryCheckpointError( f"Declared discovery input is unavailable or outside the project: {relative}" ) from exc if not resolved.is_file(): raise DiscoveryCheckpointError(f"Declared discovery input is not a file: {relative}") size = resolved.stat().st_size total_bytes += size if len(inputs) >= MAX_INPUT_FILES or total_bytes > MAX_INPUT_BYTES: raise DiscoveryCheckpointError( "Discovery input manifest exceeds the bounded file-count or byte limit." ) inputs.append(DiscoveryInput(path=relative, sha256=_file_sha256(resolved))) return inputs def compute_fingerprint( contract: DiscoveryContract, inputs: list[DiscoveryInput], *, evidence_fingerprint: str = "", ) -> str: """Return the canonical cache key for one contract and current source state.""" payload = { "schema_version": CHECKPOINT_SCHEMA_VERSION, "policy_version": DISCOVERY_POLICY_VERSION, "contract": contract.model_dump(mode="json"), "inputs": [item.model_dump(mode="json") for item in sorted(inputs, key=lambda item: item.path)], "evidence_fingerprint": evidence_fingerprint, } encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8") return hashlib.sha256(encoded).hexdigest() def create_checkpoint( *, contract: DiscoveryContract, inputs: list[DiscoveryInput], source_task_id: str, conclusions: list[str], summary: str, approved_next_action: str, source_attempt_id: str = "", canonical_paths: list[str] | None = None, canonical_symbols: list[str] | None = None, evidence_fingerprint: str = "", ) -> DiscoveryCheckpoint: """Build a structurally valid checkpoint from a trusted discovery result.""" return DiscoveryCheckpoint( fingerprint=compute_fingerprint( contract, inputs, evidence_fingerprint=evidence_fingerprint, ), cache_key=contract.cache_key, created_at=datetime.now(timezone.utc), inputs=inputs, evidence_fingerprint=evidence_fingerprint, canonical_paths=canonical_paths or [], canonical_symbols=canonical_symbols or [], conclusions=conclusions, exclusions=list(contract.exclusions), allowed_output_paths=list(contract.allowed_output_paths), approved_next_action=approved_next_action, summary=summary, source_task_id=source_task_id, source_attempt_id=source_attempt_id, ) def checkpoint_from_draft( *, contract: DiscoveryContract, inputs: list[DiscoveryInput], source_task_id: str, draft: DiscoveryCheckpointDraft, source_attempt_id: str = "", evidence_fingerprint: str = "", ) -> DiscoveryCheckpoint: """Validate a researcher draft against the declared manifest and contract.""" declared_paths = {item.path for item in inputs} if not set(draft.source_paths).issubset(declared_paths): raise DiscoveryCheckpointError( "Discovery proposal cited a path outside the declared input manifest." ) if not set(draft.canonical_paths).issubset(declared_paths): raise DiscoveryCheckpointError( "Discovery proposal named a canonical path outside the declared input manifest." ) return create_checkpoint( contract=contract, inputs=inputs, source_task_id=source_task_id, source_attempt_id=source_attempt_id, conclusions=draft.conclusions, canonical_paths=draft.canonical_paths, canonical_symbols=draft.canonical_symbols, approved_next_action=draft.approved_next_action, summary=draft.summary, evidence_fingerprint=evidence_fingerprint, ) class DiscoveryCheckpointStore: """Persists immutable artifacts by fingerprint below AFK's project state.""" def __init__(self, projects_dir: Path | str): self.projects_dir = Path(projects_dir) def checkpoint_path(self, project_name: str, fingerprint: str) -> Path: _validate_component("project_name", project_name) if len(fingerprint) != 64 or any(char not in "0123456789abcdef" for char in fingerprint): raise DiscoveryCheckpointError("Invalid checkpoint fingerprint.") return self.projects_dir / project_name / "discovery-checkpoints" / f"{fingerprint}.json" def save(self, project_name: str, checkpoint: DiscoveryCheckpoint) -> DiscoveryCheckpoint: path = self.checkpoint_path(project_name, checkpoint.fingerprint) if path.exists(): existing = self.load(project_name, checkpoint.fingerprint) if existing.model_dump(mode="json") != checkpoint.model_dump(mode="json"): return existing return existing atomic_write_text(path, checkpoint.model_dump_json(indent=2)) return self.load(project_name, checkpoint.fingerprint) def load(self, project_name: str, fingerprint: str) -> DiscoveryCheckpoint: path = self.checkpoint_path(project_name, fingerprint) if not path.is_file(): raise DiscoveryCheckpointError(f"Discovery checkpoint does not exist: {path}") try: checkpoint = DiscoveryCheckpoint.model_validate_json(path.read_text(encoding="utf-8")) except (OSError, ValidationError) as exc: raise DiscoveryCheckpointError(f"Invalid discovery checkpoint artifact: {path}: {exc}") from exc if checkpoint.fingerprint != fingerprint: raise DiscoveryCheckpointError("Checkpoint fingerprint does not match its filename.") return checkpoint def load_current( self, *, project_name: str, contract: DiscoveryContract, project_dir: Path, evidence_fingerprint: str = "", ) -> DiscoveryCheckpoint | None: """Return the exact current hit, treating any mismatch as a cache miss.""" inputs = resolve_inputs(contract, project_dir) fingerprint = compute_fingerprint( contract, inputs, evidence_fingerprint=evidence_fingerprint, ) try: checkpoint = self.load(project_name, fingerprint) except DiscoveryCheckpointError: return None if checkpoint.cache_key != contract.cache_key or checkpoint.inputs != inputs: return None return checkpoint def _file_sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while chunk := handle.read(1024 * 1024): digest.update(chunk) return digest.hexdigest() def _validate_component(name: str, value: str) -> None: if not value or "/" in value or "\\" in value or value in {".", ".."}: raise DiscoveryCheckpointError(f"Invalid checkpoint {name}.")