import warnings import sys from pathlib import Path from types import SimpleNamespace from git import Repo from afk_developer import cli from afk_developer.backends.models import AcceptanceOutcome, AcceptanceValidationResult from afk_developer.campaign_models import CampaignBatch, CampaignState, CampaignStatus from afk_developer.campaign_store import CampaignStore from afk_developer.config import Config from afk_developer.planner.task_model import ( AcceptanceProfile, TaskFailureKind, TaskNode, TaskPlan, TaskStatus, ) from afk_developer.recovery import RecoveryMode, RecoverySettings from afk_developer.scheduler import manual_retry, queue, reviewer class _FakeCortex: def __init__(self) -> None: self.permanent_writes = 0 self.sessions = 0 def replace_permanent(self, *_args) -> None: self.permanent_writes += 1 def save_session(self, _stats) -> None: self.sessions += 1 def test_retry_session_summary_records_outcome_and_renders_stats( monkeypatch, tmp_path: Path ) -> None: saved_stats: list[dict] = [] reported: list[Config] = [] class FakeCortex: def write_fading(self, **_kwargs) -> None: pass def save_session(self, stats) -> None: saved_stats.append(stats) config = Config(projects_dir=tmp_path / "state") monkeypatch.setattr(cli, "report_session_stats", lambda actual: reported.append(actual)) cli._save_retry_session( FakeCortex(), config, TaskNode(id="done", title="Done", description="Complete", status=TaskStatus.PASSED), ) assert config.stats.tasks_completed == 1 assert config.stats.tasks_failed == 0 assert saved_stats[0]["tasks_completed"] == 1 assert reported == [config] def test_manual_retry_clears_resolved_campaign_escalation(tmp_path: Path) -> None: config = Config(projects_dir=tmp_path / "state") store = CampaignStore(config.projects_dir) campaign = CampaignState( name="campaign", project_dir=tmp_path, root_goal="Complete the campaign", status=CampaignStatus.ESCALATED, stop_reason="Manual retry required", batches=[ CampaignBatch( ordinal=1, plan_name="campaign-batch-001", goal="Complete the batch", task_count=1, ) ], ) store.save(campaign) plan = TaskPlan( project_name="campaign-batch-001", goal="Complete the batch", intent="implement", tasks=[ TaskNode( id="recovered", title="Recovered", description="Recovered by retry", status=TaskStatus.PASSED, ) ], ) messages: list[str] = [] manual_retry._clear_stale_campaign_escalation( config, plan, plan.project_name, SimpleNamespace(console=SimpleNamespace(print=messages.append)), ) saved = store.load(campaign.name) assert saved is not None assert saved.status is CampaignStatus.READY assert saved.stop_reason == "" assert "can resume" in messages[0] def test_manual_retry_keeps_campaign_escalated_while_another_task_is_escalated( tmp_path: Path, ) -> None: config = Config(projects_dir=tmp_path / "state") store = CampaignStore(config.projects_dir) campaign = CampaignState( name="campaign", project_dir=tmp_path, root_goal="Complete the campaign", status=CampaignStatus.ESCALATED, stop_reason="Manual retry required", batches=[ CampaignBatch( ordinal=1, plan_name="campaign-batch-001", goal="Complete the batch", task_count=2, ) ], ) store.save(campaign) plan = TaskPlan( project_name="campaign-batch-001", goal="Complete the batch", intent="implement", tasks=[ TaskNode( id="recovered", title="Recovered", description="Recovered by retry", status=TaskStatus.PASSED, ), TaskNode( id="still-blocked", title="Still blocked", description="Still requires intervention", status=TaskStatus.ESCALATED, ), ], ) manual_retry._clear_stale_campaign_escalation( config, plan, plan.project_name, SimpleNamespace(console=SimpleNamespace(print=lambda *_args: None)), ) saved = store.load(campaign.name) assert saved is not None assert saved.status is CampaignStatus.ESCALATED assert saved.stop_reason == "Manual retry required" def test_auto_resume_halts_after_escalation(tmp_path: Path, monkeypatch) -> None: calls: list[str] = [] def fake_execute(plan, *_args, **_kwargs) -> bool: calls.append("execute") return False monkeypatch.setattr(queue, "execute_plan", fake_execute) plan = TaskPlan( project_name="example", goal="Stop after escalation", intent="implement", tasks=[ TaskNode( id="foundation", title="Foundation", description="Needs a manual retry", status=TaskStatus.ESCALATED, ), TaskNode( id="dependent", title="Dependent", description="Blocked by foundation", dependencies=["foundation"], status=TaskStatus.BLOCKED, ), ], ) cortex = _FakeCortex() config = Config(projects_dir=tmp_path / "state", target_python=Path(sys.executable)) cli._run_plan(plan, config, cortex, tmp_path, "", "", auto_resume=True) assert calls == ["execute"] assert cortex.permanent_writes == 1 assert cortex.sessions == 1 def test_auto_resume_halts_when_a_queue_pass_makes_no_progress(tmp_path: Path, monkeypatch) -> None: calls: list[str] = [] def fake_execute(plan, *_args, **_kwargs) -> bool: calls.append("execute") return False monkeypatch.setattr(queue, "execute_plan", fake_execute) plan = TaskPlan( project_name="example", goal="Detect no progress", intent="implement", tasks=[TaskNode(id="task", title="Task", description="No state change")], ) cortex = _FakeCortex() config = Config(projects_dir=tmp_path / "state", target_python=Path(sys.executable)) cli._run_plan(plan, config, cortex, tmp_path, "", "", auto_resume=True) assert calls == ["execute"] assert cortex.sessions == 1 def test_auto_resume_respects_the_queue_pass_cap(tmp_path: Path, monkeypatch) -> None: calls: list[str] = [] def fake_execute(plan, *_args, **_kwargs) -> bool: calls.append("execute") task = plan.tasks[0] task.status = TaskStatus.RETRYING task.retry_count += 1 return False monkeypatch.setattr(queue, "execute_plan", fake_execute) plan = TaskPlan( project_name="example", goal="Bound repeated recovery attempts", intent="implement", tasks=[TaskNode(id="task", title="Task", description="Changes every pass")], ) cortex = _FakeCortex() config = Config(projects_dir=tmp_path / "state", target_python=Path(sys.executable)) cli._run_plan( plan, config, cortex, tmp_path, "", "", auto_resume=True, max_auto_resume_passes=2, ) assert calls == ["execute", "execute"] assert cortex.sessions == 2 def test_active_process_guard_ignores_maintenance_invocations(monkeypatch) -> None: monkeypatch.setattr(cli.os, "getpid", lambda: 100) monkeypatch.setattr( cli.subprocess, "run", lambda *_args, **_kwargs: SimpleNamespace( returncode=0, stdout="101\tpython -m afk_developer.cli maintain-state example\n", ), ) assert not cli._other_afk_processes_active() def test_active_process_guard_detects_mutating_execution(monkeypatch) -> None: monkeypatch.setattr(cli.os, "getpid", lambda: 100) monkeypatch.setattr( cli.subprocess, "run", lambda *_args, **_kwargs: SimpleNamespace( returncode=0, stdout="101\tpython -m afk_developer.cli resume example --auto-resume\n", ), ) assert cli._other_afk_processes_active() def test_active_process_guard_allows_the_single_current_campaign(monkeypatch) -> None: monkeypatch.setattr(cli.os, "getpid", lambda: 100) monkeypatch.setattr( cli.subprocess, "run", lambda *_args, **_kwargs: SimpleNamespace( returncode=0, stdout="101\tpython -m afk_developer.cli campaign run sample --yes\n", ), ) assert not cli._other_afk_processes_active() def test_active_process_guard_detects_second_campaign(monkeypatch) -> None: monkeypatch.setattr(cli.os, "getpid", lambda: 100) monkeypatch.setattr( cli.subprocess, "run", lambda *_args, **_kwargs: SimpleNamespace( returncode=0, stdout=( "101\tpython -m afk_developer.cli campaign run sample --yes\n" "102\tpython -m afk_developer.cli campaign run other --yes\n" ), ), ) assert cli._other_afk_processes_active() def test_retry_escalates_when_review_fails(tmp_path: Path, monkeypatch) -> None: class FakeCortex: def write_fading(self, **_kwargs) -> None: pass def save_session(self, _stats) -> None: pass class FakeWorker: def __init__(self, *_args, **_kwargs) -> None: pass def execute_task(self, _task): return TaskStatus.PASSED, "worker completed", ["changed.py"] plan = TaskPlan( project_name="example", goal="Do not bypass review", intent="implement", tasks=[TaskNode(id="task", title="Task", description="Needs review")], ) loaded = (plan, str(tmp_path), "", "", cli.LintMode.STRICT, 10) saved_statuses: list[TaskStatus] = [] context = SimpleNamespace( obj={"config": Config(projects_dir=tmp_path / "state", target_python=Path(sys.executable))} ) monkeypatch.setattr(cli, "_load_plan", lambda *_args: loaded) monkeypatch.setattr(cli, "_init_cortex", lambda *_args: FakeCortex()) monkeypatch.setattr( cli, "_save_plan", lambda _config, saved_plan, **_kwargs: saved_statuses.append(saved_plan.tasks[0].status), ) monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: reviewer.ReviewResult(False, True, False), ) cli.retry.callback.__wrapped__(context, "example", "task", False, None) assert plan.tasks[0].status == TaskStatus.ESCALATED assert saved_statuses == [TaskStatus.IN_PROGRESS, TaskStatus.ESCALATED] governance_events = (tmp_path / "state" / "example" / "governance-events.jsonl").read_text( encoding="utf-8" ) assert '"kind":"environment_resolved"' in governance_events def test_retry_serializes_success_status_without_pydantic_warning( tmp_path: Path, monkeypatch ) -> None: class FakeCortex: def write_fading(self, **_kwargs) -> None: pass def save_session(self, _stats) -> None: pass def list_sessions(self, **_kwargs) -> list[object]: return [] class FakeWorker: def __init__(self, *_args, **_kwargs) -> None: pass def execute_task(self, _task): return TaskStatus.PASSED, "worker completed", ["changed.py"] plan = TaskPlan( project_name="example", goal="Persist a passed retry", intent="implement", tasks=[TaskNode(id="task", title="Task", description="Needs review")], ) config = Config(projects_dir=tmp_path / "state", target_python=Path(sys.executable)) loaded = (plan, str(tmp_path), "", "", cli.LintMode.STRICT, 10) context = SimpleNamespace(obj={"config": config}) original_load_plan = cli._load_plan monkeypatch.setattr(cli, "_load_plan", lambda *_args: loaded) monkeypatch.setattr(cli, "_init_cortex", lambda *_args: FakeCortex()) monkeypatch.setattr(cli, "_estimate_cost", lambda *_args: None) monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: reviewer.ReviewResult(True, True, True), ) with warnings.catch_warnings(): warnings.simplefilter("error", UserWarning) cli.retry.callback.__wrapped__(context, "example", "task", False, None) saved = original_load_plan(config, "example") assert plan.tasks[0].status is TaskStatus.PASSED assert saved is not None assert saved[0].tasks[0].status is TaskStatus.PASSED def test_retry_clears_a_stale_campaign_escalation_once_its_task_resolves( tmp_path: Path, monkeypatch ) -> None: from afk_developer.campaign_models import CampaignState, CampaignStatus, PhaseState from afk_developer.campaign_store import CampaignStore class _EscalationFakeCortex: def write_fading(self, **_kwargs) -> None: pass def save_session(self, _stats) -> None: pass def list_sessions(self, **_kwargs) -> list[object]: return [] class _EscalationFakeWorker: def __init__(self, *_args, **_kwargs) -> None: pass def execute_task(self, _task): return TaskStatus.PASSED, "worker completed", ["changed.py"] plan = TaskPlan( project_name="camp-phase-001", goal="Resolve the escalated task", intent="implement", tasks=[TaskNode(id="task", title="Task", description="Needs review")], ) config = Config(projects_dir=tmp_path / "state", target_python=Path(sys.executable)) loaded = (plan, str(tmp_path), "", "", cli.LintMode.STRICT, 10) context = SimpleNamespace(obj={"config": config}) store = CampaignStore(config.projects_dir) campaign = CampaignState( name="camp", project_dir=tmp_path, root_goal="Build something", status=CampaignStatus.ESCALATED, stop_reason="A human must resolve the escalated task.", phases=[ PhaseState( ordinal=1, name="Phase 1", goal="Do the work", plan_name="camp-phase-001", ) ], ) store.save(campaign) monkeypatch.setattr(cli, "_load_plan", lambda *_args: loaded) monkeypatch.setattr(cli, "_init_cortex", lambda *_args: _EscalationFakeCortex()) monkeypatch.setattr(cli, "_estimate_cost", lambda *_args: None) monkeypatch.setattr(queue, "Worker", _EscalationFakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: reviewer.ReviewResult(True, True, True), ) cli.retry.callback.__wrapped__(context, "camp-phase-001", "task", False, None) reloaded = store.load("camp") assert reloaded is not None assert reloaded.status is CampaignStatus.READY assert reloaded.stop_reason == "" class FakeCortex: def write_fading(self, **_kwargs) -> None: pass def save_session(self, _stats) -> None: pass def list_sessions(self, **_kwargs) -> list[object]: return [] class FakeWorker: def __init__(self, *_args, **_kwargs) -> None: pass def execute_task(self, _task): (tmp_path / "retry.py").write_text("value = 2\n", encoding="utf-8") return TaskStatus.PASSED, "worker completed", ["retry.py"] repo = Repo.init(tmp_path) with repo.config_writer() as config_writer: config_writer.set_value("user", "name", "AFK Test") config_writer.set_value("user", "email", "afk-test@example.invalid") (tmp_path / "retry.py").write_text("value = 1\n", encoding="utf-8") repo.git.add("retry.py") repo.index.commit("Initial project") default_branch = repo.active_branch.name plan = TaskPlan( project_name="example", goal="Finalize a recovered task branch", intent="implement", tasks=[ TaskNode( id="task", title="Recovered task", description="Complete the retained branch", status=TaskStatus.ESCALATED, ) ], ) task_branch = f"afk/{plan.branch_namespace}/task" repo.create_head(task_branch).checkout() config = Config(projects_dir=tmp_path / "state", target_python=Path(sys.executable)) loaded = (plan, str(tmp_path), "", "", cli.LintMode.STRICT, 10) context = SimpleNamespace(obj={"config": config}) monkeypatch.setattr(cli, "_load_plan", lambda *_args: loaded) monkeypatch.setattr(cli, "_init_cortex", lambda *_args: FakeCortex()) monkeypatch.setattr(cli, "_estimate_cost", lambda *_args: None) monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: reviewer.ReviewResult(True, True, True), ) cli.retry.callback.__wrapped__(context, "example", "task", False, None) assert plan.tasks[0].status is TaskStatus.PASSED assert repo.active_branch.name == default_branch assert f"Merge task branch '{task_branch}'" in repo.head.commit.message assert "AFK: Recovered task [task]" in repo.head.commit.parents[1].message assert task_branch not in [branch.name for branch in repo.heads] assert (tmp_path / "retry.py").read_text(encoding="utf-8") == "value = 2\n" def test_retry_discards_a_stale_dirty_branch_left_by_an_unrelated_earlier_failure( tmp_path: Path, monkeypatch ) -> None: """A different task's branch can be left dirty (discard_branch_on_failure defaults to False). Retrying an unrelated task must discard that stale mess and proceed, instead of re-escalating the retried task with a confusing "uncommitted changes" failure_detail that has nothing to do with the task actually being retried (real symptom observed live: "Cannot retry task safely: Cannot switch to a task branch while the current branch has uncommitted changes.").""" class FakeCortex: def write_fading(self, **_kwargs) -> None: pass def save_session(self, _stats) -> None: pass def list_sessions(self, **_kwargs) -> list[object]: return [] class FakeWorker: def __init__(self, *_args, **_kwargs) -> None: pass def execute_task(self, _task): (tmp_path / "retry.py").write_text("value = 2\n", encoding="utf-8") return TaskStatus.PASSED, "worker completed", ["retry.py"] repo = Repo.init(tmp_path) with repo.config_writer() as config_writer: config_writer.set_value("user", "name", "AFK Test") config_writer.set_value("user", "email", "afk-test@example.invalid") (tmp_path / "retry.py").write_text("value = 1\n", encoding="utf-8") repo.git.add("retry.py") repo.index.commit("Initial project") # Simulate an unrelated earlier task's branch left dirty. repo.create_head("afk/other-task").checkout() (tmp_path / "retry.py").write_text("stale dirt from a different task\n", encoding="utf-8") (tmp_path / "scratch.py").write_text("# leftover\n", encoding="utf-8") plan = TaskPlan( project_name="example", goal="Retry a task while an unrelated branch is dirty", intent="implement", tasks=[ TaskNode( id="task", title="Recovered task", description="Complete the retained branch", status=TaskStatus.ESCALATED, ) ], ) config = Config(projects_dir=tmp_path / "state", target_python=Path(sys.executable)) loaded = (plan, str(tmp_path), "", "", cli.LintMode.STRICT, 10) context = SimpleNamespace(obj={"config": config}) monkeypatch.setattr(cli, "_load_plan", lambda *_args: loaded) monkeypatch.setattr(cli, "_init_cortex", lambda *_args: FakeCortex()) monkeypatch.setattr(cli, "_estimate_cost", lambda *_args: None) monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: reviewer.ReviewResult(True, True, True), ) cli.retry.callback.__wrapped__(context, "example", "task", False, None) assert plan.tasks[0].status is TaskStatus.PASSED assert not (tmp_path / "scratch.py").exists() assert "afk/other-task" not in [branch.name for branch in repo.heads] def test_retry_verification_policy_rejection_stays_retriable_when_bounded( tmp_path: Path, monkeypatch ) -> None: """A VERIFICATION_POLICY_REJECTED hit during the worker's OWN run (not during deterministic review) must stay retriable under bounded recovery, the same way the equivalent worker-status check already does -- this is a SEPARATE escalation branch (post-review-failure) that must apply the same should_bypass_immediate_escalation contract, not just the earlier worker-status check.""" class FakeCortex: def write_fading(self, **_kwargs) -> None: pass def save_session(self, _stats) -> None: pass def list_sessions(self, **_kwargs) -> list[object]: return [] class FakeWorker: def __init__(self, *_args, **_kwargs) -> None: pass def execute_task(self, _task): (tmp_path / "retry.py").write_text("value = 2\n", encoding="utf-8") return ( TaskStatus.ESCALATED, "verification_policy_rejected: The requested options are not " "permitted for git_show.", ["retry.py"], ) repo = Repo.init(tmp_path) with repo.config_writer() as config_writer: config_writer.set_value("user", "name", "AFK Test") config_writer.set_value("user", "email", "afk-test@example.invalid") (tmp_path / "retry.py").write_text("value = 1\n", encoding="utf-8") repo.git.add("retry.py") repo.index.commit("Initial project") repo.create_head("afk/task").checkout() plan = TaskPlan( project_name="example", goal="Stay retriable on a verification policy rejection", intent="implement", tasks=[ TaskNode( id="task", title="Recovered task", description="Hits a verification policy rejection mid-run", status=TaskStatus.ESCALATED, ) ], recovery=RecoverySettings(mode=RecoveryMode.BOUNDED), ) config = Config( projects_dir=tmp_path / "state", target_python=Path(sys.executable), recovery=RecoverySettings(mode=RecoveryMode.BOUNDED), ) loaded = (plan, str(tmp_path), "", "", cli.LintMode.STRICT, 10) context = SimpleNamespace(obj={"config": config}) monkeypatch.setattr(cli, "_load_plan", lambda *_args: loaded) monkeypatch.setattr(cli, "_init_cortex", lambda *_args: FakeCortex()) monkeypatch.setattr(cli, "_estimate_cost", lambda *_args: None) monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: reviewer.ReviewResult(True, True, True), ) cli.retry.callback.__wrapped__(context, "example", "task", False, None) from afk_developer.planner.task_model import TaskFailureKind assert plan.tasks[0].status is TaskStatus.FAILED assert plan.tasks[0].failure_kind is TaskFailureKind.VERIFICATION_POLICY_REJECTED def test_retry_rolls_up_decomposed_parent_once_every_subtask_has_passed( tmp_path: Path, monkeypatch ) -> None: """A subtask can pass via a standalone `afk retry` (not just the main --auto-resume scheduler loop, which already had this rollup). The parent must still flip DECOMPOSED -> PASSED once every sibling has passed, or it sits blocked forever and permanently blocks its own dependents even though its replacement work is actually done.""" class FakeCortex: def write_fading(self, **_kwargs) -> None: pass def save_session(self, _stats) -> None: pass def list_sessions(self, **_kwargs) -> list[object]: return [] class FakeWorker: def __init__(self, *_args, **_kwargs) -> None: pass def execute_task(self, _task): (tmp_path / "sub_b.py").write_text("value = 2\n", encoding="utf-8") return TaskStatus.PASSED, "worker completed", ["sub_b.py"] repo = Repo.init(tmp_path) with repo.config_writer() as config_writer: config_writer.set_value("user", "name", "AFK Test") config_writer.set_value("user", "email", "afk-test@example.invalid") (tmp_path / "sub_b.py").write_text("value = 1\n", encoding="utf-8") repo.git.add("sub_b.py") repo.index.commit("Initial project") repo.create_head("afk/sub-b").checkout() plan = TaskPlan( project_name="example", goal="Decompose a stuck task", intent="implement", tasks=[ TaskNode( id="parent", title="Stuck parent", description="Split into two independent parts", status=TaskStatus.DECOMPOSED, subtask_ids=["sub-a", "sub-b"], ), TaskNode( id="sub-a", title="Sub A", description="Already done", status=TaskStatus.PASSED, parent_task_id="parent", ), TaskNode( id="sub-b", title="Sub B", description="Being retried now", status=TaskStatus.ESCALATED, parent_task_id="parent", ), ], recovery=RecoverySettings(require_supervisor_parent_coherence=False), ) config = Config( projects_dir=tmp_path / "state", target_python=Path(sys.executable), recovery=RecoverySettings(require_supervisor_parent_coherence=False), ) loaded = (plan, str(tmp_path), "", "", cli.LintMode.STRICT, 10) context = SimpleNamespace(obj={"config": config}) monkeypatch.setattr(cli, "_load_plan", lambda *_args: loaded) monkeypatch.setattr(cli, "_init_cortex", lambda *_args: FakeCortex()) monkeypatch.setattr(cli, "_estimate_cost", lambda *_args: None) monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: reviewer.ReviewResult(True, True, True), ) cli.retry.callback.__wrapped__(context, "example", "sub-b", False, None) tasks_by_id = {task.id: task for task in plan.tasks} assert tasks_by_id["sub-b"].status is TaskStatus.PASSED assert tasks_by_id["parent"].status is TaskStatus.PASSED def test_retry_required_profile_runs_validator_before_merging(tmp_path: Path, monkeypatch) -> None: class FakeCortex: def write_fading(self, **_kwargs) -> None: pass def save_session(self, _stats) -> None: pass def list_sessions(self, **_kwargs) -> list[object]: return [] class FakeWorker: def __init__(self, *_args, **_kwargs) -> None: pass def execute_task(self, _task): (tmp_path / "output.xml").write_text("", encoding="utf-8") return TaskStatus.PASSED, "worker completed", ["output.xml"] repo = Repo.init(tmp_path) with repo.config_writer() as config_writer: config_writer.set_value("user", "name", "AFK Test") config_writer.set_value("user", "email", "afk-test@example.invalid") (tmp_path / "output.xml").write_text("", encoding="utf-8") repo.git.add("output.xml") repo.index.commit("Initial project") default_branch = repo.active_branch.name plan = TaskPlan( project_name="example", goal="Require independent acceptance validation", intent="implement", tasks=[ TaskNode( id="task", title="Validated task", description="Complete the retained branch", status=TaskStatus.ESCALATED, acceptance_profile=AcceptanceProfile.CORPUS_RAW_OUTPUT, evidence_packet_id="example/task/revision-1", ) ], ) config = Config( projects_dir=tmp_path.parent / f"{tmp_path.name}-state", target_python=Path(sys.executable), ) loaded = (plan, str(tmp_path), "", "", cli.LintMode.STRICT, 10) context = SimpleNamespace(obj={"config": config}) validator_calls: list[str] = [] monkeypatch.setattr(cli, "_load_plan", lambda *_args: loaded) monkeypatch.setattr(cli, "_init_cortex", lambda *_args: FakeCortex()) monkeypatch.setattr(cli, "_estimate_cost", lambda *_args: None) monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: reviewer.ReviewResult(True, True, True), ) monkeypatch.setattr( queue, "validate_profiled_task", lambda **_kwargs: AcceptanceValidationResult( outcome=AcceptanceOutcome.PASS, summary="Trusted raw contract passed.", ), ) monkeypatch.setattr( queue, "_run_independent_validator", lambda **_kwargs: ( validator_calls.append("validator") or AcceptanceValidationResult( outcome=AcceptanceOutcome.PASS, summary="Independent validator passed.", ) ), ) cli.retry.callback.__wrapped__(context, "example", "task", False, None) assert validator_calls == ["validator"] assert plan.tasks[0].status is TaskStatus.PASSED assert [attempt.role for attempt in plan.tasks[0].attempts] == ["coder", "validator"] assert repo.active_branch.name == default_branch assert f"Merge task branch 'afk/{plan.branch_namespace}/task'" in repo.head.commit.message # --- Session 2 (dedup) characterization tests: pin scenarios the unified # retry/execute_plan pipeline must keep working, added BEFORE the redesign # per docs/refactor-handoffs/02-dedup.md Task 1 Step A. --- def test_retry_force_recovery_overrides_an_exhausted_semantic_budget( tmp_path: Path, monkeypatch ) -> None: """A previously-exhausted semantic-repair budget normally blocks a retry (manual_recovery_decision's requires_override) until a human explicitly passes --force-recovery. This also pins that retry refreshes plan.recovery from the LIVE config before deciding: the plan itself is built with the default (non-bounded) recovery settings, so the very fact that the first call is refused (rather than silently proceeding) proves the refresh to config.recovery=BOUNDED actually happened before manual_recovery_decision was evaluated.""" class FakeCortex: def write_fading(self, **_kwargs) -> None: pass def save_session(self, _stats) -> None: pass def list_sessions(self, **_kwargs) -> list[object]: return [] class FakeWorker: def __init__(self, *_args, **_kwargs) -> None: pass def execute_task(self, _task, recovery_context: str = ""): return TaskStatus.PASSED, "worker completed", ["changed.py"] plan = TaskPlan( project_name="example", goal="Override an exhausted semantic repair budget", intent="implement", tasks=[ TaskNode( id="task", title="Task", description="Needs an explicit override", status=TaskStatus.ESCALATED, failure_kind=TaskFailureKind.VALIDATOR_FINDINGS, validator_finding_fingerprint="same-finding", semantic_repairs_remaining=0, high_reasoning_repairs_remaining=0, semantic_repair_fingerprints=["same-finding"], ) ], ) config = Config( projects_dir=tmp_path / "state", target_python=Path(sys.executable), recovery=RecoverySettings(mode=RecoveryMode.BOUNDED), ) loaded = (plan, str(tmp_path), "", "", cli.LintMode.STRICT, 10) context = SimpleNamespace(obj={"config": config}) monkeypatch.setattr(cli, "_load_plan", lambda *_args: loaded) monkeypatch.setattr(cli, "_init_cortex", lambda *_args: FakeCortex()) monkeypatch.setattr(cli, "_estimate_cost", lambda *_args: None) monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: reviewer.ReviewResult(True, True, True), ) cli.retry.callback.__wrapped__(context, "example", "task", False, None) assert plan.tasks[0].status is TaskStatus.ESCALATED # refused, no override yet cli.retry.callback.__wrapped__(context, "example", "task", False, None, force_recovery=True) assert plan.tasks[0].status is TaskStatus.PASSED def test_retry_validate_existing_runs_review_and_acceptance_without_a_worker( tmp_path: Path, monkeypatch ) -> None: """--validate-existing must check out the retained branch, run deterministic review + acceptance, and merge on success -- without ever constructing a Worker (there is no new coder attempt to make).""" class FakeCortex: def write_fading(self, **_kwargs) -> None: pass def save_session(self, _stats) -> None: pass def list_sessions(self, **_kwargs) -> list[object]: return [] class ExplodingWorker: def __init__(self, *_args, **_kwargs) -> None: raise AssertionError("Worker must not be constructed for --validate-existing") repo = Repo.init(tmp_path) with repo.config_writer() as config_writer: config_writer.set_value("user", "name", "AFK Test") config_writer.set_value("user", "email", "afk-test@example.invalid") (tmp_path / "output.xml").write_text("", encoding="utf-8") repo.git.add("output.xml") repo.index.commit("Initial project") primary_branch = repo.active_branch.name plan = TaskPlan( project_name="example", goal="Validate retained changes", intent="implement", tasks=[ TaskNode( id="task", title="Validated task", description="Complete the retained branch", status=TaskStatus.ESCALATED, acceptance_profile=AcceptanceProfile.CORPUS_RAW_OUTPUT, evidence_packet_id="example/task/revision-1", ) ], ) repo.create_head(f"afk/{plan.branch_namespace}/task").checkout() # Leave the coder's edit UNCOMMITTED: commit only ever happens after # review+acceptance PASS in the normal pipeline, so a retained branch's # changes from an earlier attempt sit as uncommitted worktree edits -- # matching GitManager.worktree_files()'s "diff against HEAD" contract. (tmp_path / "output.xml").write_text("", encoding="utf-8") config = Config(projects_dir=tmp_path / "state", target_python=Path(sys.executable)) loaded = (plan, str(tmp_path), "", "", cli.LintMode.STRICT, 10) context = SimpleNamespace(obj={"config": config}) validator_calls: list[str] = [] monkeypatch.setattr(cli, "_load_plan", lambda *_args: loaded) monkeypatch.setattr(cli, "_init_cortex", lambda *_args: FakeCortex()) monkeypatch.setattr(cli, "_estimate_cost", lambda *_args: None) monkeypatch.setattr(queue, "Worker", ExplodingWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: reviewer.ReviewResult(True, True, True), ) monkeypatch.setattr( queue, "validate_profiled_task", lambda **_kwargs: AcceptanceValidationResult( outcome=AcceptanceOutcome.PASS, summary="Trusted raw contract passed.", ), ) monkeypatch.setattr( queue, "_run_independent_validator", lambda **_kwargs: ( validator_calls.append("validator") or AcceptanceValidationResult( outcome=AcceptanceOutcome.PASS, summary="Independent validator passed.", ) ), ) cli.retry.callback.__wrapped__(context, "example", "task", False, None, validate_existing=True) assert validator_calls == ["validator"] assert plan.tasks[0].status is TaskStatus.PASSED assert repo.active_branch.name == primary_branch assert (tmp_path / "output.xml").read_text(encoding="utf-8") == "" def test_retry_proceeds_despite_an_unsatisfied_dependency(tmp_path: Path, monkeypatch) -> None: """Manual retry targets ONE specific task a human is explicitly resolving -- it must not be silently blocked by a sibling dependency that hasn't (re)passed yet, unlike the automatic scheduler's normal dispatch gate.""" class FakeCortex: def write_fading(self, **_kwargs) -> None: pass def save_session(self, _stats) -> None: pass def list_sessions(self, **_kwargs) -> list[object]: return [] class FakeWorker: def __init__(self, *_args, **_kwargs) -> None: pass def execute_task(self, _task): return TaskStatus.PASSED, "worker completed", ["changed.py"] plan = TaskPlan( project_name="example", goal="Retry despite an unmet dependency", intent="implement", tasks=[ TaskNode( id="blocker", title="Blocker", description="Not yet passed", status=TaskStatus.PENDING, ), TaskNode( id="task", title="Task", description="Depends on blocker", status=TaskStatus.ESCALATED, dependencies=["blocker"], ), ], ) loaded = (plan, str(tmp_path), "", "", cli.LintMode.STRICT, 10) context = SimpleNamespace( obj={"config": Config(projects_dir=tmp_path / "state", target_python=Path(sys.executable))} ) monkeypatch.setattr(cli, "_load_plan", lambda *_args: loaded) monkeypatch.setattr(cli, "_init_cortex", lambda *_args: FakeCortex()) monkeypatch.setattr(cli, "_estimate_cost", lambda *_args: None) monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: reviewer.ReviewResult(True, True, True), ) cli.retry.callback.__wrapped__(context, "example", "task", False, None) assert plan.tasks[1].status is TaskStatus.PASSED def test_retry_never_decomposes_even_when_eligible(tmp_path: Path, monkeypatch) -> None: """Decompose (JIT foreman task-splitting) is reserved for the automatic --auto-resume scheduler loop; a manual `afk retry` must never trigger it, even when scope/artifact-contract checks would otherwise make the task eligible.""" class FakeCortex: def write_fading(self, **_kwargs) -> None: pass def save_session(self, _stats) -> None: pass def list_sessions(self, **_kwargs) -> list[object]: return [] class FakeWorker: def __init__(self, *_args, **_kwargs) -> None: pass def execute_task(self, _task): return TaskStatus.PASSED, "worker completed", ["changed.py"] plan = TaskPlan( project_name="example", goal="Never decompose from a manual retry", intent="implement", recovery=RecoverySettings(mode=RecoveryMode.BOUNDED), tasks=[ TaskNode( id="task", title="Task", description="Eligible for decompose but must not split", status=TaskStatus.ESCALATED, failure_kind=TaskFailureKind.TESTS_FAILED, ) ], ) loaded = (plan, str(tmp_path), "", "", cli.LintMode.STRICT, 10) context = SimpleNamespace( obj={"config": Config(projects_dir=tmp_path / "state", target_python=Path(sys.executable))} ) decompose_calls: list[str] = [] monkeypatch.setattr(cli, "_load_plan", lambda *_args: loaded) monkeypatch.setattr(cli, "_init_cortex", lambda *_args: FakeCortex()) monkeypatch.setattr(cli, "_estimate_cost", lambda *_args: None) monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: reviewer.ReviewResult(False, True, True), ) monkeypatch.setattr( queue, "_maybe_decompose_task", lambda **_kwargs: decompose_calls.append("decompose") or True, ) cli.retry.callback.__wrapped__(context, "example", "task", False, None) assert decompose_calls == [] assert plan.tasks[0].status is TaskStatus.ESCALATED