"""Ledger, altitude ladder, hypothesis gate, research contract, click-hash loop detection.""" from __future__ import annotations import json import sys from datetime import UTC, datetime, timedelta from pathlib import Path from typing import ClassVar import pytest from git import Repo from afk_developer.backends.fake import FakeReasonerBackend from afk_developer.campaign import ( CampaignState, apply_campaign_policy, apply_stall_decision, plan_phase_roadmap, ) from afk_developer.campaign_models import CampaignLimits, StallDecision from afk_developer.campaign_supervision import build_foreman_children from afk_developer.config import Config, RoleRoute from afk_developer.grillme.spec_model import DetectedContext, TaskIntent, TaskSpec from afk_developer.ledger import ( MAX_SCARS, CampaignLedger, LedgerBudgetExceeded, LedgerEntry, LedgerStore, file_key, prune_stale, working_tree_hash, ) from afk_developer.planner import decomposer from afk_developer.planner.plan_verifier import preflight_plan from afk_developer.planner.task_model import ( AttemptUsage, ForemanDecompositionProposal, ForemanSubtaskProposal, TaskFailureKind, TaskNode, TaskPlan, TaskStatus, ) from afk_developer.scheduler import ledger_judge, queue from afk_developer.scheduler.recovery_coordinator import ( degenerate_altitude_rungs, escalate_altitude, next_altitude, ) from afk_developer.scheduler.reviewer import ReviewResult from afk_developer.scheduler.task_context import assemble_task_context class _Cortex: def __init__(self) -> None: self.fading_keys: list[str] = [] def read_permanent(self, _key: str): return None def write_fading(self, **kwargs) -> None: self.fading_keys.append(kwargs.get("key", "")) class _Registry: """Routes the judge (foreman) and the cheap checker to canned JSON answers.""" foreman_responses: ClassVar[list[str]] = [] checker_responses: ClassVar[list[str]] = [] foreman_requests: ClassVar[list[tuple[str, str]]] = [] checker_requests: ClassVar[list[tuple[str, str]]] = [] def __init__(self, _config) -> None: pass def get_foreman(self) -> FakeReasonerBackend: backend = FakeReasonerBackend(list(_Registry.foreman_responses)) backend.requests = _Registry.foreman_requests return backend def get_ledger_checker(self) -> FakeReasonerBackend: backend = FakeReasonerBackend(list(_Registry.checker_responses)) backend.requests = _Registry.checker_requests return backend @pytest.fixture def registry(monkeypatch): _Registry.foreman_responses = [] _Registry.checker_responses = [] _Registry.foreman_requests = [] _Registry.checker_requests = [] monkeypatch.setattr(ledger_judge, "BackendRegistry", _Registry) return _Registry def _state(tmp_path: Path) -> Path: # A sibling of tmp_path, never inside it: several tests use tmp_path as the target repo. state = tmp_path.parent / f"{tmp_path.name}-afk-state" state.mkdir(exist_ok=True) return state def _scar(**overrides) -> LedgerEntry: values = { "kind": "scar", "hypothesis": "Mocking the clock fixes the flaky test", "tried": "patched time.time in conftest", "observed": "tests still fail: the flake is in the socket timeout", } values.update(overrides) return LedgerEntry(**values) # --- Phase 2.1: ledger + staleness -------------------------------------------------- def test_ledger_store_roundtrip_and_one_line_shape(tmp_path: Path) -> None: store = LedgerStore(_state(tmp_path)) entry = _scar(depends_on=["src/a.py@0123456789ab"]) store.add_scar("camp", entry) store.add_finding("camp", LedgerEntry(kind="finding", hypothesis="h", observed="o")) loaded = store.load("camp") assert [item.id for item in loaded.scars] == [entry.id] assert len(loaded.findings) == 1 line = loaded.scars[0].one_line() assert line.startswith(f"[scar:{entry.id}] hypothesis: ") assert "tried: patched time.time" in line assert "depends-on: src/a.py@0123456789ab" in line assert "\n" not in line def test_prune_stale_strips_only_entries_whose_files_changed(tmp_path: Path) -> None: project = tmp_path / "proj" project.mkdir() (project / "a.py").write_text("a = 1\n", encoding="utf-8") (project / "b.py").write_text("b = 1\n", encoding="utf-8") keyed_a = _scar(depends_on=[file_key(project, "a.py")]) keyed_b = LedgerEntry( kind="finding", hypothesis="b", observed="b is 1", depends_on=[file_key(project, "b.py")] ) unkeyed = _scar(hypothesis="unkeyed scar") ledger = CampaignLedger(name="camp", scars=[keyed_a, unkeyed], findings=[keyed_b]) (project / "a.py").write_text("a = 2\n", encoding="utf-8") live, stripped = prune_stale(ledger, project) assert [item.id for item in stripped] == [keyed_a.id] assert [item.id for item in live.scars] == [unkeyed.id] assert [item.id for item in live.findings] == [keyed_b.id] def test_task_context_injects_only_current_ledger_entries_and_places_them_last( tmp_path: Path, ) -> None: project = tmp_path / "proj" project.mkdir() (project / "a.py").write_text("a = 1\n", encoding="utf-8") config = Config(projects_dir=_state(tmp_path)) store = LedgerStore(config.projects_dir) stale = _scar(hypothesis="STALE-SCAR", depends_on=[file_key(project, "a.py")]) live = _scar(hypothesis="LIVE-SCAR") store.add_scar("example", stale) store.add_scar("example", live) (project / "a.py").write_text("a = 2\n", encoding="utf-8") class Cortex: def read_permanent(self, key: str): if key == "project-context": return type("M", (), {"content": "STATIC PREFIX"})() return None task = TaskNode(id="t", title="T", description="d", hypothesis="try something new") plan = TaskPlan(project_name="example", goal="g", intent="implement", tasks=[task]) context = assemble_task_context( task=task, plan=plan, config=config, cortex=Cortex(), project_dir=project ) assert "LIVE-SCAR" in context.content assert "STALE-SCAR" not in context.content assert context.stripped_ledger_entry_ids == [stale.id] assert context.source_ids[-1] == "ledger:example" assert context.content.index("STATIC PREFIX") < context.content.index("Campaign Ledger") without_tree = assemble_task_context(task=task, plan=plan, config=config, cortex=Cortex()) assert "Campaign Ledger" not in without_tree.content def test_scar_budget_signals_escalation_instead_of_appending(tmp_path: Path) -> None: store = LedgerStore(_state(tmp_path)) for index in range(MAX_SCARS): store.add_scar("camp", _scar(hypothesis=f"scar {index}")) with pytest.raises(LedgerBudgetExceeded): store.add_scar("camp", _scar(hypothesis="one too many")) assert len(store.load("camp").scars) == MAX_SCARS def test_campaign_policy_shares_one_ledger_across_phase_plans(tmp_path: Path) -> None: campaign = CampaignState(name="camp", project_dir=tmp_path, root_goal="goal") plan = TaskPlan( project_name="camp-phase-002", goal="g", intent="implement", tasks=[TaskNode(id="t", title="T", description="d")], ) apply_campaign_policy(plan, campaign) assert plan.effective_ledger_name == "camp" assert ( TaskPlan(project_name="solo", goal="g", intent="implement", tasks=[]).effective_ledger_name == "solo" ) # --- Phase 2.2: scars are written above the worker ---------------------------------- def test_scar_is_written_by_the_judging_altitude_not_the_worker(tmp_path: Path, registry) -> None: project = tmp_path / "proj" project.mkdir() (project / "mod.py").write_text("x = 1\n", encoding="utf-8") config = Config(projects_dir=_state(tmp_path)) task = TaskNode(id="t", title="Implement mod", description="d", hypothesis="x should be 1") plan = TaskPlan(project_name="example", goal="g", intent="implement", tasks=[task]) task.start_attempt( role="coder", endpoint="e", model="m", reasoning_effort="", selection_reason="s", usage_before=task.attempts[-1].usage_before if task.attempts else __import__( "afk_developer.planner.task_model", fromlist=["AttemptUsage"] ).AttemptUsage(), ) task.finish_latest_attempt( outcome_status=TaskStatus.FAILED, failure_kind=TaskFailureKind.TESTS_FAILED, outcome_summary="WORKER-SELF-DIAGNOSIS: I think the import is wrong", usage_after=task.attempts[-1].usage_before, ) task.failure_kind = TaskFailureKind.TESTS_FAILED task.failure_detail = "RAW-TRACEBACK line 1\nAssertionError: expected 2" registry.foreman_responses = [ json.dumps( { "hypothesis": "x=1 satisfies the contract", "tried": "set x to 1", "observed": "contract requires 2", "depends_on_paths": ["mod.py"], } ) ] scar = ledger_judge.write_scar_on_trip( task=task, plan=plan, config=config, project_dir=project, review_files=["mod.py"] ) assert scar is not None and scar.author_role == "foreman" assert scar.observed == "contract requires 2" assert scar.depends_on == [file_key(project, "mod.py")] # The raw log went UP into the judge's prompt and never DOWN into the ledger. assert "RAW-TRACEBACK" in registry.foreman_requests[0][1] assert "WORKER-SELF-DIAGNOSIS" in registry.foreman_requests[0][1] assert "RAW-TRACEBACK" not in scar.one_line() assert "WORKER-SELF-DIAGNOSIS" not in scar.one_line() assert LedgerStore(config.projects_dir).load("example").scars[0].id == scar.id def test_scar_falls_back_to_a_category_only_entry_when_the_judge_is_unavailable( tmp_path: Path, ) -> None: project = tmp_path / "proj" project.mkdir() config = Config(projects_dir=_state(tmp_path)) # no endpoints configured -> judge raises task = TaskNode(id="t", title="Do it", description="d") plan = TaskPlan(project_name="example", goal="g", intent="implement", tasks=[task]) task.failure_kind = TaskFailureKind.LINT_FAILED task.failure_detail = "E501 line too long RAW" scar = ledger_judge.write_scar_on_trip( task=task, plan=plan, config=config, project_dir=project, review_files=[] ) assert scar is not None and scar.author_role == "tooling" assert scar.observed == "lint_failed" assert "RAW" not in scar.one_line() def test_worker_summary_is_never_written_to_shared_memory(tmp_path: Path, monkeypatch) -> None: class Worker: def __init__(self, *_a, **_k) -> None: pass def set_task_context(self, _c: str) -> None: pass def execute_task(self, _task): return TaskStatus.PASSED, "my own post-mortem", [] cortex = _Cortex() monkeypatch.setattr(queue, "Worker", Worker) monkeypatch.setattr(queue, "review_task", lambda *_a, **_k: ReviewResult(True, True, True)) plan = TaskPlan( project_name="example", goal="g", intent="implement", tasks=[TaskNode(id="t", title="T", description="d", read_only=True)], ) assert queue.execute_plan(plan, Config(), cortex, tmp_path, "", "") assert not any(key.startswith("task-result-") for key in cortex.fading_keys) # --- Phase 2.6 + 2.2 at the queue level: breaker goes up and writes a scar ---------- def test_next_altitude_ladder_ends_at_a_human() -> None: assert next_altitude("coder_light", read_only=False) == "coder" assert next_altitude("coder", read_only=False) == "reasoner" assert next_altitude("reasoner", read_only=False) is None assert next_altitude("researcher", read_only=True) == "reasoner" assert next_altitude("reasoner", read_only=True) is None task = TaskNode(id="t", title="T", description="d") assert escalate_altitude(task) == "reasoner" assert escalate_altitude(task) is None light = TaskNode(id="l", title="L", description="d") assert ( escalate_altitude(light, Config(coder_light=RoleRoute(endpoint="e", model="cheap"))) == "coder" ) def test_failed_task_retries_one_altitude_up_then_trips_the_breaker_with_a_scar( tmp_path: Path, monkeypatch ) -> None: routes_seen: list[str] = [] class Worker: def __init__(self, config, *_a, **_k) -> None: self.config = config def set_task_context(self, _c: str) -> None: pass def execute_task(self, _task): routes_seen.append(self.config.route_for("coder").model) return TaskStatus.FAILED, f"did not work at {routes_seen[-1]}", [] config = Config( projects_dir=_state(tmp_path), coder=RoleRoute(endpoint="e", model="mid"), reasoner=RoleRoute(endpoint="e", model="top"), ) monkeypatch.setattr(queue, "Worker", Worker) monkeypatch.setattr(queue, "review_task", lambda *_a, **_k: ReviewResult(True, True, True)) task = TaskNode(id="t", title="T", description="d", hypothesis="h") plan = TaskPlan(project_name="example", goal="g", intent="implement", tasks=[task]) assert not queue.execute_plan(plan, config, _Cortex(), tmp_path, "", "") assert routes_seen == ["mid", "top"] assert [attempt.model for attempt in task.attempts] == ["mid", "top"] assert task.status is TaskStatus.ESCALATED assert task.failure_kind is TaskFailureKind.ALTITUDE_EXHAUSTED scars = LedgerStore(config.projects_dir).load("example").scars assert len(scars) == 1 and scars[0].task_id == "t" def test_read_only_failure_climbs_then_escalates(tmp_path: Path, monkeypatch) -> None: class Worker: def __init__(self, *_a, **_k) -> None: pass def set_task_context(self, _c: str) -> None: pass def execute_task(self, _task): return TaskStatus.FAILED, "could not find it", [] monkeypatch.setattr(queue, "Worker", Worker) task = TaskNode(id="audit", title="Audit", description="d", read_only=True, max_retries=5) plan = TaskPlan(project_name="example", goal="g", intent="implement", tasks=[task]) config = Config(projects_dir=_state(tmp_path)) queue.execute_plan(plan, config, _Cortex(), tmp_path, "", "") assert task.status is TaskStatus.FAILED and task.altitude == "reasoner" queue.execute_plan(plan, config, _Cortex(), tmp_path, "", "") assert task.status is TaskStatus.ESCALATED assert task.failure_kind is TaskFailureKind.ALTITUDE_EXHAUSTED assert task.retry_count == 2 def test_stall_retry_goes_up_an_altitude_and_refuses_when_exhausted() -> None: task = TaskNode( id="t", title="T", description="d", status=TaskStatus.FAILED, terra_stall_retries_remaining=5, ) plan = TaskPlan(project_name="p", goal="g", intent="implement", tasks=[task]) assert apply_stall_decision(plan, StallDecision(decision="retry_task", task_id="t", note="n")) assert task.altitude == "reasoner" task.status = TaskStatus.FAILED assert not apply_stall_decision(plan, StallDecision(decision="retry_task", task_id="t")) # --- Phase 2.3: hypothesis declaration ----------------------------------------------- def test_scarred_hypothesis_returns_the_plan_up_without_dispatching( tmp_path: Path, monkeypatch, registry ) -> None: dispatched: list[str] = [] class Worker: def __init__(self, *_a, **_k) -> None: pass def set_task_context(self, _c: str) -> None: pass def execute_task(self, task): dispatched.append(task.id) return TaskStatus.PASSED, "ok", [] config = Config(projects_dir=_state(tmp_path)) store = LedgerStore(config.projects_dir) scar = store.add_scar("example", _scar()).scars[0] registry.checker_responses = [json.dumps({"already_scarred": True, "entry": scar.id})] monkeypatch.setattr(queue, "Worker", Worker) monkeypatch.setattr(queue, "review_task", lambda *_a, **_k: ReviewResult(True, True, True)) task = TaskNode( id="t", title="T", description="d", hypothesis="Mock the clock to stop the flake" ) plan = TaskPlan(project_name="example", goal="g", intent="implement", tasks=[task]) assert not queue.execute_plan(plan, config, _Cortex(), tmp_path, "", "") assert dispatched == [] assert task.status is TaskStatus.ESCALATED assert task.failure_kind is TaskFailureKind.HYPOTHESIS_ALREADY_SCARRED assert scar.id in task.failure_detail assert "Mock the clock" in registry.checker_requests[0][1] def test_missing_hypothesis_blocks_only_when_the_plan_declares_hypotheses( tmp_path: Path, monkeypatch, registry ) -> None: class Worker: def __init__(self, *_a, **_k) -> None: pass def set_task_context(self, _c: str) -> None: pass def execute_task(self, _task): return TaskStatus.PASSED, "ok", [] config = Config(projects_dir=_state(tmp_path)) LedgerStore(config.projects_dir).add_scar("example", _scar()) monkeypatch.setattr(queue, "Worker", Worker) monkeypatch.setattr(queue, "review_task", lambda *_a, **_k: ReviewResult(True, True, True)) legacy = TaskPlan( project_name="example", goal="g", intent="implement", tasks=[TaskNode(id="old", title="Old", description="d", read_only=True)], ) assert queue.execute_plan(legacy, config, _Cortex(), tmp_path, "", "") registry.checker_responses = [json.dumps({"already_scarred": False})] mixed = TaskPlan( project_name="example", goal="g", intent="implement", tasks=[ TaskNode( id="declared", title="D", description="d", read_only=True, hypothesis="new idea" ), TaskNode(id="undeclared", title="U", description="d", read_only=True), ], ) assert not queue.execute_plan(mixed, config, _Cortex(), tmp_path, "", "") by_id = {t.id: t for t in mixed.tasks} assert by_id["declared"].status is TaskStatus.PASSED assert by_id["undeclared"].status is TaskStatus.ESCALATED assert by_id["undeclared"].failure_kind is TaskFailureKind.HYPOTHESIS_MISSING def test_decomposer_records_the_planner_hypothesis(monkeypatch, tmp_path: Path) -> None: backend = FakeReasonerBackend( [ ( '{"tasks":[{"id":"a","title":"A","description":"d","dependencies":[],' '"hypothesis":"Adding the index makes the query fast"}]}' ) ] ) class FakeRegistry: def __init__(self, _config) -> None: pass def get_reasoner(self) -> FakeReasonerBackend: return backend monkeypatch.setattr(decomposer, "BackendRegistry", FakeRegistry) spec = TaskSpec( project_name="p", project_dir=tmp_path, goal="g", intent=TaskIntent.IMPLEMENT, auto_detected=DetectedContext(existing_files_count=1), ) plan = decomposer.decompose_task(spec, Config()) assert plan.tasks[0].hypothesis == "Adding the index makes the query fast" assert "hypothesis in exactly one sentence" in backend.requests[0][0] # --- Phase 2.4: research as contract -------------------------------------------------- def test_research_contract_already_answered_by_a_finding_does_not_dispatch( tmp_path: Path, monkeypatch, registry ) -> None: dispatched: list[str] = [] class Worker: def __init__(self, *_a, **_k) -> None: pass def set_task_context(self, _c: str) -> None: pass def execute_task(self, task): dispatched.append(task.id) return TaskStatus.PASSED, "ok", [] config = Config(projects_dir=_state(tmp_path)) finding = LedgerEntry( kind="finding", hypothesis="config lives in settings.py", observed="settings.py:Settings" ) LedgerStore(config.projects_dir).add_finding("example", finding) registry.checker_responses = [json.dumps({"answered": True, "entry": finding.id})] monkeypatch.setattr(queue, "Worker", Worker) task = TaskNode( id="find-config", title="Find config", description="d", read_only=True, hypothesis="Where does config live?", ) plan = TaskPlan(project_name="example", goal="g", intent="implement", tasks=[task]) assert queue.execute_plan(plan, config, _Cortex(), tmp_path, "", "") assert dispatched == [] assert task.status is TaskStatus.PASSED assert task.attempts == [] def test_passing_research_task_yields_a_finding_keyed_to_its_files( tmp_path: Path, monkeypatch, registry ) -> None: (tmp_path / "settings.py").write_text("class Settings: ...\n", encoding="utf-8") class Worker: def __init__(self, *_a, **_k) -> None: pass def set_task_context(self, _c: str) -> None: pass def execute_task(self, _task): return TaskStatus.PASSED, "Config is in settings.py Settings class", [] config = Config(projects_dir=_state(tmp_path)) registry.foreman_responses = [ json.dumps( { "hypothesis": "config lives in settings.py", "observed": "Settings in settings.py", "depends_on_paths": ["settings.py"], } ) ] monkeypatch.setattr(queue, "Worker", Worker) monkeypatch.setattr(queue, "review_task", lambda *_a, **_k: ReviewResult(True, True, True)) task = TaskNode( id="find-config", title="Find config", description="d", read_only=True, hypothesis="Where does config live?", ) plan = TaskPlan(project_name="example", goal="g", intent="implement", tasks=[task]) assert queue.execute_plan(plan, config, _Cortex(), tmp_path, "", "") findings = LedgerStore(config.projects_dir).load("example").findings assert len(findings) == 1 assert findings[0].author_role == "foreman" assert findings[0].depends_on == [file_key(tmp_path, "settings.py")] # --- Phase 2.5: click hashing --------------------------------------------------------- def test_record_click_flags_a_return_to_an_earlier_state_but_not_a_noop(tmp_path: Path) -> None: store = LedgerStore(_state(tmp_path)) assert store.record_click("camp", "A")[1] is False assert store.record_click("camp", "B")[1] is False assert store.record_click("camp", "B")[1] is False # no-op click assert store.record_click("camp", "A")[1] is True # cycle assert store.load("camp").click_hashes == ["A", "B", "A"] def test_working_tree_hash_ignores_caches_and_tracks_content(tmp_path: Path) -> None: (tmp_path / "a.py").write_text("1\n", encoding="utf-8") first = working_tree_hash(tmp_path) (tmp_path / "__pycache__").mkdir() (tmp_path / "__pycache__" / "a.pyc").write_bytes(b"x") assert working_tree_hash(tmp_path) == first (tmp_path / "a.py").write_text("2\n", encoding="utf-8") assert working_tree_hash(tmp_path) != first def test_campaign_cycling_trips_the_breaker_after_a_click(tmp_path: Path, monkeypatch) -> None: repo = Repo.init(tmp_path, initial_branch="main") with repo.config_writer() as writer: writer.set_value("user", "name", "AFK Test") writer.set_value("user", "email", "afk-test@example.invalid") (tmp_path / "base.txt").write_text("base\n", encoding="utf-8") repo.index.add(["base.txt"]) repo.index.commit("base") class Worker: def __init__(self, *_a, **_k) -> None: pass def set_task_context(self, _c: str) -> None: pass def execute_task(self, task): if task.id == "add": (tmp_path / "f.txt").write_text("v\n", encoding="utf-8") else: (tmp_path / "f.txt").unlink() return TaskStatus.PASSED, "ok", ["f.txt"] monkeypatch.setattr(queue, "Worker", Worker) monkeypatch.setattr(queue, "review_task", lambda *_a, **_k: ReviewResult(True, True, True)) config = Config(projects_dir=_state(tmp_path)) store = LedgerStore(config.projects_dir) store.record_click("example", repo.head.commit.tree.hexsha) # the baseline click plan = TaskPlan( project_name="example", goal="g", intent="implement", tasks=[ TaskNode(id="add", title="Add", description="d"), TaskNode(id="remove", title="Remove", description="d", dependencies=["add"]), ], ) queue.execute_plan(plan, config, _Cortex(), tmp_path, "", "") by_id = {t.id: t for t in plan.tasks} assert by_id["add"].status is TaskStatus.PASSED assert by_id["remove"].status is TaskStatus.ESCALATED assert by_id["remove"].failure_kind is TaskFailureKind.CAMPAIGN_CYCLE_DETECTED assert len(store.load("example").click_hashes) == 3 # --- Contradiction 1: dispatch requires an executable contract ------------------------- class _PassingWorker: def __init__(self, *_a, **_k) -> None: pass def set_task_context(self, _c: str) -> None: pass def execute_task(self, _task): return TaskStatus.PASSED, "ok", [] def test_has_executable_contract_accepts_only_runnable_tests() -> None: assert not TaskNode( id="t", title="T", description="d", acceptance_criteria=["prose"] ).has_executable_contract() assert TaskNode( id="t", title="T", description="d", contract_command="pytest -q" ).has_executable_contract() assert TaskNode( id="t", title="T", description="d", red_regression_test_files=["tests/test_x.py"] ).has_executable_contract() assert not TaskNode( id="r", title="R", description="d", read_only=True ).has_executable_contract() assert TaskNode( id="r", title="R", description="d", read_only=True, hypothesis="q" ).has_executable_contract() def test_preflight_refuses_contractless_tasks_when_the_campaign_requires_them() -> None: plan = TaskPlan( project_name="p", goal="g", intent="implement", tasks=[TaskNode(id="t", title="T", description="d", acceptance_criteria=["prose"])], ) assert preflight_plan(plan).passed refused = preflight_plan(plan, require_executable_contracts=True) assert not refused.passed assert "no executable acceptance test" in refused.failures[0] plan.require_executable_contracts = True assert not preflight_plan(plan).passed def test_contractless_task_is_returned_upward_instead_of_dispatched( tmp_path: Path, monkeypatch ) -> None: dispatched: list[str] = [] class Worker(_PassingWorker): def execute_task(self, task): dispatched.append(task.id) return TaskStatus.PASSED, "ok", [] monkeypatch.setattr(queue, "Worker", Worker) monkeypatch.setattr(queue, "review_task", lambda *_a, **_k: ReviewResult(True, True, True)) plan = TaskPlan( project_name="example", goal="g", intent="implement", tasks=[TaskNode(id="t", title="T", description="d", hypothesis="h")], require_executable_contracts=True, ) assert not queue.execute_plan( plan, Config(projects_dir=_state(tmp_path)), _Cortex(), tmp_path, "", "" ) assert dispatched == [] assert plan.tasks[0].status is TaskStatus.ESCALATED assert plan.tasks[0].failure_kind is TaskFailureKind.CONTRACT_MISSING def test_contract_command_runs_after_review_and_fails_the_task_on_nonzero_exit( tmp_path: Path, monkeypatch ) -> None: monkeypatch.setattr(queue, "Worker", _PassingWorker) monkeypatch.setattr(queue, "review_task", lambda *_a, **_k: ReviewResult(True, True, True)) failing = TaskNode( id="bad", title="Bad", description="d", contract_command=f'"{sys.executable}" -c "raise SystemExit(\'contract violated\')"', ) passing = TaskNode( id="good", title="Good", description="d", contract_command=f'"{sys.executable}" -c "pass"' ) plan = TaskPlan(project_name="example", goal="g", intent="implement", tasks=[failing, passing]) config = Config( projects_dir=_state(tmp_path), coder_light=RoleRoute(endpoint="e", model="cheap") ) queue.execute_plan(plan, config, _Cortex(), tmp_path, "", "") assert passing.status is TaskStatus.PASSED assert failing.status is not TaskStatus.PASSED # First attempt fails the contract; the escalated retry reproduces it exactly, so the # repeat detector trips the breaker. Both facts must be on the attempt record. assert failing.attempts[0].failure_kind is TaskFailureKind.CONTRACT_FAILED assert "contract violated" in failing.attempts[0].outcome_summary assert failing.status is TaskStatus.ESCALATED assert failing.failure_kind is TaskFailureKind.REPEATED_FAILURE def test_campaign_policy_stamps_contract_requirement_and_budgets(tmp_path: Path) -> None: campaign = CampaignState( name="camp", project_dir=tmp_path, root_goal="goal", limits=CampaignLimits(max_tokens_per_task=5_000, max_seconds_per_task=600), ) plan = TaskPlan( project_name="camp-phase-001", goal="g", intent="implement", tasks=[TaskNode(id="t", title="T", description="d")], ) apply_campaign_policy(plan, campaign) assert plan.require_executable_contracts is True assert plan.tasks[0].max_tokens == 5_000 assert plan.tasks[0].max_seconds == 600 # --- Contradiction 2: raw logs never reach the cheapest rung ---------------------------- def test_raw_review_output_is_withheld_at_the_cheapest_rung(tmp_path: Path) -> None: config = Config(projects_dir=_state(tmp_path)) task = TaskNode(id="t", title="T", description="d") task.failure_kind = TaskFailureKind.TESTS_FAILED task.failure_detail = "RAW pytest traceback line" plan = TaskPlan(project_name="example", goal="g", intent="implement", tasks=[task]) at_default = assemble_task_context(task=task, plan=plan, config=config, cortex=_Cortex()) assert "RAW pytest" not in at_default.content assert "raw output withheld" in at_default.content task.altitude = "reasoner" above = assemble_task_context(task=task, plan=plan, config=config, cortex=_Cortex()) assert "RAW pytest traceback line" in above.content # --- Contradiction 3: dependencies report tooling facts, not the worker's claim --------- def test_dependency_section_carries_files_and_finding_ids_not_the_self_report( tmp_path: Path, ) -> None: config = Config(projects_dir=_state(tmp_path)) dependency = TaskNode( id="research", title="Research", description="d", read_only=True, status=TaskStatus.PASSED, files_created=["notes.md"], ) dependency.start_attempt( role="researcher", endpoint="e", model="m", reasoning_effort="", selection_reason="s", usage_before=AttemptUsage(), ) dependency.finish_latest_attempt( outcome_status=TaskStatus.PASSED, failure_kind=None, outcome_summary="WORKER CLAIM: I believe config is in settings.py", usage_after=AttemptUsage(), ) finding = LedgerEntry( kind="finding", hypothesis="where config lives", observed="settings.py", task_id="research" ) LedgerStore(config.projects_dir).add_finding("example", finding) task = TaskNode(id="t", title="T", description="d", dependencies=["research"]) plan = TaskPlan(project_name="example", goal="g", intent="implement", tasks=[dependency, task]) context = assemble_task_context( task=task, plan=plan, config=config, cortex=_Cortex(), project_dir=tmp_path ) assert "WORKER CLAIM" not in context.content assert "- notes.md" in context.content assert f"see ledger entries {finding.id}" in context.content assert context.content.index("Completed Dependency") < context.content.index("Campaign Ledger") def test_every_passing_research_task_yields_a_finding_even_without_a_hypothesis( tmp_path: Path, monkeypatch, registry ) -> None: monkeypatch.setattr(queue, "Worker", _PassingWorker) monkeypatch.setattr(queue, "review_task", lambda *_a, **_k: ReviewResult(True, True, True)) registry.foreman_responses = [ json.dumps({"hypothesis": "h", "observed": "o", "depends_on_paths": []}) ] config = Config(projects_dir=_state(tmp_path)) plan = TaskPlan( project_name="example", goal="g", intent="implement", tasks=[ TaskNode(id="legacy-audit", title="Audit the baseline", description="d", read_only=True) ], ) assert queue.execute_plan(plan, config, _Cortex(), tmp_path, "", "") findings = LedgerStore(config.projects_dir).load("example").findings assert [entry.task_id for entry in findings] == ["legacy-audit"] assert "Audit the baseline" in registry.foreman_requests[0][1] # --- Contradiction 4: the campaign root is a contract ----------------------------------- def test_roadmap_planner_supplies_the_campaign_closure_metric(tmp_path: Path, monkeypatch) -> None: import afk_developer.campaign as campaign_module roadmap = { "closure_metric": {"name": "root", "command": "echo 0", "target": 0, "direction": "down"}, "phases": [ {"name": f"P{i}", "goal": "g", "task_ids": [f"t{i}"], "acceptance_criteria": ["c"]} for i in range(1, 4) ], } class Registry: requests: ClassVar[list[tuple[str, str]]] = [] def __init__(self, _c) -> None: pass def get_reasoner(self): backend = FakeReasonerBackend([json.dumps(roadmap)]) backend.requests = Registry.requests return backend monkeypatch.setattr(campaign_module, "BackendRegistry", Registry) campaign = CampaignState(name="camp", project_dir=tmp_path, root_goal="goal") phases = plan_phase_roadmap(campaign, config=Config()) assert len(phases) == 3 assert campaign.closure_metric is not None and campaign.closure_metric.name == "root" assert "campaign's own contract" in Registry.requests[0][0] # --- Contradiction 5: per-contract token and wall-clock budgets -------------------------- def _spent_attempt(task: TaskNode, *, tokens: int, seconds: int) -> None: task.start_attempt( role="coder", endpoint="e", model="m", reasoning_effort="", selection_reason="s", usage_before=AttemptUsage(), ) attempt = task.attempts[-1] attempt.started_at = datetime.now(UTC) - timedelta(seconds=seconds) task.finish_latest_attempt( outcome_status=TaskStatus.FAILED, failure_kind=TaskFailureKind.TESTS_FAILED, outcome_summary="failed", usage_after=AttemptUsage(total_tokens=tokens), ) def test_budget_exhausted_returns_the_task_upward_with_a_scar(tmp_path: Path, monkeypatch) -> None: dispatched: list[str] = [] class Worker(_PassingWorker): def execute_task(self, task): dispatched.append(task.id) return TaskStatus.PASSED, "ok", [] monkeypatch.setattr(queue, "Worker", Worker) monkeypatch.setattr(queue, "review_task", lambda *_a, **_k: ReviewResult(True, True, True)) config = Config(projects_dir=_state(tmp_path)) over_tokens = TaskNode( id="tokens", title="T", description="d", max_tokens=100, status=TaskStatus.FAILED ) _spent_attempt(over_tokens, tokens=150, seconds=1) over_time = TaskNode( id="time", title="T", description="d", max_seconds=60, status=TaskStatus.FAILED ) _spent_attempt(over_time, tokens=1, seconds=120) within = TaskNode( id="ok", title="T", description="d", max_tokens=100, max_seconds=60, status=TaskStatus.FAILED, ) _spent_attempt(within, tokens=10, seconds=5) plan = TaskPlan( project_name="example", goal="g", intent="implement", tasks=[over_tokens, over_time, within] ) queue.execute_plan(plan, config, _Cortex(), tmp_path, "", "") assert dispatched == ["ok"] assert over_tokens.status is TaskStatus.ESCALATED assert over_tokens.failure_kind is TaskFailureKind.BUDGET_EXHAUSTED assert "token budget" in over_tokens.failure_detail assert over_time.failure_kind is TaskFailureKind.BUDGET_EXHAUSTED assert within.status is TaskStatus.PASSED scars = LedgerStore(config.projects_dir).load("example").scars assert sorted(scar.task_id for scar in scars) == ["time", "tokens"] # --- Contradiction 6: decomposed children carry their own hypothesis and contract ------- def test_foreman_children_inherit_hypothesis_and_carry_their_own_contract() -> None: parent = TaskNode( id="p", title="Parent", description="d", hypothesis="parent idea", acceptance_criteria=["A", "B"], ) proposal = ForemanDecompositionProposal( parent_task_id="p", failure_fingerprint="f", subtasks=[ ForemanSubtaskProposal( id="p-sub-1", title="One", description="d", hypothesis="child idea", contract_command="pytest tests/test_one.py -q", covers=["criterion:A"], ), ForemanSubtaskProposal( id="p-sub-2", title="Two", description="d", covers=["criterion:B"] ), ], ) children = build_foreman_children(parent, proposal) assert children[0].hypothesis == "child idea" assert children[0].contract_command == "pytest tests/test_one.py -q" assert children[0].has_executable_contract() assert children[1].hypothesis == "parent idea" assert children[1].altitude == "" # children restart at the cheapest rung by design # --- Contradiction 7: an unverifiable hypothesis never dispatches ----------------------- def test_ledger_checker_outage_fails_closed(tmp_path: Path, monkeypatch, registry) -> None: dispatched: list[str] = [] class Worker(_PassingWorker): def execute_task(self, task): dispatched.append(task.id) return TaskStatus.PASSED, "ok", [] def boom(**_kwargs): raise RuntimeError("provider down") monkeypatch.setattr(queue, "check_hypothesis", boom) monkeypatch.setattr(queue, "Worker", Worker) config = Config(projects_dir=_state(tmp_path)) LedgerStore(config.projects_dir).add_scar("example", _scar()) task = TaskNode(id="t", title="T", description="d", read_only=True, hypothesis="new idea") plan = TaskPlan(project_name="example", goal="g", intent="implement", tasks=[task]) assert not queue.execute_plan(plan, config, _Cortex(), tmp_path, "", "") assert dispatched == [] assert task.status is TaskStatus.ESCALATED assert task.failure_kind is TaskFailureKind.PROVIDER_UNAVAILABLE assert task.attempts == [] # --- Contradiction 8: a degenerate ladder is detected ----------------------------------- def test_degenerate_altitude_rungs_are_detected_and_warned(tmp_path: Path, monkeypatch) -> None: same = RoleRoute(endpoint="e", model="one") assert degenerate_altitude_rungs(Config(coder=same, reasoner=same)) == ["coder->reasoner"] assert degenerate_altitude_rungs( Config(coder=same, reasoner=same, coder_light=same, researcher=same) ) == ["coder_light->coder", "coder->reasoner", "researcher->reasoner"] assert ( degenerate_altitude_rungs( Config( coder=RoleRoute(endpoint="e", model="mid"), reasoner=RoleRoute(endpoint="e", model="top"), ) ) == [] ) warnings: list[dict] = [] monkeypatch.setattr( queue, "emit", lambda kind, message, **extra: warnings.append({"kind": kind, **extra}) ) monkeypatch.setattr(queue, "Worker", _PassingWorker) monkeypatch.setattr(queue, "review_task", lambda *_a, **_k: ReviewResult(True, True, True)) plan = TaskPlan( project_name="example", goal="g", intent="implement", tasks=[TaskNode(id="t", title="T", description="d", read_only=True)], ) queue.execute_plan(plan, Config(coder=same, reasoner=same), _Cortex(), tmp_path, "", "") assert any(item.get("code") == "ALTITUDE_LADDER_DEGENERATE" for item in warnings)