"""Campaign ledger: scars (negative facts) and findings (positive facts). Logs go up, the ledger goes down. Raw evidence never enters this file; each entry is one distilled line written by the altitude that judged the evidence, keyed to the content hash of the files it is true about. Tooling -- never a worker -- decides staleness by re-hashing those files against the working tree. """ from __future__ import annotations import hashlib from datetime import UTC, datetime from pathlib import Path from typing import Literal from uuid import uuid4 from pydantic import BaseModel, Field from afk_developer import fsutil MAX_SCARS = 20 _HASH_PREFIX_LENGTH = 12 _SKIP_DIRS = {".git", ".venv", "venv", "__pycache__", "node_modules", ".afk-developer"} class LedgerEntry(BaseModel): """One line of settled knowledge. ``depends_on`` entries are ``path@sha12``.""" id: str = Field(default_factory=lambda: uuid4().hex[:8]) kind: Literal["scar", "finding"] hypothesis: str = Field(min_length=1, max_length=300) tried: str = Field(default="", max_length=300) observed: str = Field(min_length=1, max_length=300) depends_on: list[str] = Field(default_factory=list, max_length=20) author_role: str = Field(default="", max_length=40) task_id: str = Field(default="", max_length=120) created_at: datetime = Field(default_factory=lambda: datetime.now(UTC)) def one_line(self) -> str: deps = ", ".join(self.depends_on) or "(unkeyed)" tried = f" tried: {self.tried};" if self.tried else "" return ( f"[{self.kind}:{self.id}] hypothesis: {self.hypothesis};{tried} " f"observed: {self.observed}; depends-on: {deps}" ) class CampaignLedger(BaseModel): """Per-campaign scar list, findings list, and the click hashes of the ratchet.""" name: str scars: list[LedgerEntry] = Field(default_factory=list) findings: list[LedgerEntry] = Field(default_factory=list) click_hashes: list[str] = Field(default_factory=list) def scar_budget_exhausted(self) -> bool: return len(self.scars) >= MAX_SCARS def find(self, entry_id: str) -> LedgerEntry | None: for entry in (*self.scars, *self.findings): if entry.id == entry_id: return entry return None def render(self) -> str: lines = [ "Settled facts for this campaign. Scars are refuted hypotheses; findings are", "verified facts. Each is keyed to file@hash and has already been checked", "against the current working tree, so every line below is current.", ] for heading, entries in (("Scars:", self.scars), ("Findings:", self.findings)): lines.append(heading) lines.extend(f"- {entry.one_line()}" for entry in entries) if not entries: lines.append("- (none)") return "\n".join(lines) class LedgerBudgetExceeded(RuntimeError): """Raised instead of appending a 21st scar: the campaign must escalate, not accumulate.""" def file_key(project_dir: Path, relative_path: str) -> str | None: """Return ``path@sha12`` for a project-relative file, or None if absent.""" root = Path(project_dir).resolve() candidate = (root / relative_path).resolve() if not candidate.is_relative_to(root) or not candidate.is_file(): return None digest = hashlib.sha256(candidate.read_bytes()).hexdigest()[:_HASH_PREFIX_LENGTH] return f"{Path(relative_path).as_posix()}@{digest}" def file_keys(project_dir: Path, relative_paths: list[str]) -> list[str]: keys = [file_key(project_dir, path) for path in sorted(set(relative_paths))] return [key for key in keys if key is not None] def entry_is_current(entry: LedgerEntry, project_dir: Path) -> bool: """An entry is current only if every depends-on file still hashes identically.""" for key in entry.depends_on: path, _, _digest = key.rpartition("@") if file_key(project_dir, path) != key: return False return True def prune_stale( ledger: CampaignLedger, project_dir: Path ) -> tuple[CampaignLedger, list[LedgerEntry]]: """Return a view of the ledger with stale entries removed, plus the entries stripped.""" stripped: list[LedgerEntry] = [] live_scars = [] live_findings = [] for entry in ledger.scars: (live_scars if entry_is_current(entry, project_dir) else stripped).append(entry) for entry in ledger.findings: (live_findings if entry_is_current(entry, project_dir) else stripped).append(entry) return ( CampaignLedger( name=ledger.name, scars=live_scars, findings=live_findings, click_hashes=list(ledger.click_hashes), ), stripped, ) def working_tree_hash(project_dir: Path) -> str: """Content hash of the working tree (paths + bytes), independent of git metadata.""" root = Path(project_dir).resolve() digest = hashlib.sha256() for path in sorted(root.rglob("*")): if not path.is_file(): continue relative = path.relative_to(root) if any(part in _SKIP_DIRS or part.endswith(".pyc") for part in relative.parts): continue digest.update(relative.as_posix().encode("utf-8")) digest.update(b"\0") digest.update(hashlib.sha256(path.read_bytes()).digest()) return digest.hexdigest() class LedgerStore: """Atomic JSON persistence for one ledger per campaign (or per standalone plan).""" def __init__(self, projects_dir: Path): self.root = Path(projects_dir) / "ledgers" def path_for(self, name: str) -> Path: return self.root / f"{name}.json" def load(self, name: str) -> CampaignLedger: path = self.path_for(name) if not path.is_file(): return CampaignLedger(name=name) return CampaignLedger.model_validate_json(path.read_text(encoding="utf-8")) def save(self, ledger: CampaignLedger) -> Path: path = self.path_for(ledger.name) path.parent.mkdir(parents=True, exist_ok=True) fsutil.atomic_write_text(path, ledger.model_dump_json(indent=2)) return path def add_scar(self, name: str, entry: LedgerEntry) -> CampaignLedger: ledger = self.load(name) if ledger.scar_budget_exhausted(): raise LedgerBudgetExceeded( f"Ledger '{name}' already holds {MAX_SCARS} scars; escalate instead of appending." ) ledger.scars.append(entry) self.save(ledger) return ledger def add_finding(self, name: str, entry: LedgerEntry) -> CampaignLedger: ledger = self.load(name) ledger.findings.append(entry) self.save(ledger) return ledger def record_click(self, name: str, tree_hash: str) -> tuple[CampaignLedger, bool]: """Append one ratchet click. Returns (ledger, cycling). A hash equal to the immediately preceding click is a no-op click, not a cycle; a hash equal to any older click means the campaign has returned to a prior state and is cycling. """ ledger = self.load(name) if ledger.click_hashes and ledger.click_hashes[-1] == tree_hash: return ledger, False cycling = tree_hash in ledger.click_hashes ledger.click_hashes.append(tree_hash) self.save(ledger) return ledger, cycling