"""Ledger judgments made at the altitude above the worker. Raw evidence (failure detail, review output, the worker's own summary) flows UP into these calls; only distilled one-line entries flow DOWN through the ledger. A worker never writes here. """ from __future__ import annotations import os import subprocess from dataclasses import dataclass from pathlib import Path from afk_developer.backends.registry import BackendRegistry from afk_developer.campaign_models import ClosureMetric from afk_developer.closure_metric import ClosureMetricError, resolve_metric_command from afk_developer.config import Config from afk_developer.ledger import ( CampaignLedger, LedgerBudgetExceeded, LedgerEntry, LedgerStore, file_keys, prune_stale, ) from afk_developer.planner.task_model import TaskNode, TaskPlan from afk_developer.utils import extract_json _LINE = 300 def _clip(value: object, limit: int = _LINE) -> str: return str(value or "").strip().replace("\n", " ")[:limit] def _paths(raw: object) -> list[str]: if not isinstance(raw, list): return [] return [str(item).strip() for item in raw if str(item).strip()][:20] def _live_ledger(plan: TaskPlan, config: Config, project_dir: Path) -> CampaignLedger: ledger = LedgerStore(config.projects_dir).load(plan.effective_ledger_name) live, _stripped = prune_stale(ledger, project_dir) return live def run_contract_command( command: str, project_dir: Path, *, target_python: Path | str | None = None, timeout: int = 300, ) -> tuple[bool, str]: """Run a task's executable acceptance test; (True, '') iff it exits 0. Deterministic and fail-closed like a closure metric: an unresolvable ``{python}``, a timeout, or a start failure is a failed contract, never a pass. """ probe = ClosureMetric(name="contract", command=command) try: resolved = resolve_metric_command(probe, project_dir, target_python=target_python) except ClosureMetricError as exc: return False, str(exc) environment = os.environ.copy() environment["PYTHONDONTWRITEBYTECODE"] = "1" try: result = subprocess.run( resolved, shell=True, cwd=str(project_dir), env=environment, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, check=False, ) except subprocess.TimeoutExpired: return False, f"contract command timed out after {timeout}s: {command}" except OSError as exc: return False, f"contract command could not start: {exc}" if result.returncode == 0: return True, "" detail = ((result.stderr or "") + (result.stdout or "")).strip()[-2_000:] return False, f"exit {result.returncode}: {detail or command}" def write_scar_on_trip( *, task: TaskNode, plan: TaskPlan, config: Config, project_dir: Path, review_files: list[str], judge_role: str = "foreman", ) -> LedgerEntry | None: """On a breaker trip, send the raw log up and let the judging altitude write the scar. Returns the scar written, or ``None`` when the scar budget is exhausted (the caller must escalate instead of appending). The judging model's failure is absorbed: tooling then writes a category-only scar so no raw text leaks down. """ store = LedgerStore(config.projects_dir) ledger_name = plan.effective_ledger_name if store.load(ledger_name).scar_budget_exhausted(): return None attempt = task.attempts[-1] if task.attempts else None evidence = ( f"TASK: {task.title}\n" f"HYPOTHESIS: {task.hypothesis or '(none declared)'}\n" f"ATTEMPTS: {len(task.attempts)}; ROLE: {attempt.role if attempt else 'unknown'}\n" f"FAILURE KIND: {task.failure_kind.value if task.failure_kind else 'unknown'}\n" f"RAW FAILURE DETAIL (deterministic tooling):\n{task.failure_detail[:4000]}\n\n" "WORKER SELF-REPORT (a claim, not evidence of cause):\n" f"{(attempt.outcome_summary if attempt else '')[:1000]}\n\n" f"FILES TOUCHED: {', '.join(review_files) or '(none)'}" ) hypothesis = _clip(task.hypothesis) or _clip(task.title) tried = _clip(f"{len(task.attempts)} attempt(s) via {attempt.role if attempt else 'unknown'}") observed = _clip(task.failure_kind.value if task.failure_kind else "failed") extra_paths: list[str] = [] try: response = ( BackendRegistry(config) .get_foreman() .complete( system_prompt=( "You judge one failed task from the evidence below and write ONE scar: a " "negative fact a later worker must not re-derive. Return ONLY JSON: " '{"hypothesis":"what the attempt assumed would work (one sentence)",' '"tried":"what was actually done (one sentence)",' '"observed":"what the tooling observed, not what the worker claimed (one sentence)",' '"depends_on_paths":["project-relative files this fact is true about"]}. ' "Never copy stack traces or log lines; distill." ), user_prompt=evidence, temperature=0.0, ) ) config.record_usage(response.usage, role=judge_role) raw = extract_json(response.content) hypothesis = _clip(raw.get("hypothesis")) or hypothesis tried = _clip(raw.get("tried")) or tried observed = _clip(raw.get("observed")) or observed extra_paths = _paths(raw.get("depends_on_paths")) except Exception: # noqa: BLE001 - a judge outage must still yield a category-only scar judge_role = "tooling" entry = LedgerEntry( kind="scar", hypothesis=hypothesis, tried=tried, observed=observed, depends_on=file_keys(project_dir, [*review_files, *extra_paths]), author_role=judge_role, task_id=task.id, ) try: store.add_scar(ledger_name, entry) except LedgerBudgetExceeded: return None return entry @dataclass(frozen=True) class HypothesisVerdict: """Whether a declared hypothesis is already refuted by a scar on the ledger.""" already_scarred: bool entry: LedgerEntry | None = None detail: str = "" def check_hypothesis( *, task: TaskNode, plan: TaskPlan, config: Config, project_dir: Path ) -> HypothesisVerdict: """Ask the cheapest model whether ``task.hypothesis`` is already on the scar list. This is a semantic yes/no read of the scar list, deliberately not a hash or embedding comparison. With no live scars there is nothing to collide with. """ live = _live_ledger(plan, config, project_dir) if not live.scars: return HypothesisVerdict(already_scarred=False) if not task.hypothesis.strip(): if not any(item.hypothesis.strip() for item in plan.tasks): # Legacy plan authored before hypotheses existed: nothing to compare, do not block. return HypothesisVerdict(already_scarred=False) return HypothesisVerdict( already_scarred=True, detail=( "Task declares no hypothesis, so it cannot be checked against " f"{len(live.scars)} live scar(s). Declare one sentence before dispatch." ), ) scar_text = "\n".join(f"- id={entry.id}: {entry.one_line()}" for entry in live.scars) response = ( BackendRegistry(config) .get_ledger_checker() .complete( system_prompt=( "You compare one hypothesis against a list of scars (already-refuted " "hypotheses). Answer whether the hypothesis is the same claim as, or a " "restatement of, any scar. Return ONLY JSON: " '{"already_scarred": true|false, "entry": ""}.' ), user_prompt=f"HYPOTHESIS:\n{task.hypothesis}\n\nSCARS:\n{scar_text}", temperature=0.0, ) ) config.record_usage(response.usage, role="coder_light") raw = extract_json(response.content) matched = bool(raw.get("already_scarred", False)) entry = live.find(str(raw.get("entry", "")).strip()) if matched else None if matched and entry is None: # The checker said yes but named no valid entry; treat as no match rather than block on noise. return HypothesisVerdict(already_scarred=False) if not matched: return HypothesisVerdict(already_scarred=False) return HypothesisVerdict( already_scarred=True, entry=entry, detail=f"Hypothesis is already refuted by scar {entry.id}: {entry.one_line()}", ) @dataclass(frozen=True) class ResearchVerdict: """Whether the findings ledger already answers a research contract.""" satisfied: bool entry: LedgerEntry | None = None detail: str = "" def research_contract_satisfied( *, task: TaskNode, plan: TaskPlan, config: Config, project_dir: Path ) -> ResearchVerdict: """A research task's acceptance test: does a live finding answer its question?""" if not task.read_only or not task.hypothesis.strip(): return ResearchVerdict(satisfied=False) live = _live_ledger(plan, config, project_dir) if not live.findings: return ResearchVerdict(satisfied=False) finding_text = "\n".join(f"- id={entry.id}: {entry.one_line()}" for entry in live.findings) response = ( BackendRegistry(config) .get_ledger_checker() .complete( system_prompt=( "You decide whether a research question is already answered by one of the " "findings listed. Only a finding that directly settles the question counts. " 'Return ONLY JSON: {"answered": true|false, "entry": ""}.' ), user_prompt=f"QUESTION / EXPECTED FINDING:\n{task.hypothesis}\n\nFINDINGS:\n{finding_text}", temperature=0.0, ) ) config.record_usage(response.usage, role="coder_light") raw = extract_json(response.content) entry = live.find(str(raw.get("entry", "")).strip()) if raw.get("answered") else None if entry is None: return ResearchVerdict(satisfied=False) return ResearchVerdict( satisfied=True, entry=entry, detail=f"Research contract already satisfied by finding {entry.id}: {entry.one_line()}", ) def write_finding_from_research( *, task: TaskNode, plan: TaskPlan, config: Config, project_dir: Path, worker_summary: str, judge_role: str = "foreman", ) -> LedgerEntry | None: """After a read-only task passes, the altitude above distills its result into a finding. The worker's summary is treated as a claim to be distilled, not copied. This is the ONLY channel by which a research result reaches later tasks, so it runs for every read-only task (the title stands in for an undeclared hypothesis). If the judge cannot name any existing file the fact depends on, the finding is still recorded but unkeyed (it then never expires mechanically). """ if not task.read_only: return None question = task.hypothesis.strip() or task.title.strip() candidate_paths = list(task.required_artifacts) if task.discovery_contract is not None: candidate_paths.extend(task.discovery_contract.input_paths) try: response = ( BackendRegistry(config) .get_foreman() .complete( system_prompt=( "A read-only research task passed its deterministic review. Write ONE " "finding: a positive fact a later worker may rely on. Return ONLY JSON: " '{"hypothesis":"the question as a claim (one sentence)",' '"observed":"the settled answer (one sentence)",' '"depends_on_paths":["project-relative files this fact is true about"]}. ' "Distill; do not copy the worker's text." ), user_prompt=( f"QUESTION / EXPECTED FINDING: {question}\n" f"WORKER SUMMARY (a claim): {worker_summary[:3000]}\n" f"DECLARED FILES: {', '.join(candidate_paths) or '(none)'}" ), temperature=0.0, ) ) config.record_usage(response.usage, role=judge_role) raw = extract_json(response.content) except Exception: # noqa: BLE001 - a judge outage must never fail a passed research task return None observed = _clip(raw.get("observed")) if not observed: return None entry = LedgerEntry( kind="finding", hypothesis=_clip(raw.get("hypothesis")) or _clip(question), observed=observed, depends_on=file_keys(project_dir, [*candidate_paths, *_paths(raw.get("depends_on_paths"))]), author_role=judge_role, task_id=task.id, ) LedgerStore(config.projects_dir).add_finding(plan.effective_ledger_name, entry) return entry