"""Assemble concise, source-attributed context for one AFK task attempt.""" from __future__ import annotations from dataclasses import dataclass, field from pathlib import Path from afk_developer.config import Config from afk_developer.cortex.db import CortexDB from afk_developer.evidence import EvidencePacketError, EvidencePacketStore from afk_developer.ledger import CampaignLedger, LedgerStore, prune_stale from afk_developer.planner.task_model import TaskFailureKind, TaskNode, TaskPlan from afk_developer.scheduler.discovery_checkpoint import ( DiscoveryCheckpointError, DiscoveryCheckpointStore, ) from afk_developer.scheduler.recovery_coordinator import current_altitude, default_altitude MAX_CONTEXT_CHARS = 24_000 _SELECTED_PERMANENT_KEYS = ( "project-context", "project-guidelines", "architecture", "conventions", "constraints", ) _REVIEW_FAILURES = { TaskFailureKind.TESTS_FAILED, TaskFailureKind.LINT_FAILED, TaskFailureKind.DIFF_CHECK_FAILED, TaskFailureKind.REVIEW_REJECTED, TaskFailureKind.CONTRACT_FAILED, } @dataclass(frozen=True) class TaskContext: """Bounded text and durable provenance for an external task attempt.""" content: str source_ids: list[str] character_count: int token_estimate: int stripped_ledger_entry_ids: list[str] = field(default_factory=list) def assemble_task_context( *, task: TaskNode, plan: TaskPlan, config: Config, cortex: CortexDB, max_characters: int = MAX_CONTEXT_CHARS, project_dir: Path | None = None, ) -> TaskContext: """Return relevant task context without injecting all permanent or fading memory. ``project_dir`` enables the campaign ledger section: entries are pruned against the working tree before injection. Without a tree to hash against, no ledger is injected at all -- a worker never sees an entry whose currency is unverified. """ if max_characters < 1: raise ValueError("max_characters must be at least one.") sections: list[str] = [] source_ids: list[str] = [] used = 0 def add(source_id: str, heading: str, body: str) -> None: nonlocal used if not body or used >= max_characters: return prefix = f"--- {heading} ---\n" remaining = max_characters - used - len(prefix) if remaining <= 0: return if len(body) > remaining: body = f"{body[: max(0, remaining - 1)]}…" section = f"{prefix}{body}" sections.append(section) source_ids.append(source_id) used += len(section) + 2 add( "task-contract", "Task Contract", ( f"ID: {task.id}\nTitle: {task.title}\nDescription: {task.description}\n" f"Acceptance profile: {task.acceptance_profile.value}\n" f"Read-only: {task.read_only}\n" "Required artifacts:\n" + "\n".join(f"- {path}" for path in task.required_artifacts) + ("\n" if task.required_artifacts else "- (none)\n") + "Acceptance criteria:\n" + "\n".join(f"- {criterion}" for criterion in task.acceptance_criteria) + ("" if task.acceptance_criteria else "- (none)") ), ) read_permanent = getattr(cortex, "read_permanent", None) if callable(read_permanent): phase_goal = read_permanent("phase-goal") if phase_goal: add("phase-goal", "Current Campaign Phase", phase_goal.content) phase_history = read_permanent("phase-history") if phase_history: add("phase-history", "Prior Phase Summaries", phase_history.content) for key in _SELECTED_PERMANENT_KEYS: memory = read_permanent(key) if memory: add(f"permanent:{key}", f"Project Memory: {key}", memory.content) task_by_id = {item.id: item for item in plan.tasks} live_ledger, stripped_ids = _load_live_ledger(plan, config, project_dir) for dependency_id in task.dependencies: dependency = task_by_id.get(dependency_id) if dependency is None: continue # Tooling-observed facts only. The dependency worker's own summary is a claim; the # settled version of it is the finding the judging altitude wrote to the ledger. files = "\n".join(f"- {path}" for path in dependency.files_created[:30]) or "- (none)" finding_ids = ( [entry.id for entry in live_ledger.findings if entry.task_id == dependency.id] if live_ledger is not None else [] ) add( f"dependency:{dependency.id}", f"Completed Dependency: {dependency.id}", ( f"Title: {dependency.title}\nStatus: {dependency.status.value}\n" f"Files delivered:\n{files}\n" "Findings: " + ( "see ledger entries " + ", ".join(finding_ids) if finding_ids else "(none recorded)" ) ), ) _add_evidence_summary(add, task, config) _add_discovery_checkpoint_summary(add, task, plan, config) if task.failure_kind in _REVIEW_FAILURES and task.failure_detail: if _at_cheapest_rung(task, config): # Logs go up, not down: the cheapest rung gets the category, never the raw output. add( "deterministic-review", "Previous Deterministic Review", f"{task.failure_kind.value}: raw output withheld at this altitude; the campaign " "ledger below holds the settled conclusion.", ) else: add( "deterministic-review", "Previous Deterministic Review", f"{task.failure_kind.value}: {task.failure_detail[:2000]}", ) if task.validator_findings: finding_lines = [] for finding in task.validator_findings[:20]: paths = ", ".join(str(path) for path in finding.get("affected_paths", [])[:20]) finding_lines.append( "- " f"{str(finding.get('summary', 'Validator finding'))[:500]}\n" f" expected: {str(finding.get('expected', ''))[:1000]}\n" f" actual: {str(finding.get('actual', ''))[:1000]}" + (f"\n affected paths: {paths}" if paths else "") ) add("validator-findings", "Independent Validator Findings", "\n".join(finding_lines)) if task.recovery_action.value != "none": add( "recovery-state", "Scheduled Recovery", ( f"Action: {task.recovery_action.value}\n" f"Semantic repairs remaining: {task.semantic_repairs_remaining}\n" f"Research supplements remaining: {task.research_supplements_remaining}\n" f"High-reasoning repairs remaining: {task.high_reasoning_repairs_remaining}" ), ) # Ledger goes last: after every static/cached section, immediately before the task prompt. if live_ledger is not None and (live_ledger.scars or live_ledger.findings): add(f"ledger:{live_ledger.name}", "Campaign Ledger", live_ledger.render()) content = "\n\n".join(sections) return TaskContext( content=content, source_ids=source_ids, character_count=len(content), token_estimate=(len(content) + 3) // 4, stripped_ledger_entry_ids=stripped_ids, ) def _at_cheapest_rung(task: TaskNode, config: Config) -> bool: return current_altitude(task, config) == default_altitude(task, config) def _load_live_ledger( plan: TaskPlan, config: Config, project_dir: Path | None ) -> tuple[CampaignLedger | None, list[str]]: """Load and prune the ledger; None when there is no tree to verify currency against.""" if project_dir is None: return None, [] ledger = LedgerStore(config.projects_dir).load(plan.effective_ledger_name) if not ledger.scars and not ledger.findings: return ledger, [] live, stripped = prune_stale(ledger, project_dir) return live, [entry.id for entry in stripped] def _add_evidence_summary(add, task: TaskNode, config: Config) -> None: if not task.evidence_packet_id or task.evidence_revision is None: return try: project_name, evidence_task_id, revision = task.evidence_packet_id.rsplit("/", 2) except ValueError: add("evidence:invalid-id", "Evidence Packet", "The saved evidence packet ID is invalid.") return if not project_name or not evidence_task_id or not revision.startswith("revision-"): add("evidence:invalid-id", "Evidence Packet", "The saved evidence packet ID is invalid.") return try: packet = EvidencePacketStore(config.projects_dir).load_packet( project_name=project_name, task_id=evidence_task_id, revision=task.evidence_revision, ) except EvidencePacketError as exc: add("evidence:unavailable", "Evidence Packet", f"Evidence packet unavailable: {exc}") return rules = "\n".join(f"- {rule.category}: {rule.statement}" for rule in packet.observed_rules[:20]) contracts = "\n".join( f"- {contract.output_path} <- source #{contract.source_index}" for contract in packet.raw_output_contracts[:20] ) add( f"evidence:{packet.packet_id}", "Verified Evidence Summary", ( f"Packet: {packet.packet_id} revision={packet.revision}\n" f"Fingerprint: {packet.fingerprint}\n" f"Supported forms: {', '.join(packet.support_boundary.supported_forms[:20])}\n" f"Exclusions: {', '.join(packet.support_boundary.exclusions[:20]) or '(none)'}\n" f"Observed rules:\n{rules or '(none)'}\n" f"Raw-output contracts:\n{contracts or '(none)'}" ), ) def _add_discovery_checkpoint_summary(add, task: TaskNode, plan: TaskPlan, config: Config) -> None: if not task.discovery_checkpoint_fingerprint: return try: checkpoint = DiscoveryCheckpointStore(config.projects_dir).load( plan.project_name, task.discovery_checkpoint_fingerprint, ) except DiscoveryCheckpointError as exc: add( "discovery:unavailable", "Verified Discovery Checkpoint", f"Discovery checkpoint unavailable: {exc}", ) return paths = "\n".join(f"- {path}" for path in checkpoint.canonical_paths[:30]) symbols = ", ".join(checkpoint.canonical_symbols[:30]) conclusions = "\n".join(f"- {item}" for item in checkpoint.conclusions[:30]) add( f"discovery:{checkpoint.fingerprint}", "Verified Discovery Checkpoint", ( f"Fingerprint: {checkpoint.fingerprint}\n" f"Cache key: {checkpoint.cache_key or '(task-local)'}\n" f"Canonical paths:\n{paths or '(none)'}\n" f"Canonical symbols: {symbols or '(none)'}\n" f"Conclusions:\n{conclusions}\n" f"Exclusions: {', '.join(checkpoint.exclusions) or '(none)'}\n" f"Allowed outputs: {', '.join(checkpoint.allowed_output_paths)}\n" f"Next action: {checkpoint.approved_next_action}\n" f"Summary: {checkpoint.summary}" ), )