import json import sys import threading from pathlib import Path import click import pytest from click.testing import CliRunner from afk_developer import campaign as campaign_module from afk_developer import cli as cli_module from afk_developer import fsutil from afk_developer.backends.fake import FakeReasonerBackend from afk_developer.campaign import CampaignStore from afk_developer.cli import ( _campaign_ensure_queue, _load_plan, _save_plan, _validate_plan_name, main, ) from afk_developer.config import Config, LintMode from afk_developer.grillme.spec_model import TaskSpec from afk_developer.planner import decomposer as decomposer_module from afk_developer.planner.decomposer import _task_evidence_roots from afk_developer.planner.task_model import SupervisorAmendment, TaskPlan, TaskStatus from afk_developer.recovery import RecoveryMode, RecoverySettings from afk_developer.scheduler.lint_baseline import capture_ruff_baseline, save_baseline def test_validate_plan_name_accepts_isolated_state_name(): assert _validate_plan_name(None, None, "peoplesoft-developer-related-content") == ( "peoplesoft-developer-related-content" ) @pytest.mark.parametrize("value", ["../escape", "state/name", ".hidden", "with space"]) def test_validate_plan_name_rejects_unsafe_state_name(value): with pytest.raises(click.BadParameter): _validate_plan_name(None, None, value) def test_task_evidence_roots_captures_goal_corpus_but_excludes_target(tmp_path): target = tmp_path / "target" evidence = tmp_path / "corpus" target.mkdir() evidence.mkdir() spec = TaskSpec( project_dir=target, project_name="target", goal=f"Use {evidence} as immutable evidence; work only in {target}.", ) assert _task_evidence_roots(spec, {"description": "Audit the corpus."}) == [ str(evidence.resolve()) ] def test_task_evidence_roots_ignores_slash_separated_prose(tmp_path): spec = TaskSpec( project_dir=tmp_path, project_name="target", goal="Run pytest/Ruff/Git checks with no external evidence path.", ) assert _task_evidence_roots(spec, {"description": "Check start/end markers."}) == [] def test_save_plan_leaves_prior_save_untouched_when_write_is_interrupted(tmp_path, monkeypatch): """_save_plan must write via temp-file-then-replace so a crash mid-write can never leave plan.json truncated or corrupted -- the previous save must survive intact.""" config = Config(projects_dir=tmp_path / "state") plan = TaskPlan( project_name="atomic-example", goal="original goal", intent="implement", tasks=[], ) assert _save_plan(config, plan, project_dir=tmp_path) path = cli_module._get_plan_path(config, plan.project_name) original_bytes = path.read_bytes() plan.goal = "a goal that must never land if the write is interrupted" def _boom(*_args, **_kwargs): raise RuntimeError("simulated crash mid-write") monkeypatch.setattr(fsutil, "NamedTemporaryFile", _boom) with pytest.raises(RuntimeError): _save_plan(config, plan, project_dir=tmp_path) assert path.read_bytes() == original_bytes def test_save_plan_retries_through_a_transient_windows_permission_error(tmp_path, monkeypatch): """os.replace can transiently raise PermissionError: [WinError 5] on Windows if another process (antivirus, indexer, backup agent) briefly has the just-written temp file open -- this is reliably transient, not a real conflict. _save_plan must retry through it instead of crashing the whole run on an unhandled PermissionError.""" config = Config(projects_dir=tmp_path / "state") plan = TaskPlan( project_name="flaky-replace-example", goal="a goal that must still land after a transient PermissionError", intent="implement", tasks=[], ) real_replace = Path.replace calls = {"count": 0} def _flaky_replace(self, target): calls["count"] += 1 if calls["count"] == 1: raise PermissionError("[WinError 5] Access is denied (simulated)") return real_replace(self, target) monkeypatch.setattr(Path, "replace", _flaky_replace) monkeypatch.setattr(fsutil.time, "sleep", lambda _seconds: None) assert _save_plan(config, plan, project_dir=tmp_path) path = cli_module._get_plan_path(config, plan.project_name) saved = json.loads(path.read_text(encoding="utf-8")) assert saved["goal"] == "a goal that must still land after a transient PermissionError" assert calls["count"] == 2 def test_save_plan_preserves_audit_log_path(tmp_path): config = Config(projects_dir=tmp_path / "state") plan = TaskPlan( project_name="audited-example", goal="retain the friction audit configuration", intent="implement", tasks=[], audit_log_path="audits/audited-example.jsonl", supervisor_amendments=[SupervisorAmendment(reason="Split an oversized task.")], ) assert _save_plan(config, plan, project_dir=tmp_path) loaded = _load_plan(config, plan.project_name) assert loaded is not None assert loaded[0].audit_log_path == "audits/audited-example.jsonl" assert loaded[0].supervisor_amendments[0].reason == "Split an oversized task." def test_load_plan_generates_namespace_for_legacy_plan(tmp_path): config = Config(projects_dir=tmp_path / "state") path = cli_module._get_plan_path(config, "legacy-example") path.parent.mkdir(parents=True) path.write_text( json.dumps( { "project_name": "legacy-example", "goal": "Load an older saved plan.", "intent": "implement", "tasks": [], } ), encoding="utf-8", ) loaded = _load_plan(config, "legacy-example") assert loaded is not None assert loaded[0].branch_namespace def test_status_command_shows_a_one_shot_plan_snapshot(tmp_path, monkeypatch): from afk_developer.planner.task_model import TaskNode config = Config.from_env() config.projects_dir = tmp_path / "state" monkeypatch.setattr("afk_developer.cli.Config.from_env", lambda: config) plan = TaskPlan( project_name="widget-factory", goal="Build a working widget factory end to end", intent="implement", tasks=[ TaskNode(id="t1", title="First task", description="Do the first thing."), ], ) plan.tasks[0].status = TaskStatus.PASSED assert _save_plan(config, plan, project_dir=tmp_path) result = CliRunner().invoke(main, ["status", "widget-factory"]) assert result.exit_code == 0, result.output assert "widget-factory" in result.output assert "Build a working widget factory end to end" in result.output assert "t1" in result.output assert "passed" in result.output assert "Passed: 1" in result.output def test_status_command_without_project_lists_projects_and_campaigns(tmp_path, monkeypatch): from afk_developer.campaign_models import CampaignState from afk_developer.planner.task_model import TaskNode config = Config.from_env() config.projects_dir = tmp_path / "state" monkeypatch.setattr("afk_developer.cli.Config.from_env", lambda: config) standalone_target = tmp_path / "standalone-target" campaign_target = tmp_path / "campaign-target" standalone_target.mkdir() campaign_target.mkdir() plan = TaskPlan( project_name="standalone-project", goal="Build the standalone project", intent="implement", tasks=[TaskNode(id="t1", title="First task", description="Do the first thing.")], ) plan.tasks[0].status = TaskStatus.PASSED assert _save_plan(config, plan, project_dir=standalone_target) CampaignStore(config.projects_dir).save( CampaignState( name="new-core", project_dir=campaign_target, root_goal="Build a new processor core", ) ) result = CliRunner().invoke(main, ["status"], terminal_width=240) assert result.exit_code == 0, result.output assert "standalone-project" in result.output assert standalone_target.name in result.output assert "new-core" in result.output assert campaign_target.name in result.output assert "needs roadmap approval" in result.output def test_status_command_without_project_supports_watch_mode(tmp_path, monkeypatch): config = Config.from_env() config.projects_dir = tmp_path / "state" monkeypatch.setattr("afk_developer.cli.Config.from_env", lambda: config) plan = TaskPlan( project_name="watched-project", goal="Build a visible project", intent="implement", tasks=[], ) assert _save_plan(config, plan, project_dir=tmp_path / "target") def render_once(console, interval, render): assert interval == 0.2 console.print(render()) monkeypatch.setattr("afk_developer.watch.watch_loop", render_once) result = CliRunner().invoke(main, ["status", "--watch", "--interval", "0.2"]) assert result.exit_code == 0, result.output assert "watched-project" in result.output assert "Stopped watching" in result.output def test_status_command_reports_a_clear_error_for_an_unknown_project(tmp_path, monkeypatch): config = Config.from_env() config.projects_dir = tmp_path / "state" monkeypatch.setattr("afk_developer.cli.Config.from_env", lambda: config) result = CliRunner().invoke(main, ["status", "no-such-project"]) assert result.exit_code != 0 assert "no-such-project" in result.output def test_prepare_lint_baseline_reuses_file_created_by_a_concurrent_holder(tmp_path, monkeypatch): """A caller blocked waiting for the lint-baseline lock must, once it acquires the lock, notice a baseline was already created while it waited and read that back instead of capturing (and redundantly overwriting) a second one.""" project_dir = tmp_path / "project" project_dir.mkdir() config = Config(projects_dir=tmp_path / "state") baseline_path = cli_module._lint_baseline_path(config, "example") capture_calls: list[int] = [] def _counting_capture(target_dir, project_name): capture_calls.append(1) return capture_ruff_baseline(target_dir, project_name) monkeypatch.setattr(cli_module, "capture_ruff_baseline", _counting_capture) started = threading.Event() release = threading.Event() def _hold_lock_then_create_baseline(): with cli_module._LINT_BASELINE_LOCK: started.set() release.wait(timeout=5) # Simulate a concurrent worker thread winning the race and creating # the baseline first, while our real caller below sits blocked on # the lock -- it must never call capture_ruff_baseline itself. save_baseline(baseline_path, capture_ruff_baseline(project_dir, "example")) holder = threading.Thread(target=_hold_lock_then_create_baseline) holder.start() assert started.wait(timeout=5) result_box: list = [] def _call(): result_box.append( cli_module._prepare_lint_baseline( config, "example", project_dir, "ruff", LintMode.BASELINE, True ) ) caller = threading.Thread(target=_call) caller.start() caller.join(timeout=0.5) assert caller.is_alive() # genuinely blocked on the lock, not racing ahead unlocked release.set() caller.join(timeout=10) holder.join(timeout=10) assert not caller.is_alive() assert capture_calls == [] assert result_box[0] is not None assert result_box[0].project_name == "example" def test_campaign_create_accepts_none_profile_with_read_only_evidence_roots(tmp_path, monkeypatch): target = tmp_path / "target" evidence_root = tmp_path / "corpus" target.mkdir() evidence_root.mkdir() config = Config.from_env() config.projects_dir = tmp_path / "state" monkeypatch.setattr("afk_developer.cli.Config.from_env", lambda: config) result = CliRunner().invoke( main, [ "campaign", "create", "read-only-audit", "--project-dir", str(target), "--goal", "Audit the approved immutable evidence root.", "--profile", "none", "--evidence-root", str(evidence_root), ], ) assert result.exit_code == 0, result.output campaign = CampaignStore(config.projects_dir).load("read-only-audit") assert campaign is not None assert campaign.evidence_roots == [str(evidence_root.resolve())] def _clean_core_target(tmp_path): from git import Actor, Repo target = tmp_path / "new-core" target.mkdir() interpreter = ( target / ".venv" / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") ) interpreter.parent.mkdir(parents=True) interpreter.write_text("", encoding="utf-8") (target / ".gitignore").write_text(".venv/\n", encoding="utf-8") (target / "README.md").write_text("# New core\n", encoding="utf-8") repo = Repo.init(target) repo.index.add([".gitignore", "README.md"]) repo.index.commit( "Initial baseline", author=Actor("AFK Test", "afk@example.invalid"), committer=Actor("AFK Test", "afk@example.invalid"), ) repo.close() return target, interpreter def _create_core_args(target: Path) -> list[str]: return [ "campaign", "create-core", "mos6502-core", "--project-dir", str(target), "--architecture", "NMOS 6502", "--package-name", "sixfiveohtwo", "--oracle-name", "SingleStepTests/65x02", "--oracle-repository", "https://github.com/SingleStepTests/65x02", "--oracle-revision", "2f6980a2d95757486c7bee24355c360e40e2a224", "--oracle-scale", "256 files with 10,000 records each", ] def test_campaign_create_core_builds_bounded_unapproved_campaign(tmp_path, monkeypatch): target, interpreter = _clean_core_target(tmp_path) config = Config.from_env() config.projects_dir = tmp_path / "state" monkeypatch.setattr("afk_developer.cli.Config.from_env", lambda: config) result = CliRunner().invoke(main, _create_core_args(target)) assert result.exit_code == 0, result.output campaign = CampaignStore(config.projects_dir).load("mos6502-core") assert campaign is not None assert campaign.status.value == "ready" assert not campaign.plan_approved assert not campaign.ever_approved assert campaign.phases == [] assert campaign.batches == [] assert campaign.limits.max_active_seconds == 16 * 3600 assert campaign.limits.max_batches == 8 assert campaign.limits.max_total_tasks == 120 assert campaign.limits.max_tasks_per_batch == 20 assert campaign.limits.max_auto_resume_passes == 24 assert not campaign.limits.require_supervisor_parent_coherence assert campaign.friction_audit_enabled assert "NMOS 6502" in campaign.root_goal assert "sixfiveohtwo" in campaign.root_goal assert "SingleStepTests/65x02" in campaign.root_goal assert "2f6980a2d95757486c7bee24355c360e40e2a224" in campaign.root_goal assert "256 files with 10,000 records each" in campaign.root_goal assert str(interpreter.resolve()) in campaign.root_goal assert "Never parametrize one pytest case per raw oracle record" in campaign.root_goal assert not list(config.projects_dir.glob("*/plan.json")) assert "afk campaign plan mos6502-core" in result.output assert "afk status --watch" in result.output @pytest.mark.parametrize( ("invalid_target", "expected_error"), [ ("missing-interpreter", "needs a local interpreter"), ("dirty-worktree", "found dirty worktree"), ], ) def test_campaign_create_core_rejects_unsafe_target_before_saving( tmp_path, monkeypatch, invalid_target, expected_error ): target, interpreter = _clean_core_target(tmp_path) if invalid_target == "missing-interpreter": interpreter.unlink() else: (target / "untracked.txt").write_text("not part of the baseline", encoding="utf-8") config = Config.from_env() config.projects_dir = tmp_path / "state" monkeypatch.setattr("afk_developer.cli.Config.from_env", lambda: config) result = CliRunner().invoke(main, _create_core_args(target)) assert result.exit_code != 0 assert expected_error in result.output assert CampaignStore(config.projects_dir).load("mos6502-core") is None def test_campaign_create_core_requires_full_immutable_oracle_revision(tmp_path, monkeypatch): target, _ = _clean_core_target(tmp_path) config = Config.from_env() config.projects_dir = tmp_path / "state" monkeypatch.setattr("afk_developer.cli.Config.from_env", lambda: config) arguments = _create_core_args(target) arguments[arguments.index("--oracle-revision") + 1] = "main" result = CliRunner().invoke(main, arguments) assert result.exit_code != 0 assert "full 40- or 64-character Git object ID" in result.output assert CampaignStore(config.projects_dir).load("mos6502-core") is None def test_campaign_cancel_marks_a_saved_campaign_terminal(tmp_path, monkeypatch): from afk_developer.campaign import CampaignStatus target = tmp_path / "target" target.mkdir() config = Config.from_env() config.projects_dir = tmp_path / "state" monkeypatch.setattr("afk_developer.cli.Config.from_env", lambda: config) runner = CliRunner() create_result = runner.invoke( main, [ "campaign", "create", "nightly-work", "--project-dir", str(target), "--goal", "Improve the target project incrementally.", ], ) assert create_result.exit_code == 0, create_result.output cancel_result = runner.invoke(main, ["campaign", "cancel", "nightly-work"]) assert cancel_result.exit_code == 0, cancel_result.output campaign = CampaignStore(config.projects_dir).load("nightly-work") assert campaign is not None assert campaign.status is CampaignStatus.CANCELLED second_cancel = runner.invoke(main, ["campaign", "cancel", "nightly-work"]) assert second_cancel.exit_code == 0, second_cancel.output assert "already" in second_cancel.output.lower() def test_campaign_extend_reopens_only_active_time_exhaustion(tmp_path, monkeypatch): """A supervisor can explicitly add time without resetting consumed budget.""" from afk_developer.campaign import CampaignLimits, CampaignState, CampaignStatus config, target = _configured(tmp_path, monkeypatch) store = CampaignStore(config.projects_dir) state = CampaignState( name="long-run", project_dir=target, root_goal="Finish the approved durable queue.", limits=CampaignLimits(max_active_seconds=3600), active_seconds=3600, status=CampaignStatus.EXHAUSTED, stop_reason="Active-time budget exhausted.", ) store.save(state) result = CliRunner().invoke( main, ["campaign", "extend", "long-run", "--additional-hours", "2"], ) assert result.exit_code == 0, result.output extended = store.load("long-run") assert extended is not None assert extended.status is CampaignStatus.READY assert extended.stop_reason == "" assert extended.active_seconds == 3600 assert extended.limits.max_active_seconds == 3 * 3600 def test_campaign_extend_rejects_non_time_exhaustion(tmp_path, monkeypatch): """The extension command cannot override another terminal safeguard.""" from afk_developer.campaign import CampaignLimits, CampaignState, CampaignStatus config, target = _configured(tmp_path, monkeypatch) CampaignStore(config.projects_dir).save( CampaignState( name="queue-cap", project_dir=target, root_goal="Finish the approved durable queue.", limits=CampaignLimits(max_active_seconds=3600), status=CampaignStatus.EXHAUSTED, stop_reason="Queue-step budget exhausted.", ) ) result = CliRunner().invoke( main, ["campaign", "extend", "queue-cap", "--additional-hours", "1"], ) assert result.exit_code != 0 assert "active-time budget" in result.output # --------------------------------------------------------------------------- # Phase roadmaps + plan-first approval (Stage 2) # --------------------------------------------------------------------------- def _configured(tmp_path, monkeypatch): target = tmp_path / "target" target.mkdir() # remaining-0.txt stands in for the campaign's own (root) closure metric. for ordinal in range(0, 11): _write_remaining(target, ordinal, 3) config = Config.from_env() config.projects_dir = tmp_path / "state" monkeypatch.setattr("afk_developer.cli.Config.from_env", lambda: config) return config, target def _write_remaining(target: Path, ordinal: int, value: int) -> None: """Stand-in for real repository state a phase's closure metric would measure.""" (target / f"remaining-{ordinal}.txt").write_text(str(value), encoding="utf-8") def _remaining_metric(ordinal: int) -> dict: script = f"import pathlib;print(pathlib.Path('remaining-{ordinal}.txt').read_text().strip())" return { "name": f"remaining-{ordinal}", "command": f'"{sys.executable}" -c "{script}"', "target": 0, "direction": "down", } def _fake_reasoner_registry(response: str): backend = FakeReasonerBackend([response]) class _Registry: def __init__(self, _config) -> None: pass def get_reasoner(self) -> FakeReasonerBackend: return backend return _Registry def _roadmap_json( count: int = 3, first_phase_task_ids: tuple[str, ...] = ("bootstrap",), *, unmeasured_phases: tuple[int, ...] = (), unmeasured_root: bool = False, ) -> str: task_ids_by_phase = { 1: list(first_phase_task_ids), 2: ["core" if "core" not in first_phase_task_ids else "phase-2-task"], 3: ["polish" if "polish" not in first_phase_task_ids else "phase-3-task"], } phases = [] for i in range(1, count + 1): phase = { "name": f"Phase {i}", "goal": f"Goal for phase {i}.", "task_ids": task_ids_by_phase.get(i, [f"phase-{i}-task"]), "acceptance_criteria": [f"Criterion {i}"], } if i not in unmeasured_phases: phase["closure_metric"] = _remaining_metric(i) phases.append(phase) roadmap: dict = {"phases": phases} if not unmeasured_root: roadmap["closure_metric"] = _remaining_metric(0) return json.dumps(roadmap) def _tasks_json(*task_ids: str) -> str: return json.dumps( { "tasks": [ { "id": task_id, "title": task_id, "description": f"Do {task_id}.", "hypothesis": f"Doing {task_id} satisfies its criterion.", "contract_command": f'"{sys.executable}" -c "pass"', "dependencies": [], } for task_id in task_ids ] } ) def _fake_campaign_backends(monkeypatch, *, roadmap_response: str, decompose_response: str) -> None: monkeypatch.setattr( campaign_module, "BackendRegistry", _fake_reasoner_registry(roadmap_response) ) monkeypatch.setattr( decomposer_module, "BackendRegistry", _fake_reasoner_registry(decompose_response) ) def _create_and_approve_phased_campaign(runner, tmp_path, monkeypatch, *, approve_each_phase=False): config, target = _configured(tmp_path, monkeypatch) _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3), decompose_response=_tasks_json("bootstrap") ) assert ( runner.invoke( main, [ "campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship it.", ], ).exit_code == 0 ) plan_args = ["campaign", "plan", "phased-work"] if approve_each_phase: plan_args.append("--approve-each-phase") assert runner.invoke(main, plan_args).exit_code == 0 assert runner.invoke(main, ["campaign", "approve", "phased-work"]).exit_code == 0 return config, target def _mark_active_phase_all_done(config, campaign_name, *, close_metric: bool = True): store = CampaignStore(config.projects_dir) campaign = store.load(campaign_name) active = campaign.active_phase() if close_metric: _write_remaining(campaign.project_dir, active.ordinal, 0) if active.ordinal == len(campaign.phases): _write_remaining(campaign.project_dir, 0, 0) loaded = _load_plan(config, active.plan_name) plan = loaded[0] for task in plan.tasks: task.status = TaskStatus.PASSED _save_plan( config, plan, project_dir=loaded[1], linter=loaded[2], test_framework=loaded[3], lint_mode=loaded[4], max_auto_resume_passes=loaded[5], ) return store, campaign def test_campaign_plan_drafts_roadmap_and_phase_one_tasks(tmp_path, monkeypatch): config, target = _configured(tmp_path, monkeypatch) _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3, ("bootstrap", "core")), decompose_response=_tasks_json("bootstrap", "core"), ) runner = CliRunner() assert ( runner.invoke( main, [ "campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship a phased project.", "--friction-audit", ], ).exit_code == 0 ) plan_result = runner.invoke(main, ["campaign", "plan", "phased-work"]) assert plan_result.exit_code == 0, plan_result.output campaign = CampaignStore(config.projects_dir).load("phased-work") assert len(campaign.phases) == 3 assert campaign.phases[0].plan_name == "phased-work-phase-001" assert campaign.phases[0].status.value == "planned" assert campaign.phases[1].plan_name == "" assert campaign.batches[-1].task_count == 2 assert campaign.plan_approved is False assert campaign.ever_approved is False loaded = _load_plan(config, campaign.phases[0].plan_name) assert loaded is not None assert loaded[0].audit_log_path == "audits/phased-work-phase-001.jsonl" def test_campaign_replace_task_preserves_plan_metadata(tmp_path, monkeypatch): from afk_developer.campaign import CampaignBatch, CampaignState, CampaignStatus from afk_developer.planner.task_model import TaskNode config, target = _configured(tmp_path, monkeypatch) plan_name = "repair-work-phase-001" plan = TaskPlan( project_name=plan_name, goal="Repair the queue.", intent="implement", tasks=[ TaskNode(id="bad", title="Bad", description="Oversized.", status=TaskStatus.ESCALATED), TaskNode(id="after", title="After", description="Continue.", dependencies=["bad"]), ], recovery=RecoverySettings( mode=RecoveryMode.BOUNDED, semantic_repair_limit=2, high_reasoning_repair_limit=2, ), ) _save_plan( config, plan, project_dir=target, linter="ruff", test_framework="pytest", lint_mode=LintMode.BASELINE, max_auto_resume_passes=7, ) CampaignStore(config.projects_dir).save( CampaignState( name="repair-work", project_dir=target, root_goal="Repair the queue.", status=CampaignStatus.RUNNING, friction_audit_enabled=True, batches=[CampaignBatch(ordinal=1, plan_name=plan_name, goal="Repair.", task_count=2)], ) ) spec_path = tmp_path / "replacement.json" spec_path.write_text( json.dumps( [ { "id": "narrow-one", "title": "Narrow one", "description": "Fit the first mutation ceiling.", "max_changed_files": 2, "max_changed_lines": 100, }, { "id": "narrow-two", "title": "Narrow two", "description": "Fit the second mutation ceiling.", "dependencies": ["narrow-one"], "max_changed_files": 2, "max_changed_lines": 100, }, ] ), encoding="utf-8", ) result = CliRunner().invoke( main, [ "campaign", "replace-task", "repair-work", "bad", "--spec", str(spec_path), "--reason", "Split the oversized task.", ], ) assert result.exit_code == 0, result.output loaded = _load_plan(config, plan_name) assert loaded is not None amended, project_dir, linter, test_framework, lint_mode, max_passes = loaded tasks = {task.id: task for task in amended.tasks} assert tasks["bad"].status is TaskStatus.NOT_APPLICABLE assert tasks["after"].dependencies == ["narrow-two"] assert tasks["narrow-one"].semantic_repairs_remaining == 2 assert tasks["narrow-two"].high_reasoning_repairs_remaining == 2 assert amended.supervisor_amendments[-1].replacement_task_ids == [ "narrow-one", "narrow-two", ] assert amended.audit_log_path == f"audits/{plan_name}.jsonl" assert Path(project_dir) == target assert linter == "ruff" assert test_framework == "pytest" assert lint_mode is LintMode.BASELINE assert max_passes == 7 assert CampaignStore(config.projects_dir).load("repair-work").batches[-1].task_count == 3 def test_campaign_ready_task_writes_configured_audit_log(tmp_path, monkeypatch): from afk_developer.campaign import CampaignBatch, CampaignState from afk_developer.campaign_runner import _campaign_run_ready_task from afk_developer.events import emit from afk_developer.planner.task_model import TaskNode config, target = _configured(tmp_path, monkeypatch) config.target_python = Path(sys.executable) (target / "pyproject.toml").write_text( """[project] name = "audited-work" version = "0.1.0" [project.optional-dependencies] dev = ["pytest", "ruff"] [tool.pytest.ini_options] testpaths = ["tests"] [tool.ruff] line-length = 88 """, encoding="utf-8", ) plan_name = "audited-work-phase-001" task = TaskNode(id="one", title="One", description="Run one task.") plan = TaskPlan( project_name=plan_name, goal="Run one task.", intent="implement", tasks=[task], audit_log_path=f"audits/{plan_name}.jsonl", ) _save_plan(config, plan, project_dir=target) campaign = CampaignState( name="audited-work", project_dir=target, root_goal="Run one task.", batches=[CampaignBatch(ordinal=1, plan_name=plan_name, goal="Run.", task_count=1)], ) received_tooling = {} def _emit_one_event(_plan, _config, _cortex, _target, linter, test_framework, **_kwargs): received_tooling.update(linter=linter, test_framework=test_framework) emit("attempt_summary", "Attempt complete", task_id="one", outcome="passed") monkeypatch.setattr("afk_developer.scheduler.queue.execute_plan", _emit_one_event) _campaign_run_ready_task(config, campaign, plan, task) audit_path = config.projects_dir / plan.audit_log_path record = json.loads(audit_path.read_text(encoding="utf-8")) assert record["kind"] == "attempt_summary" assert record["data"]["task_id"] == "one" assert received_tooling == {"linter": "ruff", "test_framework": "pytest"} governance_path = config.resolve_project_dir(plan_name) / "governance-events.jsonl" governance_records = [ json.loads(line) for line in governance_path.read_text(encoding="utf-8").splitlines() ] assert any(record["kind"] == "environment_resolved" for record in governance_records) def test_campaign_create_can_auto_accept_passing_parent_coherence(tmp_path, monkeypatch): config, target = _configured(tmp_path, monkeypatch) result = CliRunner().invoke( main, [ "campaign", "create", "unattended-work", "--project-dir", str(target), "--goal", "Complete a bounded unattended campaign.", "--auto-accept-parent-coherence", ], ) assert result.exit_code == 0, result.output campaign = CampaignStore(config.projects_dir).load("unattended-work") assert campaign is not None assert not campaign.limits.require_supervisor_parent_coherence def test_campaign_plan_is_redraftable_with_feedback_before_approval(tmp_path, monkeypatch): config, target = _configured(tmp_path, monkeypatch) runner = CliRunner() _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3, ("first",)), decompose_response=_tasks_json("first"), ) assert ( runner.invoke( main, [ "campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship a phased project.", ], ).exit_code == 0 ) assert runner.invoke(main, ["campaign", "plan", "phased-work"]).exit_code == 0 _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(4, ("redo",)), decompose_response=_tasks_json("redo"), ) second = runner.invoke(main, ["campaign", "plan", "phased-work", "--feedback", "Add a phase."]) assert second.exit_code == 0, second.output campaign = CampaignStore(config.projects_dir).load("phased-work") assert len(campaign.phases) == 4 assert campaign.phases[0].plan_name == "phased-work-phase-001" assert campaign.batches[-1].task_count == 1 def test_campaign_plan_blocked_after_approval(tmp_path, monkeypatch): runner = CliRunner() _create_and_approve_phased_campaign(runner, tmp_path, monkeypatch) blocked = runner.invoke(main, ["campaign", "plan", "phased-work"]) assert blocked.exit_code != 0 assert "already been approved" in blocked.output def test_campaign_approve_requires_a_drafted_roadmap(tmp_path, monkeypatch): config, target = _configured(tmp_path, monkeypatch) runner = CliRunner() assert ( runner.invoke( main, [ "campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship it.", ], ).exit_code == 0 ) result = runner.invoke(main, ["campaign", "approve", "phased-work"]) assert result.exit_code != 0 assert "no drafted roadmap" in result.output.lower() def test_campaign_approve_locks_the_roadmap_fingerprint(tmp_path, monkeypatch): config, target = _configured(tmp_path, monkeypatch) runner = CliRunner() _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3, ("first",)), decompose_response=_tasks_json("first"), ) assert ( runner.invoke( main, [ "campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship it.", ], ).exit_code == 0 ) assert runner.invoke(main, ["campaign", "plan", "phased-work"]).exit_code == 0 result = runner.invoke(main, ["campaign", "approve", "phased-work"]) assert result.exit_code == 0, result.output campaign = CampaignStore(config.projects_dir).load("phased-work") assert campaign.plan_approved is True assert campaign.ever_approved is True assert campaign.roadmap_fingerprint != "" def test_campaign_step_refuses_an_unapproved_phased_campaign(tmp_path, monkeypatch): config, target = _configured(tmp_path, monkeypatch) runner = CliRunner() _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3, ("first",)), decompose_response=_tasks_json("first"), ) assert ( runner.invoke( main, [ "campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship it.", ], ).exit_code == 0 ) assert runner.invoke(main, ["campaign", "plan", "phased-work"]).exit_code == 0 result = runner.invoke(main, ["campaign", "step", "phased-work"]) assert result.exit_code != 0 assert "unapproved phase roadmap" in result.output.lower() def test_campaign_run_refuses_a_phased_campaign(tmp_path, monkeypatch): runner = CliRunner() _create_and_approve_phased_campaign(runner, tmp_path, monkeypatch) result = runner.invoke(main, ["campaign", "run", "phased-work", "--yes"]) assert result.exit_code != 0 assert "phased campaign" in result.output.lower() def test_campaign_work_refuses_multiple_workers_without_worktree_isolation(tmp_path, monkeypatch): config, target = _configured(tmp_path, monkeypatch) runner = CliRunner() assert ( runner.invoke( main, [ "campaign", "create", "unparallel-work", "--project-dir", str(target), "--goal", "Ship it.", ], ).exit_code == 0 ) result = runner.invoke(main, ["campaign", "work", "unparallel-work", "--yes", "--workers", "2"]) assert result.exit_code != 0 assert "worktree" in result.output.lower() def test_campaign_status_shows_phase_progress(tmp_path, monkeypatch): runner = CliRunner() _create_and_approve_phased_campaign(runner, tmp_path, monkeypatch) result = runner.invoke(main, ["campaign", "status", "phased-work"]) assert result.exit_code == 0, result.output assert "Phases: 0/3 resolved; approved=True" in result.output assert "[ ] 1." in result.output def test_campaign_status_renders_completed_and_skipped_phase_markers(tmp_path, monkeypatch): """Rich markup treats a bare [x]/[skip] as an unrecognized style tag and silently drops it unless escaped -- this pins the fix so it can't regress.""" from afk_developer.campaign import PhaseStatus runner = CliRunner() config, _target = _create_and_approve_phased_campaign(runner, tmp_path, monkeypatch) store = CampaignStore(config.projects_dir) campaign = store.load("phased-work") campaign.phases[0].status = PhaseStatus.COMPLETED campaign.phases[1].status = PhaseStatus.SKIPPED store.save(campaign) result = runner.invoke(main, ["campaign", "status", "phased-work"]) assert result.exit_code == 0, result.output assert "[x] 1." in result.output assert "[skip] 2." in result.output assert "[ ] 3." in result.output def test_phase_boundary_expands_the_next_phase_and_carries_summary_forward(tmp_path, monkeypatch): runner = CliRunner() config, _target = _create_and_approve_phased_campaign(runner, tmp_path, monkeypatch) store, campaign = _mark_active_phase_all_done(config, "phased-work") monkeypatch.setattr( campaign_module, "BackendRegistry", _fake_reasoner_registry( json.dumps({"decision": "complete_phase", "summary": "Bootstrap done."}) ), ) monkeypatch.setattr( decomposer_module, "BackendRegistry", _fake_reasoner_registry(_tasks_json("core")) ) result_plan = _campaign_ensure_queue(config, store, campaign) assert not result_plan.all_done() reloaded = store.load("phased-work") assert reloaded.phases[0].status.value == "completed" assert reloaded.phases[0].summary == "Bootstrap done." assert reloaded.phases[1].status.value == "active" assert reloaded.phases[1].plan_name == "phased-work-phase-002" assert reloaded.batches[-1].plan_name == "phased-work-phase-002" def test_phase_boundary_pauses_for_reapproval_when_approve_each_phase_is_set(tmp_path, monkeypatch): runner = CliRunner() config, _target = _create_and_approve_phased_campaign( runner, tmp_path, monkeypatch, approve_each_phase=True ) store, campaign = _mark_active_phase_all_done(config, "phased-work") monkeypatch.setattr( campaign_module, "BackendRegistry", _fake_reasoner_registry(json.dumps({"decision": "complete_phase", "summary": "Done."})), ) # Phase 2 is expanded (via a real decompose call) as part of the same # transition that raises the re-approval pause, so its fake must be ready # before that call, not after. monkeypatch.setattr( decomposer_module, "BackendRegistry", _fake_reasoner_registry(_tasks_json("core")) ) with pytest.raises(click.ClickException, match="awaiting"): _campaign_ensure_queue(config, store, campaign) reloaded = store.load("phased-work") assert reloaded.status.value == "paused" assert reloaded.plan_approved is False assert reloaded.ever_approved is True assert reloaded.phases[0].status.value == "completed" assert reloaded.phases[1].plan_name == "phased-work-phase-002" reapprove = runner.invoke(main, ["campaign", "approve", "phased-work"]) assert reapprove.exit_code == 0, reapprove.output resumed_campaign = store.load("phased-work") result_plan = _campaign_ensure_queue(config, store, resumed_campaign) assert not result_plan.all_done() assert store.load("phased-work").phases[1].plan_name == "phased-work-phase-002" def test_phase_boundary_escalates_when_the_checkpoint_requires_a_human(tmp_path, monkeypatch): runner = CliRunner() config, _target = _create_and_approve_phased_campaign(runner, tmp_path, monkeypatch) store, campaign = _mark_active_phase_all_done(config, "phased-work") monkeypatch.setattr( campaign_module, "BackendRegistry", _fake_reasoner_registry( json.dumps({"decision": "escalate", "summary": "Needs human review."}) ), ) with pytest.raises(click.ClickException, match="human review"): _campaign_ensure_queue(config, store, campaign) reloaded = store.load("phased-work") assert reloaded.status.value == "escalated" assert reloaded.phases[0].status.value == "completed" assert reloaded.phases[0].summary == "Needs human review." def test_phased_campaign_completes_when_the_last_phase_completes(tmp_path, monkeypatch): from afk_developer.campaign import CampaignStatus, continue_campaign_once runner = CliRunner() config, _target = _create_and_approve_phased_campaign(runner, tmp_path, monkeypatch) store, campaign = _mark_active_phase_all_done(config, "phased-work") monkeypatch.setattr( campaign_module, "BackendRegistry", _fake_reasoner_registry( json.dumps({"decision": "complete_phase", "summary": "Phase 1 done."}) ), ) monkeypatch.setattr( decomposer_module, "BackendRegistry", _fake_reasoner_registry(_tasks_json("core")) ) _campaign_ensure_queue(config, store, campaign) store, campaign = _mark_active_phase_all_done(config, "phased-work") monkeypatch.setattr( campaign_module, "BackendRegistry", _fake_reasoner_registry( json.dumps({"decision": "complete_phase", "summary": "Phase 2 done."}) ), ) monkeypatch.setattr( decomposer_module, "BackendRegistry", _fake_reasoner_registry(_tasks_json("polish")) ) _campaign_ensure_queue(config, store, campaign) store, campaign = _mark_active_phase_all_done(config, "phased-work") monkeypatch.setattr( campaign_module, "BackendRegistry", _fake_reasoner_registry(json.dumps({"decision": "complete_phase", "summary": "All done."})), ) final_plan = _campaign_ensure_queue(config, store, campaign) assert final_plan.all_done() reloaded = store.load("phased-work") assert all(phase.status.value == "completed" for phase in reloaded.phases) result = continue_campaign_once( store.load("phased-work"), store=store, ensure_queue=lambda current: _campaign_ensure_queue(config, store, current), run_ready_task=lambda *_a: pytest.fail("No task should run once every phase is done"), persist_queue=lambda *_a: pytest.fail("No persistence should be needed"), ) assert result.queue_complete assert store.load("phased-work").status is CampaignStatus.COMPLETED # --------------------------------------------------------------------------- # Phase closure metrics: the half-done question, answered by the repository # --------------------------------------------------------------------------- def test_phase_boundary_refuses_to_close_a_phase_whose_metric_is_unsatisfied(tmp_path, monkeypatch): """Every task passed, yet the repository says work remains: the phase must not close. This is the 6502-refactor 77% case -- 12 of 12 family tasks passed while 12 opcode handlers were still inline. Nothing in the pipeline owned that residual until the closure metric did. """ runner = CliRunner() config, target = _create_and_approve_phased_campaign(runner, tmp_path, monkeypatch) store, campaign = _mark_active_phase_all_done(config, "phased-work", close_metric=False) monkeypatch.setattr( campaign_module, "BackendRegistry", _fake_reasoner_registry( json.dumps({"decision": "complete_phase", "summary": "Looks done to me."}) ), ) with pytest.raises(click.ClickException, match="reads 3, target <= 0"): _campaign_ensure_queue(config, store, campaign) reloaded = store.load("phased-work") assert reloaded.status.value == "escalated" assert "not done" in reloaded.stop_reason assert reloaded.phases[0].status.value != "completed" assert reloaded.phases[0].closure_metric.last_value == 3 assert reloaded.phases[1].plan_name == "" # Once the residual is actually closed in the repository, the same phase closes normally. from afk_developer.campaign import CampaignStatus _write_remaining(target, 1, 0) reloaded.status = CampaignStatus.READY reloaded.stop_reason = "" store.save(reloaded) monkeypatch.setattr( decomposer_module, "BackendRegistry", _fake_reasoner_registry(_tasks_json("core")) ) next_plan = _campaign_ensure_queue(config, store, store.load("phased-work")) assert not next_plan.all_done() closed = store.load("phased-work") assert closed.phases[0].status.value == "completed" assert closed.phases[0].closure_metric.last_value == 0 assert closed.phases[1].closure_metric.start_value == 3 def test_phase_boundary_escalates_when_the_closure_metric_cannot_be_measured(tmp_path, monkeypatch): runner = CliRunner() config, target = _create_and_approve_phased_campaign(runner, tmp_path, monkeypatch) store, campaign = _mark_active_phase_all_done(config, "phased-work", close_metric=False) (target / "remaining-1.txt").unlink() with pytest.raises(click.ClickException, match="closure metric failed"): _campaign_ensure_queue(config, store, campaign) assert store.load("phased-work").status.value == "escalated" def test_campaign_plan_records_the_metric_start_value_and_refuses_a_satisfied_metric( tmp_path, monkeypatch ): config, target = _configured(tmp_path, monkeypatch) runner = CliRunner() _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3, ("first",)), decompose_response=_tasks_json("first"), ) assert ( runner.invoke( main, ["campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship."], ).exit_code == 0 ) _write_remaining(target, 1, 0) refused = runner.invoke(main, ["campaign", "plan", "phased-work"]) assert refused.exit_code != 0 assert "already reads 0" in refused.output assert "cannot detect a half-done phase" in refused.output assert CampaignStore(config.projects_dir).load("phased-work").phases[0].plan_name == "" _write_remaining(target, 1, 7) _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3, ("first",)), decompose_response=_tasks_json("first"), ) planned = runner.invoke(main, ["campaign", "plan", "phased-work"]) assert planned.exit_code == 0, planned.output assert "closure metric: remaining-1: now 7, target <= 0" in planned.output campaign = CampaignStore(config.projects_dir).load("phased-work") assert campaign.phases[0].closure_metric.start_value == 7 assert campaign.phases[0].closure_metric.last_value == 7 assert campaign.phases[1].closure_metric.start_value is None def test_campaign_plan_tells_the_task_planner_about_the_closure_metric(tmp_path, monkeypatch): config, target = _configured(tmp_path, monkeypatch) runner = CliRunner() decompose_backend = FakeReasonerBackend([_tasks_json("first")]) class _DecomposeRegistry: def __init__(self, _config) -> None: pass def get_reasoner(self): return decompose_backend monkeypatch.setattr( campaign_module, "BackendRegistry", _fake_reasoner_registry(_roadmap_json(3, ("first",))) ) monkeypatch.setattr(decomposer_module, "BackendRegistry", _DecomposeRegistry) assert ( runner.invoke( main, ["campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship."], ).exit_code == 0 ) assert runner.invoke(main, ["campaign", "plan", "phased-work"]).exit_code == 0 _system_prompt, planner_input = decompose_backend.requests[-1] assert "Phase closure metric: 'remaining-1'" in planner_input assert "It currently reads 3." in planner_input assert "the final task must own whatever residual" in planner_input def test_campaign_approve_refuses_unmeasured_phases_unless_explicitly_allowed( tmp_path, monkeypatch ): config, target = _configured(tmp_path, monkeypatch) runner = CliRunner() _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3, ("first",), unmeasured_phases=(2,)), decompose_response=_tasks_json("first"), ) assert ( runner.invoke( main, ["campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship."], ).exit_code == 0 ) assert runner.invoke(main, ["campaign", "plan", "phased-work"]).exit_code == 0 refused = runner.invoke(main, ["campaign", "approve", "phased-work"]) assert refused.exit_code != 0 assert "Phase(s) 2 ('Phase 2') declare no closure metric" in refused.output assert "--allow-unmeasured-phases" in refused.output assert CampaignStore(config.projects_dir).load("phased-work").plan_approved is False allowed = runner.invoke( main, ["campaign", "approve", "phased-work", "--allow-unmeasured-phases"] ) assert allowed.exit_code == 0, allowed.output assert "2. Phase 2 - closure metric: (none" in allowed.output campaign = CampaignStore(config.projects_dir).load("phased-work") assert campaign.plan_approved is True assert campaign.roadmap_fingerprint != "" def test_campaign_status_shows_closure_metric_progress(tmp_path, monkeypatch): runner = CliRunner() _create_and_approve_phased_campaign(runner, tmp_path, monkeypatch) result = runner.invoke(main, ["campaign", "status", "phased-work"]) assert result.exit_code == 0, result.output assert "closure metric: remaining-1: now 3, target <= 0" in result.output # --------------------------------------------------------------------------- # The campaign root is itself a contract # --------------------------------------------------------------------------- def test_campaign_approve_refuses_an_unmeasured_root_unless_explicitly_allowed( tmp_path, monkeypatch ): config, target = _configured(tmp_path, monkeypatch) runner = CliRunner() _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3, ("first",), unmeasured_root=True), decompose_response=_tasks_json("first"), ) assert ( runner.invoke( main, ["campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship."], ).exit_code == 0 ) assert runner.invoke(main, ["campaign", "plan", "phased-work"]).exit_code == 0 refused = runner.invoke(main, ["campaign", "approve", "phased-work"]) assert refused.exit_code != 0 assert "campaign itself declares no closure metric" in refused.output allowed = runner.invoke( main, ["campaign", "approve", "phased-work", "--allow-unmeasured-phases"] ) assert allowed.exit_code == 0, allowed.output assert "Campaign closure metric: (none" in allowed.output def test_campaign_plan_refuses_a_root_metric_that_is_already_satisfied(tmp_path, monkeypatch): config, target = _configured(tmp_path, monkeypatch) _write_remaining(target, 0, 0) runner = CliRunner() _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3, ("first",)), decompose_response=_tasks_json("first"), ) assert ( runner.invoke( main, ["campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship."], ).exit_code == 0 ) planned = runner.invoke(main, ["campaign", "plan", "phased-work"]) assert planned.exit_code != 0 assert "Campaign closure metric 'remaining-0' already reads 0" in planned.output def test_final_phase_refuses_to_close_while_the_campaign_contract_is_unmet(tmp_path, monkeypatch): """Every phase closed its own metric, yet the objective's metric says work remains.""" runner = CliRunner() config, target = _create_and_approve_phased_campaign(runner, tmp_path, monkeypatch) reflections = [json.dumps({"decision": "complete_phase", "summary": "Done."})] * 6 monkeypatch.setattr( campaign_module, "BackendRegistry", _fake_reasoner_registry_many(reflections), ) store = CampaignStore(config.projects_dir) assert store.load("phased-work").closure_metric.start_value == 3 for next_task in ("core", "polish"): _mark_active_phase_all_done(config, "phased-work") _write_remaining(target, 0, 3) # keep the root metric open while phases 1-2 close monkeypatch.setattr( decomposer_module, "BackendRegistry", _fake_reasoner_registry(_tasks_json(next_task)) ) _campaign_ensure_queue(config, store, store.load("phased-work")) store, campaign = _mark_active_phase_all_done(config, "phased-work", close_metric=False) _write_remaining(target, 3, 0) # phase 3's own metric is satisfied; the root is not with pytest.raises(click.ClickException, match="Campaign is not done"): _campaign_ensure_queue(config, store, campaign) escalated = store.load("phased-work") assert escalated.status.value == "escalated" assert escalated.phases[2].status.value != "completed" assert escalated.closure_metric.last_value == 3 from afk_developer.campaign import CampaignStatus _write_remaining(target, 0, 0) escalated.status = CampaignStatus.READY escalated.stop_reason = "" store.save(escalated) _campaign_ensure_queue(config, store, store.load("phased-work")) closed = store.load("phased-work") assert closed.all_phases_resolved() assert closed.closure_metric.last_value == 0 def _fake_reasoner_registry_many(responses: list[str]): backend = FakeReasonerBackend(list(responses)) class _Registry: def __init__(self, _config) -> None: pass def get_reasoner(self) -> FakeReasonerBackend: return backend return _Registry def test_campaign_approve_rejects_a_phase_metric_already_at_its_target(tmp_path, monkeypatch): """A metric that starts satisfied closes its phase no matter what happened. Only the root metric is measured before phase 1, so without this gate such a phase is discovered as a useless oracle hours into a run, or never. """ runner = CliRunner() config, target = _configured(tmp_path, monkeypatch) _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3), decompose_response=_tasks_json("bootstrap") ) assert ( runner.invoke( main, ["campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship."], ).exit_code == 0 ) assert runner.invoke(main, ["campaign", "plan", "phased-work"]).exit_code == 0 # Phase 2's metric can run and already reads its target. _write_remaining(target, 2, 0) result = runner.invoke(main, ["campaign", "approve", "phased-work"]) assert result.exit_code != 0 assert "already satisfied before any work starts" in result.output assert "2 ('Phase 2')" in result.output assert not CampaignStore(config.projects_dir).load("phased-work").plan_approved def test_campaign_approve_ignores_a_phase_metric_that_cannot_run_yet(tmp_path, monkeypatch): """Later phases legitimately measure paths that earlier phases create.""" runner = CliRunner() config, target = _configured(tmp_path, monkeypatch) _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3), decompose_response=_tasks_json("bootstrap") ) assert ( runner.invoke( main, ["campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship."], ).exit_code == 0 ) assert runner.invoke(main, ["campaign", "plan", "phased-work"]).exit_code == 0 # No remaining-*.txt exists, so every phase metric fails to run entirely. result = runner.invoke(main, ["campaign", "approve", "phased-work"]) assert result.exit_code == 0, result.output assert CampaignStore(config.projects_dir).load("phased-work").plan_approved def test_campaign_replace_task_works_while_the_campaign_is_escalated(tmp_path, monkeypatch): """Escalation means a human must decide, so the deciding tools must still run. Observed live: the 6502 campaign escalated because a read-only task demanded evidence its agent could not obtain, and replace-task -- the supervisor amendment path for exactly that -- refused with "already escalated", leaving retrying the unchanged failing task as the only offered move. """ runner = CliRunner() config, target = _configured(tmp_path, monkeypatch) _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3), decompose_response=_tasks_json("bootstrap") ) assert ( runner.invoke( main, ["campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship."], ).exit_code == 0 ) assert runner.invoke(main, ["campaign", "plan", "phased-work"]).exit_code == 0 assert runner.invoke(main, ["campaign", "approve", "phased-work"]).exit_code == 0 from afk_developer.campaign import CampaignStatus store = CampaignStore(config.projects_dir) campaign = store.load("phased-work") campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = "A read-only task could not obtain its required evidence." store.save(campaign) spec = tmp_path / "replacement.json" spec.write_text( json.dumps( { "tasks": [ { "id": "bootstrap-replacement", "title": "Replacement", "description": "Ask a question this verifier can actually answer.", "contract_command": "true", "read_only": True, "acceptance_criteria": ["The source states what it imports."], } ] } ), encoding="utf-8", ) result = runner.invoke( main, [ "campaign", "replace-task", "phased-work", "bootstrap", "--spec", str(spec), "--reason", "The original demanded evidence the read-only verifier cannot obtain.", ], ) assert result.exit_code == 0, result.output assert "already escalated" not in result.output def test_campaign_replace_task_still_refuses_a_finished_campaign(tmp_path, monkeypatch): runner = CliRunner() config, target = _configured(tmp_path, monkeypatch) _fake_campaign_backends( monkeypatch, roadmap_response=_roadmap_json(3), decompose_response=_tasks_json("bootstrap") ) assert ( runner.invoke( main, ["campaign", "create", "phased-work", "--project-dir", str(target), "--goal", "Ship."], ).exit_code == 0 ) assert runner.invoke(main, ["campaign", "plan", "phased-work"]).exit_code == 0 assert runner.invoke(main, ["campaign", "approve", "phased-work"]).exit_code == 0 from afk_developer.campaign import CampaignStatus store = CampaignStore(config.projects_dir) campaign = store.load("phased-work") campaign.status = CampaignStatus.COMPLETED store.save(campaign) spec = tmp_path / "replacement.json" spec.write_text(json.dumps({"tasks": []}), encoding="utf-8") result = runner.invoke( main, ["campaign", "replace-task", "phased-work", "bootstrap", "--spec", str(spec), "--reason", "x"], ) assert result.exit_code != 0 assert "already completed" in result.output