from pathlib import Path from afk_developer import reporter from afk_developer.config import Config from afk_developer.evidence import EvidencePacketDraft, EvidencePacketStore, ResearcherMetadata from afk_developer.planner.task_model import ( AttemptUsage, TaskFailureKind, TaskNode, TaskPlan, TaskStatus, ) from afk_developer.recovery import RecoveryAction from afk_developer.scheduler import queue from afk_developer.scheduler.reviewer import ReviewResult from afk_developer.scheduler.task_context import assemble_task_context def test_queue_uses_bounded_task_context_and_records_its_provenance( tmp_path: Path, monkeypatch ) -> None: received_contexts: list[str] = [] class FakeCortex: def __init__(self) -> None: self.permanent = { "project-guidelines": "Use source-backed assertions only.", "last-plan": "STALE PLAN MUST NOT REACH THE WORKER", } def read_permanent(self, key: str): value = self.permanent.get(key) return type("Memory", (), {"content": value})() if value else None def get_context_for_worker(self) -> str: raise AssertionError("Queue must use bounded task context, not broad Cortex context.") def write_fading(self, **_kwargs) -> None: pass class CaptureWorker: def __init__(self, *_args, **_kwargs) -> None: self.context = "" def set_task_context(self, context: str) -> None: self.context = context def execute_task(self, _task): received_contexts.append(self.context) return TaskStatus.PASSED, "analysis complete", [] cortex = FakeCortex() dependency = TaskNode( id="foundation", title="Foundation", description="Already completed dependency.", status=TaskStatus.PASSED, ) task = TaskNode( id="audit", title="Audit output", description="Inspect the completed dependency without modifying files.", dependencies=["foundation"], read_only=True, ) plan = TaskPlan( project_name="example", goal="Bound worker context", intent="analyze", tasks=[dependency, task], ) monkeypatch.setattr(queue, "Worker", CaptureWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: ReviewResult(True, True, True), ) assert queue.execute_plan(plan, Config(), cortex, tmp_path, "ruff", "pytest") assert len(received_contexts) == 1 context = received_contexts[0] assert "Audit output" in context assert "Use source-backed assertions only." in context assert "Completed Dependency: foundation" in context assert "STALE PLAN" not in context attempt = task.attempts[0] assert attempt.context_source_ids == [ "task-contract", "permanent:project-guidelines", "dependency:foundation", ] assert attempt.context_characters == len(context) assert attempt.context_token_estimate == (len(context) + 3) // 4 def test_assemble_task_context_includes_phase_goal_and_history_when_present( tmp_path: Path, ) -> None: class FakeCortex: def __init__(self, permanent: dict[str, str]) -> None: self.permanent = permanent def read_permanent(self, key: str): value = self.permanent.get(key) return type("Memory", (), {"content": value})() if value else None cortex = FakeCortex( { "phase-goal": ( "Phase 2 of 3: Core\nBuild the core engine.\nAcceptance criteria:\n- Tests pass" ), "phase-history": "Phase 1 (Bootstrap): Bootstrap finished cleanly.", } ) task = TaskNode(id="engine", title="Build engine", description="Implement the core engine.") plan = TaskPlan(project_name="example", goal="Build it", intent="implement", tasks=[task]) context = assemble_task_context(task=task, plan=plan, config=Config(), cortex=cortex) assert "Current Campaign Phase" in context.content assert "Build the core engine." in context.content assert "Prior Phase Summaries" in context.content assert "Bootstrap finished cleanly." in context.content assert context.source_ids == ["task-contract", "phase-goal", "phase-history"] def test_assemble_task_context_omits_phase_sections_when_absent(tmp_path: Path) -> None: class FakeCortex: def read_permanent(self, _key: str): return None task = TaskNode(id="engine", title="Build engine", description="Implement the core engine.") plan = TaskPlan(project_name="example", goal="Build it", intent="implement", tasks=[task]) context = assemble_task_context(task=task, plan=plan, config=Config(), cortex=FakeCortex()) assert "phase-goal" not in context.source_ids assert "phase-history" not in context.source_ids def test_assemble_task_context_includes_executable_contract_details(tmp_path: Path) -> None: class FakeCortex: def read_permanent(self, _key: str): return None task = TaskNode( id="ignore-policy", title="Define ignore policy", description="Ignore only project-local generated artifacts.", required_artifacts=[".gitignore"], acceptance_criteria=[".gitignore ignores tests/6502_test_vectors/ and tests/dormann/."], ) plan = TaskPlan(project_name="example", goal="Build it", intent="implement", tasks=[task]) context = assemble_task_context(task=task, plan=plan, config=Config(), cortex=FakeCortex()) assert "Required artifacts:\n- .gitignore" in context.content assert "Acceptance criteria:" in context.content assert "tests/6502_test_vectors/ and tests/dormann/" in context.content def test_max_context_chars_was_raised_for_phased_campaigns() -> None: from afk_developer.scheduler.task_context import MAX_CONTEXT_CHARS assert MAX_CONTEXT_CHARS == 24_000 def test_results_report_includes_attempt_route_context_and_recovery_state(tmp_path: Path) -> None: task = TaskNode( id="corpus", title="Validate corpus output", description="Preserve the source-backed output.", status=TaskStatus.ESCALATED, failure_kind=TaskFailureKind.RECOVERY_TOOL_FAILED, failure_detail="Configured researcher adapter is unavailable.", evidence_packet_id="example/corpus/revision-1", evidence_revision=1, evidence_fingerprint="abc123def4567890", recovery_action=RecoveryAction.RESEARCH_SUPPLEMENT, research_supplements_used=1, research_supplements_remaining=0, ) task.start_attempt( role="researcher", endpoint="copilot", model="gpt-5.6-terra", reasoning_effort="high", selection_reason="validator_missing_evidence_supplement", usage_before=AttemptUsage(), context_source_ids=["recovery-state", "validator-missing-evidence"], context_characters=480, context_token_estimate=120, ) task.finish_latest_attempt( outcome_status=TaskStatus.ESCALATED, failure_kind=TaskFailureKind.RECOVERY_TOOL_FAILED, outcome_summary="Configured researcher adapter is unavailable.", usage_after=AttemptUsage(), ) plan = TaskPlan( project_name="example", goal="Validate evidence", intent="implement", tasks=[task] ) with reporter.console.capture() as capture: reporter.report_results(plan, tmp_path, Config()) output = capture.get() attempt_rows = reporter._attempt_report_rows(plan) execution_details = reporter._execution_details(task, "fallback") failure_details = reporter._failure_details(task, "fallback") assert "Attempt Routes and Bounded Context" in output assert attempt_rows == [ ( "corpus", "researcher", "copilot/gpt-5.6-terra (high)", "validator_missing_evidence_supplement", "escalated: recovery_tool_failed", "2 sources, ~120 tokens", ) ] assert "evidence r1: abc123def456" in execution_details assert "scheduled: research supplement" in execution_details assert "verification/recovery infrastructure" in failure_details def test_task_context_loads_an_inherited_discovery_packet(tmp_path: Path) -> None: corpus = tmp_path / "corpus" corpus.mkdir() (corpus / "source.txt").write_text("BEGIN output END", encoding="utf-8") store = EvidencePacketStore(tmp_path / "state") packet = store.create_packet( project_name="example", task_id="discover", approved_roots=[str(corpus)], draft=EvidencePacketDraft.model_validate( { "sources": [ { "root": str(corpus), "relative_path": "source.txt", "start_marker": "BEGIN", "end_marker": "END", } ], "facts": ["The exact output is source-backed."], "observed_rules": [ { "category": "raw-output", "statement": "Preserve the marked output exactly.", "source_indices": [0], } ], "support_boundary": {"supported_forms": ["marked output"], "exclusions": []}, } ), researcher=ResearcherMetadata(endpoint="copilot", model="gpt-5.6-terra"), ) implementation = TaskNode( id="implement", title="Implement output", description="Consume discovery evidence.", evidence_packet_id=packet.packet_id, evidence_revision=packet.revision, evidence_fingerprint=packet.fingerprint, ) plan = TaskPlan( project_name="example", goal="Use discovery evidence", intent="implement", tasks=[implementation], ) class EmptyCortex: def read_permanent(self, _key): return None context = assemble_task_context( task=implementation, plan=plan, config=Config(projects_dir=tmp_path / "state"), cortex=EmptyCortex(), ) assert "Verified Evidence Summary" in context.content assert "evidence:example/discover/revision-1" in context.source_ids def test_session_statistics_show_per_model_cache_reasoning_and_credits(monkeypatch) -> None: config = Config() stats = config.stats stats.api_calls = 3 stats.total_turns = 3 stats.copilot_prompts_submitted = 1 stats.copilot_usage_available = True stats.copilot_nano_aiu = 1_250_000_000 stats.model_usage["copilot:gpt-5.6-luna"] = { "model": "gpt-5.6-luna", "endpoint": "copilot", "prompt_tokens": 1_000, "completion_tokens": 200, "total_tokens": 1_200, "cache_read_tokens": 700, "cache_write_tokens": 50, "reasoning_tokens": 80, "api_calls": 3, "agent_turns": 3, "copilot_nano_aiu": 1_250_000_000, "telemetry_available": True, } wide_console = reporter.Console(width=240, force_terminal=False, color_system=None) monkeypatch.setattr(reporter, "console", wide_console) with wide_console.capture() as capture: reporter.report_session_stats(config) output = capture.get() assert "Model Usage" in output assert "Cache Read" in output assert "Cache Write" in output assert "Reasoning" in output assert "copilot" in output assert "1,000" in output assert "700" in output assert "50" in output assert "80" in output assert "1.2500" in output