import json import os from datetime import datetime, timedelta, timezone from pathlib import Path import click import pytest from afk_developer import campaign as campaign_module from afk_developer import campaign_store from afk_developer.backends.fake import FakeReasonerBackend from afk_developer.campaign import ( TERMINAL_CAMPAIGN_STATUSES, CampaignBatch, CampaignBusyError, CampaignLimits, CampaignReflection, CampaignState, CampaignStatus, CampaignStore, ClosureMetric, PhaseRoadmapError, PhaseState, PhaseStatus, StallDecision, apply_campaign_policy, apply_stall_decision, build_campaign_statistics, continue_campaign_once, make_batch_goal, make_phase_batch_goal, phase_roadmap_fingerprint, PhaseAmendment, PhaseAmendmentError, apply_phase_amendments, plan_phase_roadmap, reap_expired_leases, reflect_on_completed_phase, run_campaign, run_campaign_queue_until_terminal, ) from afk_developer.campaign_runner import ( _drop_completed_phase_dependencies, _campaign_close_out_phase, _record_phase_divergence, ) from afk_developer.config import Config from afk_developer.ledger import CampaignLedger, LedgerEntry, LedgerStore from afk_developer.planner.task_model import ( AcceptanceProfile, AttemptUsage, TaskAttempt, TaskNode, TaskPlan, TaskPriority, TaskStatus, ) from afk_developer.reporter import report_campaign_statistics def _campaign(tmp_path: Path, **limits) -> CampaignState: return CampaignState( name="nightly-work", project_dir=tmp_path, root_goal="Improve the target project through small verified batches.", limits=CampaignLimits(**limits), ) def test_campaign_completes_after_a_checkpoint_declares_done(tmp_path: Path) -> None: state = _campaign(tmp_path) store = CampaignStore(tmp_path / "state") created: list[str] = [] def create(current, goal): created.append(goal) return CampaignBatch( ordinal=len(current.batches) + 1, plan_name=current.next_plan_name(), goal=goal, task_count=2, ) def execute(_current, _batch): return True, ["audit: passed", "feature: passed"], "" def reflect(_current, batch, _summaries): return CampaignReflection(batch_ordinal=batch.ordinal, decision="complete", summary="Done.") result = run_campaign( state, store=store, create_batch=create, execute_batch=execute, reflect=reflect ) assert result.status is CampaignStatus.COMPLETED assert len(result.batches) == 1 assert result.total_tasks == 2 assert created assert store.load("nightly-work").status is CampaignStatus.COMPLETED def test_campaign_release_witness_policy_pauses_at_release_ready(tmp_path: Path) -> None: state = _campaign(tmp_path) state.require_release_witness = True store = CampaignStore(tmp_path / "state") result = run_campaign( state, store=store, create_batch=lambda current, goal: CampaignBatch( ordinal=len(current.batches) + 1, plan_name=current.next_plan_name(), goal=goal, task_count=1, ), execute_batch=lambda _current, _batch: (True, ["task: passed"], ""), reflect=lambda _current, batch, _summaries: CampaignReflection( batch_ordinal=batch.ordinal, decision="complete", summary="Ready for observation." ), ) assert result.status is CampaignStatus.RELEASE_READY assert store.load("nightly-work").status is CampaignStatus.RELEASE_READY def test_campaign_stops_without_reflection_when_a_batch_is_incomplete(tmp_path: Path) -> None: state = _campaign(tmp_path) store = CampaignStore(tmp_path / "state") reflections: list[str] = [] def create(current, goal): return CampaignBatch( ordinal=len(current.batches) + 1, plan_name=current.next_plan_name(), goal=goal, task_count=1, ) def execute(_current, _batch): return False, ["implementation: escalated"], "Manual retry required: implementation" def reflect(*_args): reflections.append("called") raise AssertionError("Incomplete batches must not generate follow-up work") result = run_campaign( state, store=store, create_batch=create, execute_batch=execute, reflect=reflect ) assert result.status is CampaignStatus.ESCALATED assert "Manual retry required" in result.stop_reason assert not reflections assert not result.reflections def test_campaign_enforces_batch_ceiling_after_reflective_follow_up(tmp_path: Path) -> None: state = _campaign(tmp_path, max_batches=2, max_total_tasks=10) store = CampaignStore(tmp_path / "state") def create(current, goal): return CampaignBatch( ordinal=len(current.batches) + 1, plan_name=current.next_plan_name(), goal=goal, task_count=1, ) def execute(_current, _batch): return True, ["task: passed"], "" def reflect(_current, batch, _summaries): return CampaignReflection( batch_ordinal=batch.ordinal, decision="continue", summary="One small follow-up remains.", next_goal=f"Implement bounded follow-up {batch.ordinal}.", ) result = run_campaign( state, store=store, create_batch=create, execute_batch=execute, reflect=reflect ) assert result.status is CampaignStatus.EXHAUSTED assert result.stop_reason == "Batch limit reached." assert len(result.batches) == 2 assert len(result.reflections) == 2 def test_campaign_rejects_a_repeated_follow_up_goal(tmp_path: Path) -> None: state = _campaign(tmp_path, max_batches=3) store = CampaignStore(tmp_path / "state") def create(current, goal): return CampaignBatch( ordinal=len(current.batches) + 1, plan_name=current.next_plan_name(), goal=goal, task_count=1, ) def execute(_current, _batch): return True, ["task: passed"], "" def reflect(_current, batch, _summaries): return CampaignReflection( batch_ordinal=batch.ordinal, decision="continue", summary="Keep going.", next_goal="Implement the same thing again.", ) result = run_campaign( state, store=store, create_batch=create, execute_batch=execute, reflect=reflect ) assert result.status is CampaignStatus.ESCALATED assert result.stop_reason == "Checkpoint proposed an empty or repeated follow-up goal." assert len(result.batches) == 2 assert len(result.reflections) == 1 def test_campaign_applies_only_creator_approved_corpus_policy(tmp_path: Path) -> None: campaign = _campaign(tmp_path) campaign.acceptance_profile = AcceptanceProfile.CORPUS_RAW_OUTPUT.value campaign.evidence_roots = [str(tmp_path / "corpus")] plan = TaskPlan( project_name="batch", goal="Use the approved corpus only.", intent="implement", tasks=[ TaskNode(id="discover", title="Discover", description="Read", read_only=True), TaskNode( id="implement", title="Implement", description="Write", dependencies=["discover"], ), ], ) apply_campaign_policy(plan, campaign) discovery, implementation = plan.tasks assert discovery.acceptance_profile is AcceptanceProfile.NONE assert implementation.acceptance_profile is AcceptanceProfile.CORPUS_RAW_OUTPUT assert discovery.evidence_roots == campaign.evidence_roots assert implementation.evidence_roots == campaign.evidence_roots assert implementation.max_changed_files == campaign.limits.max_changed_files_per_task assert implementation.max_changed_lines == campaign.limits.max_changed_lines_per_task assert implementation.require_raw_contract_artifacts assert implementation.discard_branch_on_failure def test_campaign_allows_none_profile_evidence_roots_for_read_only_batch(tmp_path: Path) -> None: campaign = _campaign(tmp_path) campaign.evidence_roots = [str(tmp_path / "corpus")] plan = TaskPlan( project_name="batch", goal="Read an approved corpus only.", intent="audit", tasks=[TaskNode(id="discover", title="Discover", description="Read", read_only=True)], ) apply_campaign_policy(plan, campaign) task = plan.tasks[0] assert task.acceptance_profile is AcceptanceProfile.NONE assert task.evidence_roots == campaign.evidence_roots def test_campaign_rejects_none_profile_evidence_roots_for_mutable_batch(tmp_path: Path) -> None: campaign = _campaign(tmp_path) campaign.evidence_roots = [str(tmp_path / "corpus")] plan = TaskPlan( project_name="batch", goal="Do not expose external evidence to a mutable task.", intent="implement", tasks=[ TaskNode(id="discover", title="Discover", description="Read", read_only=True), TaskNode(id="implement", title="Implement", description="Write"), ], ) with pytest.raises(ValueError, match="every generated task is read-only"): apply_campaign_policy(plan, campaign) assert all(not task.evidence_roots for task in plan.tasks) def test_campaign_store_prevents_a_second_live_runner(tmp_path: Path) -> None: store = CampaignStore(tmp_path / "state") lock = store.acquire_run_lock("one") with pytest.raises(CampaignBusyError): store.acquire_run_lock("one") store.release_run_lock(lock) replacement = store.acquire_run_lock("one") store.release_run_lock(replacement) def test_campaign_store_reclaims_a_lock_whose_pid_was_recycled(tmp_path: Path) -> None: """A dead owner's PID can be reassigned; the start token must expose that.""" store = CampaignStore(tmp_path / "state") lock = store.acquire_run_lock("one") recorded = lock.read_text(encoding="utf-8").split("\n") assert int(recorded[0]) == os.getpid() lock.write_text(f"{recorded[0]}\nnot-the-original-start-token", encoding="utf-8") reclaimed = store.acquire_run_lock("one") store.release_run_lock(reclaimed) def test_owner_still_running_distinguishes_a_recycled_pid() -> None: live = os.getpid() genuine = campaign_store._process_start_token(live) assert campaign_store._owner_still_running(live, genuine) assert not campaign_store._owner_still_running(live, "start-token-of-a-dead-process") # A legacy lock file records no token, so PID liveness remains the only signal. assert campaign_store._owner_still_running(live, "") def test_process_start_token_is_stable_and_absent_for_dead_pids() -> None: live = os.getpid() assert campaign_store._process_start_token(live) assert campaign_store._process_start_token(live) == campaign_store._process_start_token(live) assert campaign_store._process_start_token(-1) == "" def test_campaign_store_honors_a_legacy_pid_only_lock(tmp_path: Path) -> None: store = CampaignStore(tmp_path / "state") lock = store.acquire_run_lock("one") lock.write_text(str(os.getpid()), encoding="utf-8") with pytest.raises(CampaignBusyError): store.acquire_run_lock("one") store.release_run_lock(lock) def _attempt( attempt_id: str, role: str, *, tokens: int = 0, calls: int = 0, ) -> TaskAttempt: return TaskAttempt( id=attempt_id, role=role, endpoint="copilot", model="gpt-test", selection_reason="test", usage_delta=AttemptUsage( prompt_tokens=tokens, completion_tokens=tokens // 2, total_tokens=tokens + tokens // 2, api_calls=calls, agent_turns=calls, copilot_prompts_submitted=calls, copilot_nano_aiu=float(calls * 1_000_000_000), ), ) def _plan(name: str, *tasks: TaskNode) -> TaskPlan: return TaskPlan(project_name=name, goal="campaign test", intent="implement", tasks=list(tasks)) def _campaign_statistics_state(tmp_path: Path) -> CampaignState: campaign = _campaign(tmp_path, max_batches=3) campaign.status = CampaignStatus.COMPLETED campaign.batches = [ CampaignBatch( ordinal=1, plan_name="nightly-work-batch-001", goal="one", task_count=1, completed=True ), CampaignBatch( ordinal=2, plan_name="nightly-work-batch-002", goal="two", task_count=1, completed=True ), ] return campaign def test_campaign_statistics_totals_two_completed_persisted_batches(tmp_path: Path) -> None: campaign = _campaign_statistics_state(tmp_path) plans = { "nightly-work-batch-001": _plan( "nightly-work-batch-001", TaskNode( id="first", title="First", description="", status=TaskStatus.PASSED, attempts=[_attempt("a1", "coder", tokens=10, calls=1)], ), ), "nightly-work-batch-002": _plan( "nightly-work-batch-002", TaskNode( id="second", title="Second", description="", status=TaskStatus.PASSED, attempts=[_attempt("a2", "validator", tokens=20, calls=2)], ), ), } statistics = build_campaign_statistics(campaign, plans.get) assert statistics.batches_completed == 2 assert statistics.tasks_planned == 2 assert statistics.tasks_passed == 2 assert statistics.attempts == 2 assert statistics.role_attempts == {"coder": 1, "validator": 1} assert statistics.usage.api_calls == 3 assert statistics.usage.total_tokens == 45 assert len(statistics.batches) == 2 assert [batch.usage.api_calls for batch in statistics.batches] == [1, 2] def test_campaign_statistics_survive_a_new_process_resume(tmp_path: Path) -> None: campaign = _campaign_statistics_state(tmp_path) campaign.created_at = datetime.now(timezone.utc) - timedelta(minutes=5) plan = _plan( "nightly-work-batch-001", TaskNode( id="first", title="First", description="", status=TaskStatus.PASSED, attempts=[_attempt("a1", "coder", tokens=9, calls=1)], ), ) second = _plan( "nightly-work-batch-002", TaskNode( id="second", title="Second", description="", status=TaskStatus.PASSED, attempts=[_attempt("a2", "researcher", tokens=7, calls=1)], ), ) # Simulate a fresh process loading only JSON persisted by the prior run. resumed_campaign = CampaignState.model_validate_json(campaign.model_dump_json()) resumed_plans = { plan.project_name: TaskPlan.model_validate_json(plan.model_dump_json()), second.project_name: TaskPlan.model_validate_json(second.model_dump_json()), } statistics = build_campaign_statistics(resumed_campaign, resumed_plans.get) assert statistics.tasks_passed == 2 assert statistics.attempts == 2 assert statistics.usage.prompt_tokens == 16 assert statistics.elapsed_wall_seconds is not None assert statistics.elapsed_wall_seconds >= 300 def test_campaign_statistics_count_retries_once_each_and_are_idempotent(tmp_path: Path) -> None: campaign = _campaign_statistics_state(tmp_path) campaign.batches = campaign.batches[:1] retrying_task = TaskNode( id="retrying", title="Retrying", description="", status=TaskStatus.PASSED, attempts=[ _attempt("initial", "coder", tokens=5, calls=1), _attempt("retry", "coder", tokens=8, calls=1), ], ) plans = {"nightly-work-batch-001": _plan("nightly-work-batch-001", retrying_task)} first = build_campaign_statistics(campaign, plans.get) repeated_status_call = build_campaign_statistics(campaign, plans.get) assert first.attempts == repeated_status_call.attempts == 2 assert first.usage.total_tokens == repeated_status_call.usage.total_tokens == 19 assert first.role_attempts == {"coder": 2} def test_campaign_statistics_counts_decomposed_tasks(tmp_path: Path) -> None: campaign = _campaign_statistics_state(tmp_path) parent = TaskNode( id="stuck", title="Stuck", description="", status=TaskStatus.DECOMPOSED, subtask_ids=["stuck-sub-1", "stuck-sub-2"], ) subtask = TaskNode( id="stuck-sub-1", title="Sub 1", description="", status=TaskStatus.PASSED, parent_task_id="stuck", ) plans = { "nightly-work-batch-001": _plan("nightly-work-batch-001", parent, subtask), "nightly-work-batch-002": _plan( "nightly-work-batch-002", TaskNode(id="second", title="Second", description="", status=TaskStatus.PASSED), ), } statistics = build_campaign_statistics(campaign, plans.get) assert statistics.tasks_decomposed == 1 assert statistics.batches[0].decomposed_tasks == 1 def test_campaign_statistics_deduplicates_stable_attempt_ids_across_batches(tmp_path: Path) -> None: campaign = _campaign_statistics_state(tmp_path) shared = _attempt("stable-id", "coder", tokens=9, calls=1) plans = { "nightly-work-batch-001": _plan( "nightly-work-batch-001", TaskNode( id="first", title="First", description="", status=TaskStatus.PASSED, attempts=[shared], ), ), "nightly-work-batch-002": _plan( "nightly-work-batch-002", TaskNode( id="duplicate", title="Duplicate", description="", status=TaskStatus.PASSED, attempts=[shared.model_copy()], ), ), } statistics = build_campaign_statistics(campaign, plans.get) assert statistics.attempts == 1 assert statistics.usage.api_calls == 1 assert [batch.attempts for batch in statistics.batches] == [1, 0] def test_campaign_statistics_include_failed_and_escalated_attempt_costs(tmp_path: Path) -> None: campaign = _campaign_statistics_state(tmp_path) campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = "Manual retry required" plans = { "nightly-work-batch-001": _plan( "nightly-work-batch-001", TaskNode( id="failed", title="Failed", description="", status=TaskStatus.FAILED, attempts=[_attempt("failed-a", "coder", tokens=4, calls=1)], ), ), "nightly-work-batch-002": _plan( "nightly-work-batch-002", TaskNode( id="stopped", title="Stopped", description="", status=TaskStatus.ESCALATED, attempts=[_attempt("escalated-a", "researcher", tokens=6, calls=2)], ), ), } statistics = build_campaign_statistics(campaign, plans.get) assert statistics.tasks_failed == 1 assert statistics.tasks_escalated == 1 assert statistics.usage.api_calls == 3 assert statistics.usage.prompt_tokens == 10 def test_campaign_statistics_represent_not_applicable_and_missing_usage_as_zero( tmp_path: Path, ) -> None: campaign = _campaign_statistics_state(tmp_path) campaign.batches = campaign.batches[:1] historical_attempt = TaskAttempt( id="historical", role="validator", endpoint="copilot", model="gpt-test", selection_reason="legacy", ) plans = { "nightly-work-batch-001": _plan( "nightly-work-batch-001", TaskNode(id="na", title="N/A", description="", status=TaskStatus.NOT_APPLICABLE), TaskNode( id="legacy", title="Legacy", description="", status=TaskStatus.PASSED, attempts=[historical_attempt], ), ) } statistics = build_campaign_statistics(campaign, plans.get) assert statistics.tasks_not_applicable == 1 assert statistics.tasks_passed == 1 assert statistics.attempts == 1 assert statistics.usage.model_dump() == AttemptUsage().model_dump() @pytest.mark.parametrize("status", [CampaignStatus.COMPLETED, CampaignStatus.ESCALATED]) def test_campaign_statistics_output_for_terminal_campaigns( tmp_path: Path, capsys, status: CampaignStatus ) -> None: campaign = _campaign_statistics_state(tmp_path) campaign.status = status campaign.stop_reason = ( "Checkpoint complete" if status is CampaignStatus.COMPLETED else "Manual retry required" ) report_campaign_statistics(build_campaign_statistics(campaign, lambda _name: None)) output = capsys.readouterr().out assert "Campaign Statistics" in output assert status.value in output assert "not an invoice" in output assert "not necessarily" in output # --------------------------------------------------------------------------- # Durable single-queue campaign continuation (continue_campaign_once / # run_campaign_queue_until_terminal). These are pure-logic tests: the queue # plan is round-tripped through real JSON (de)serialization on every # ensure_queue/persist_queue call, exactly like the CLI's saved-plan file, so # a "crash" can be simulated by simply not persisting a mutation. # --------------------------------------------------------------------------- class _QueueHarness: """Durable-ish in-memory stand-in for the CLI's saved queue plan file.""" def __init__(self, plan: TaskPlan, *, results: dict[str, TaskStatus] | None = None) -> None: self._serialized = plan.model_dump_json() self.results = results or {} self.crash_before_finish: set[str] = set() self.lease_seconds = 60 self.run_calls: list[str] = [] self.ensure_calls = 0 self.persist_calls = 0 def ensure_queue(self, _campaign: CampaignState) -> TaskPlan: self.ensure_calls += 1 return TaskPlan.model_validate_json(self._serialized) def persist_queue(self, _campaign: CampaignState, plan: TaskPlan) -> None: self.persist_calls += 1 self._serialized = plan.model_dump_json() def run_ready_task(self, campaign: CampaignState, plan: TaskPlan, task: TaskNode) -> None: self.run_calls.append(task.id) target = next(item for item in plan.tasks if item.id == task.id) now = datetime.now(timezone.utc) target.status = TaskStatus.IN_PROGRESS target.leased_at = now target.lease_expires_at = now + timedelta(seconds=self.lease_seconds) target.lease_owner = "worker-1" self.persist_queue(campaign, plan) if task.id in self.crash_before_finish: # Simulate the owning process dying mid-sprint: the lease is # already durably persisted as IN_PROGRESS, but nothing finishes. return target.status = self.results.get(task.id, TaskStatus.PASSED) if target.status is TaskStatus.FAILED and target.retry_count == 0: target.retry_count = 1 target.leased_at = None target.lease_expires_at = None target.lease_owner = "" self.persist_queue(campaign, plan) def test_continue_campaign_once_selects_highest_priority_ready_task_with_dependencies( tmp_path: Path, ) -> None: campaign = _campaign(tmp_path) store = CampaignStore(tmp_path / "state") plan = _plan( "queue", TaskNode(id="setup", title="Setup", description="", priority=TaskPriority.INFRASTRUCTURE), TaskNode( id="feature-a", title="A", description="", dependencies=["setup"], priority=TaskPriority.FEATURE, ), TaskNode( id="feature-b", title="B", description="", dependencies=["setup"], priority=TaskPriority.CRITICAL_BUG, ), ) harness = _QueueHarness(plan) first = continue_campaign_once( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, ) assert first.task_id == "setup" second = continue_campaign_once( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, ) # feature-b outranks feature-a once both become ready. assert second.task_id == "feature-b" assert harness.run_calls == ["setup", "feature-b"] def test_continue_campaign_once_dispatches_up_to_max_workers_ready_tasks_concurrently( tmp_path: Path, ) -> None: campaign = _campaign(tmp_path) store = CampaignStore(tmp_path / "state") plan = _plan( "queue", TaskNode(id="independent-a", title="A", description=""), TaskNode(id="independent-b", title="B", description=""), TaskNode(id="independent-c", title="C", description=""), ) harness = _QueueHarness(plan) result = continue_campaign_once( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, max_workers=2, ) assert sorted(result.task_ids) == ["independent-a", "independent-b"] assert result.task_id == "independent-a" assert sorted(harness.run_calls) == ["independent-a", "independent-b"] assert campaign.queue_steps_taken == 2 final = continue_campaign_once( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, max_workers=2, ) assert final.queue_complete assert final.task_ids == ["independent-c"] def test_continue_campaign_once_default_max_workers_matches_original_single_task_behavior( tmp_path: Path, ) -> None: campaign = _campaign(tmp_path) store = CampaignStore(tmp_path / "state") plan = _plan( "queue", TaskNode(id="independent-a", title="A", description=""), TaskNode(id="independent-b", title="B", description=""), ) harness = _QueueHarness(plan) result = continue_campaign_once( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, ) assert result.task_id == "independent-a" assert result.task_ids == ["independent-a"] assert harness.run_calls == ["independent-a"] assert campaign.queue_steps_taken == 1 def test_continue_campaign_once_completes_the_queue(tmp_path: Path) -> None: campaign = _campaign(tmp_path) store = CampaignStore(tmp_path / "state") plan = _plan("queue", TaskNode(id="only", title="Only", description="")) harness = _QueueHarness(plan) result = continue_campaign_once( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, ) assert result.task_id == "only" assert campaign.status is CampaignStatus.RUNNING final = continue_campaign_once( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, ) assert final.queue_complete assert campaign.status is CampaignStatus.COMPLETED def test_terminal_campaign_is_a_no_op_and_never_touches_the_queue(tmp_path: Path) -> None: campaign = _campaign(tmp_path) campaign.status = CampaignStatus.COMPLETED store = CampaignStore(tmp_path / "state") plan = _plan("queue", TaskNode(id="only", title="Only", description="")) harness = _QueueHarness(plan) result = continue_campaign_once( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, ) assert result.queue_complete assert harness.ensure_calls == 0 assert harness.run_calls == [] def test_reap_expired_leases_returns_an_abandoned_task_to_pending() -> None: now = datetime.now(timezone.utc) plan = _plan( "queue", TaskNode( id="stuck", title="Stuck", description="", status=TaskStatus.IN_PROGRESS, leased_at=now - timedelta(hours=1), lease_expires_at=now - timedelta(minutes=1), lease_owner="dead-worker", ), ) reaped = reap_expired_leases(plan, now=now) assert reaped == ["stuck"] task = plan.tasks[0] assert task.status is TaskStatus.PENDING assert task.lease_expires_at is None assert task.lease_owner == "" def test_reap_expired_leases_leaves_an_active_lease_alone() -> None: now = datetime.now(timezone.utc) plan = _plan( "queue", TaskNode( id="active", title="Active", description="", status=TaskStatus.IN_PROGRESS, leased_at=now, lease_expires_at=now + timedelta(minutes=10), lease_owner="live-worker", ), ) assert reap_expired_leases(plan, now=now) == [] assert plan.tasks[0].status is TaskStatus.IN_PROGRESS def test_crash_mid_sprint_is_recovered_on_the_next_step_without_duplicating_a_pass( tmp_path: Path, ) -> None: """A process that dies mid-sprint leaves a durable, expiring lease. The next call (simulating a fresh process/run) must not treat the task as done, must not run a second concurrent sprint while the lease is still live, and must complete it exactly once once the lease has expired. """ campaign = _campaign(tmp_path) store = CampaignStore(tmp_path / "state") plan = _plan("queue", TaskNode(id="only", title="Only", description="")) harness = _QueueHarness(plan) harness.lease_seconds = 60 harness.crash_before_finish.add("only") crashed = continue_campaign_once( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, ) assert crashed.task_id == "only" assert harness.run_calls == ["only"] # Immediately after the crash, the lease has not expired: nothing is ready. still_leased = continue_campaign_once( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, now=datetime.now(timezone.utc), ) assert still_leased.stalled assert harness.run_calls == ["only"] # Once the lease has expired, the abandoned task is reaped and re-run once. harness.crash_before_finish.discard("only") recovered = continue_campaign_once( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, now=datetime.now(timezone.utc) + timedelta(seconds=120), ) assert recovered.reaped_lease_task_ids == ["only"] assert recovered.task_id == "only" assert recovered.queue_complete assert harness.run_calls == ["only", "only"] def test_incomplete_sprint_leaves_the_task_retrying_and_selected_again(tmp_path: Path) -> None: campaign = _campaign(tmp_path) store = CampaignStore(tmp_path / "state") plan = _plan("queue", TaskNode(id="flaky", title="Flaky", description="")) harness = _QueueHarness(plan, results={"flaky": TaskStatus.FAILED}) first = continue_campaign_once( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, ) assert first.task_status == TaskStatus.FAILED.value # A FAILED task with retries remaining is still ready; it must never be # marked complete based only on the sprint's own report. harness.results["flaky"] = TaskStatus.PASSED second = continue_campaign_once( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, ) assert second.task_id == "flaky" assert second.task_status == TaskStatus.PASSED.value assert second.queue_complete assert harness.run_calls == ["flaky", "flaky"] def test_run_until_terminal_stops_at_the_queue_step_budget(tmp_path: Path) -> None: campaign = _campaign(tmp_path, max_queue_steps=1) store = CampaignStore(tmp_path / "state") plan = _plan( "queue", TaskNode(id="one", title="One", description=""), TaskNode(id="two", title="Two", description=""), ) harness = _QueueHarness(plan) result = run_campaign_queue_until_terminal( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, consult_stall=lambda *_args: pytest.fail("Terra must not be consulted for a budget stop"), ) assert result.status is CampaignStatus.EXHAUSTED assert "budget" in result.stop_reason.lower() assert len(harness.run_calls) == 1 def test_run_until_terminal_stops_at_the_active_time_budget(tmp_path: Path) -> None: campaign = _campaign(tmp_path) campaign.limits.max_active_seconds = 60 campaign.active_seconds = 60.0 store = CampaignStore(tmp_path / "state") plan = _plan("queue", TaskNode(id="one", title="One", description="")) harness = _QueueHarness(plan) result = run_campaign_queue_until_terminal( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, consult_stall=lambda *_args: pytest.fail("Terra must not be consulted for a budget stop"), ) assert result.status is CampaignStatus.EXHAUSTED assert harness.run_calls == [] def test_run_until_terminal_completes_the_whole_queue_without_consulting_terra( tmp_path: Path, ) -> None: campaign = _campaign(tmp_path) store = CampaignStore(tmp_path / "state") plan = _plan( "queue", TaskNode(id="first", title="First", description=""), TaskNode(id="second", title="Second", description="", dependencies=["first"]), ) harness = _QueueHarness(plan) result = run_campaign_queue_until_terminal( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, consult_stall=lambda *_args: pytest.fail("A clean run must never need Terra"), ) assert result.status is CampaignStatus.COMPLETED assert harness.run_calls == ["first", "second"] def test_run_until_terminal_consults_terra_once_and_unblocks_a_failed_task( tmp_path: Path, ) -> None: campaign = _campaign(tmp_path) store = CampaignStore(tmp_path / "state") plan = _plan("queue", TaskNode(id="stuck", title="Stuck", description="", max_retries=0)) harness = _QueueHarness(plan, results={"stuck": TaskStatus.ESCALATED}) consult_calls: list[str] = [] def consult_stall(_campaign: CampaignState, queue_plan: TaskPlan) -> StallDecision: consult_calls.append("called") harness.results["stuck"] = TaskStatus.PASSED return StallDecision( decision="retry_task", task_id="stuck", note="Try a narrower approach.", summary="" ) result = run_campaign_queue_until_terminal( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, consult_stall=consult_stall, ) assert result.status is CampaignStatus.COMPLETED assert consult_calls == ["called"] assert harness.run_calls == ["stuck", "stuck"] def test_run_until_terminal_escalates_when_terra_cannot_unblock(tmp_path: Path) -> None: campaign = _campaign(tmp_path) store = CampaignStore(tmp_path / "state") plan = _plan("queue", TaskNode(id="stuck", title="Stuck", description="", max_retries=0)) harness = _QueueHarness(plan, results={"stuck": TaskStatus.ESCALATED}) consult_calls: list[str] = [] def consult_stall(_campaign: CampaignState, _queue_plan: TaskPlan) -> StallDecision: consult_calls.append("called") return StallDecision(decision="escalate", summary="A human must review this failure.") result = run_campaign_queue_until_terminal( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, consult_stall=consult_stall, ) assert result.status is CampaignStatus.ESCALATED assert result.stop_reason == "A human must review this failure." assert consult_calls == ["called"] def test_run_until_terminal_never_consults_terra_twice_for_the_same_stalled_state( tmp_path: Path, ) -> None: campaign = _campaign(tmp_path) store = CampaignStore(tmp_path / "state") plan = _plan("queue", TaskNode(id="stuck", title="Stuck", description="", max_retries=0)) harness = _QueueHarness(plan, results={"stuck": TaskStatus.ESCALATED}) consult_calls: list[str] = [] def consult_stall(_campaign: CampaignState, _queue_plan: TaskPlan) -> StallDecision: consult_calls.append("called") # A decision that cannot actually unblock anything (task ineligible). return StallDecision(decision="retry_task", task_id="does-not-exist", summary="") result = run_campaign_queue_until_terminal( campaign, store=store, ensure_queue=harness.ensure_queue, run_ready_task=harness.run_ready_task, persist_queue=harness.persist_queue, consult_stall=consult_stall, ) assert result.status is CampaignStatus.ESCALATED assert len(consult_calls) == 1 def test_apply_stall_decision_is_bounded_to_one_retry_per_task() -> None: plan = _plan( "queue", TaskNode(id="stuck", title="Stuck", description="", status=TaskStatus.ESCALATED), ) decision = StallDecision(decision="retry_task", task_id="stuck", note="Narrow the scope.") assert apply_stall_decision(plan, decision) is True task = plan.tasks[0] assert task.status is TaskStatus.PENDING assert task.terra_stall_retries_remaining == 0 assert "Narrow the scope." in task.failure_detail # The counter is exhausted: an identical decision cannot unblock it again. task.status = TaskStatus.ESCALATED assert apply_stall_decision(plan, decision) is False def test_apply_stall_decision_ignores_an_escalate_decision() -> None: plan = _plan( "queue", TaskNode(id="stuck", title="Stuck", description="", status=TaskStatus.ESCALATED), ) assert apply_stall_decision(plan, StallDecision(decision="escalate", summary="x")) is False assert plan.tasks[0].status is TaskStatus.ESCALATED def test_cancelled_campaign_is_treated_as_terminal() -> None: assert CampaignStatus.CANCELLED in TERMINAL_CAMPAIGN_STATUSES # --------------------------------------------------------------------------- # Phase roadmaps + plan-first approval (Stage 2) # --------------------------------------------------------------------------- def _fake_reasoner_registry(responses: list[str]): """Build a BackendRegistry-shaped fake whose get_reasoner() returns canned JSON.""" backend = FakeReasonerBackend(responses) class _Registry: def __init__(self, _config) -> None: pass def get_reasoner(self) -> FakeReasonerBackend: return backend return _Registry, backend def test_phase_state_defaults_to_planned_with_no_plan() -> None: phase = PhaseState(ordinal=1, name="Bootstrap", goal="Set up the project.") assert phase.status is PhaseStatus.PLANNED assert phase.plan_name == "" assert phase.summary == "" assert phase.task_ids == [] assert phase.acceptance_criteria == [] def test_completed_phase_dependencies_preserve_local_and_unknown_edges() -> None: plan = _plan( "phase-two", TaskNode( id="add-ignore-contract", title="Add ignore contract", description="Add ignore rules.", dependencies=["bootstrap-package", "unknown-task"], ), TaskNode( id="document-foundation", title="Document foundation", description="Document the project.", dependencies=["bootstrap-package", "add-ignore-contract"], ), ) _drop_completed_phase_dependencies(plan, {"bootstrap-package", "add-ignore-contract"}) assert plan.tasks[0].dependencies == ["unknown-task"] assert plan.tasks[1].dependencies == ["add-ignore-contract"] def _divergence_phase(**overrides) -> PhaseState: defaults = { "ordinal": 2, "name": "Contracts", "goal": "Add repository contracts.", "task_sketch": ["add-ignore-contract", "document-foundation"], } return PhaseState(**{**defaults, **overrides}) def test_phase_divergence_within_budget_is_recorded_not_raised(tmp_path: Path) -> None: campaign = _campaign(tmp_path) phase = _divergence_phase() plan = _plan( "grown", TaskNode(id="add-ignore-contract", title="Ignore", description="Add ignore rules."), TaskNode(id="document-foundation", title="Docs", description="Add documentation."), TaskNode(id="handle-residual", title="Residual", description="Work nobody predicted."), ) _record_phase_divergence(Config(), campaign, plan, phase) assert phase.task_ids == ["add-ignore-contract", "document-foundation", "handle-residual"] assert "planned 3 tasks against a roadmap sketch of 2 (+1)" in phase.divergence_note assert "handle-residual" in phase.divergence_note findings = LedgerStore(Config().projects_dir).load(plan.effective_ledger_name).findings assert any("handle-residual" in entry.observed for entry in findings) def test_phase_divergence_beyond_budget_escalates(tmp_path: Path) -> None: campaign = _campaign(tmp_path) campaign.limits.phase_divergence_budget = 1 phase = _divergence_phase() plan = _plan( "runaway", *[ TaskNode(id=f"task-{index}", title=f"T{index}", description="Discovered work.") for index in range(5) ], ) with pytest.raises(click.ClickException, match="exceeds the phase divergence budget of 1"): _record_phase_divergence(Config(), campaign, plan, phase) def test_phase_divergence_is_silent_when_the_plan_matches_the_sketch(tmp_path: Path) -> None: campaign = _campaign(tmp_path) phase = _divergence_phase() plan = _plan( "matching", TaskNode(id="add-ignore-contract", title="Ignore", description="Add ignore rules."), TaskNode(id="document-foundation", title="Docs", description="Add documentation."), ) _record_phase_divergence(Config(), campaign, plan, phase) assert phase.divergence_note == "" assert LedgerStore(Config().projects_dir).load(plan.effective_ledger_name).findings == [] def test_phase_divergence_without_a_sketch_only_records_actual_ids(tmp_path: Path) -> None: campaign = _campaign(tmp_path) phase = _divergence_phase(task_sketch=[]) plan = _plan("free", TaskNode(id="only", title="Only", description="Sole task.")) _record_phase_divergence(Config(), campaign, plan, phase) assert phase.task_ids == ["only"] assert phase.divergence_note == "" def test_campaign_state_active_phase_and_phase_after_navigate_in_order(tmp_path: Path) -> None: campaign = _campaign(tmp_path) campaign.phases = [ PhaseState(ordinal=1, name="One", goal="First.", status=PhaseStatus.COMPLETED), PhaseState(ordinal=2, name="Two", goal="Second.", status=PhaseStatus.ACTIVE), PhaseState(ordinal=3, name="Three", goal="Third."), ] assert campaign.active_phase().ordinal == 2 assert campaign.phase_after(2).ordinal == 3 assert campaign.phase_after(3) is None assert not campaign.all_phases_resolved() campaign.phases[1].status = PhaseStatus.COMPLETED campaign.phases[2].status = PhaseStatus.SKIPPED assert campaign.active_phase() is None assert campaign.all_phases_resolved() def test_old_saved_campaign_json_without_phase_fields_still_loads(tmp_path: Path) -> None: """Migration safety: JSON persisted before Stage 2 has no phase fields at all.""" legacy_json = json.dumps( { "name": "legacy-campaign", "project_dir": str(tmp_path), "root_goal": "Pre-existing campaign saved before phases existed.", } ) restored = CampaignState.model_validate_json(legacy_json) assert restored.phases == [] assert restored.plan_approved is False assert restored.ever_approved is False assert restored.roadmap_fingerprint == "" assert restored.approve_each_phase is False assert restored.limits.max_phases == 8 assert restored.limits.max_tasks_per_phase == 20 assert restored.limits.max_decompositions == 6 assert restored.limits.max_subtasks_per_decomposition == 5 assert restored.limits.max_decomposition_depth == 1 def test_campaign_limits_default_decomposition_budgets() -> None: limits = CampaignLimits() assert limits.max_decompositions == 6 assert limits.max_subtasks_per_decomposition == 5 assert limits.max_decomposition_depth == 1 def test_plan_phase_roadmap_returns_ordered_phases(monkeypatch, tmp_path: Path) -> None: campaign = _campaign(tmp_path) registry, backend = _fake_reasoner_registry( [ json.dumps( { "phases": [ { "name": "Bootstrap", "goal": "Set up.", "task_ids": ["bootstrap"], "acceptance_criteria": ["CI green"], }, { "name": "Core", "goal": "Build core.", "task_ids": ["build-core"], "acceptance_criteria": [], }, { "name": "Polish", "goal": "Polish it.", "task_ids": ["polish"], "acceptance_criteria": ["Docs done"], }, ] } ) ] ) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) phases = plan_phase_roadmap(campaign, config=Config()) assert [phase.ordinal for phase in phases] == [1, 2, 3] assert [phase.name for phase in phases] == ["Bootstrap", "Core", "Polish"] assert [phase.task_sketch for phase in phases] == [["bootstrap"], ["build-core"], ["polish"]] # The sketch is advisory; nothing is claimed to be owned until expansion. assert all(phase.task_ids == [] for phase in phases) assert phases[0].acceptance_criteria == ["CI green"] assert all(phase.status is PhaseStatus.PLANNED for phase in phases) assert backend.requests def test_plan_phase_roadmap_rejects_too_few_phases(monkeypatch, tmp_path: Path) -> None: campaign = _campaign(tmp_path) registry, _backend = _fake_reasoner_registry( [json.dumps({"phases": [{"name": "Only", "goal": "Do it all."}]})] ) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) with pytest.raises(PhaseRoadmapError, match="3-10 phases"): plan_phase_roadmap(campaign, config=Config()) def test_plan_phase_roadmap_rejects_a_phase_missing_a_goal(monkeypatch, tmp_path: Path) -> None: campaign = _campaign(tmp_path) raw_phases = [ {"name": f"Phase {i}", "goal": "Do work.", "task_ids": [f"task-{i}"]} for i in range(1, 4) ] raw_phases[-1] = {"name": "Broken"} registry, _backend = _fake_reasoner_registry([json.dumps({"phases": raw_phases})]) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) with pytest.raises(PhaseRoadmapError, match="missing a name or goal"): plan_phase_roadmap(campaign, config=Config()) def test_phase_roadmap_requires_unique_task_ownership(monkeypatch, tmp_path: Path) -> None: campaign = _campaign(tmp_path) registry, _backend = _fake_reasoner_registry( [ json.dumps( { "phases": [ {"name": "One", "goal": "First.", "task_ids": ["shared"]}, {"name": "Two", "goal": "Second.", "task_ids": ["shared"]}, {"name": "Three", "goal": "Third.", "task_ids": ["last"]}, ] } ) ] ) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) phases = plan_phase_roadmap(campaign, config=Config()) # A repeated sketch entry is a weak roadmap, not an unusable one: the sketch # binds nothing, so it is deduplicated rather than rejected. assert [phase.task_sketch for phase in phases] == [["shared"], [], ["last"]] def test_phase_roadmap_fingerprint_is_stable_and_sensitive_to_changes() -> None: phases = [ PhaseState( ordinal=1, name="One", goal="First.", task_sketch=["one"], acceptance_criteria=["a"], ), PhaseState(ordinal=2, name="Two", goal="Second.", task_sketch=["two"]), ] same_phases = [phase.model_copy() for phase in phases] changed = [phases[0].model_copy(update={"goal": "Different."}), phases[1].model_copy()] assert phase_roadmap_fingerprint(phases) == phase_roadmap_fingerprint(same_phases) assert phase_roadmap_fingerprint(phases) != phase_roadmap_fingerprint(changed) changed_tasks = [phases[0].model_copy(update={"task_sketch": ["other"]}), phases[1]] assert phase_roadmap_fingerprint(phases) != phase_roadmap_fingerprint(changed_tasks) def test_phase_roadmap_fingerprint_covers_the_closure_metric_but_not_its_readings() -> None: metric = ClosureMetric(name="guards", command="count-guards", target=0) phase = PhaseState(ordinal=1, name="One", goal="First.", task_sketch=["one"]) measured = phase.model_copy(update={"closure_metric": metric}) without_metric = phase_roadmap_fingerprint([phase]) assert phase_roadmap_fingerprint([measured]) != without_metric weakened = measured.model_copy( update={"closure_metric": metric.model_copy(update={"target": 12})} ) assert phase_roadmap_fingerprint([weakened]) != phase_roadmap_fingerprint([measured]) # Recording a measurement is not a roadmap edit; the approval must survive it. read = measured.model_copy( update={"closure_metric": metric.model_copy(update={"start_value": 78, "last_value": 12})} ) assert phase_roadmap_fingerprint([read]) == phase_roadmap_fingerprint([measured]) def test_closure_metric_satisfaction_honours_direction() -> None: down = ClosureMetric(name="remaining", command="x", target=0) up = ClosureMetric(name="covered", command="x", target=256, direction="up") assert down.satisfied_by(0) and not down.satisfied_by(1) assert up.satisfied_by(256) and not up.satisfied_by(255) assert down.describe_target() == "<= 0" assert up.describe_target() == ">= 256" def _roadmap_with_metric(metric: object) -> str: phases = [ {"name": f"Phase {i}", "goal": "Do work.", "task_ids": [f"task-{i}"]} for i in range(1, 4) ] phases[0]["closure_metric"] = metric return json.dumps({"phases": phases}) def test_plan_phase_roadmap_parses_an_optional_closure_metric(monkeypatch, tmp_path: Path) -> None: campaign = _campaign(tmp_path) registry, _backend = _fake_reasoner_registry( [ _roadmap_with_metric( { "name": "mnemonic_guards_in_core", "command": '{python} -c "print(12)"', "target": 0, "direction": "DOWN", } ) ] ) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) phases = plan_phase_roadmap(campaign, config=Config()) metric = phases[0].closure_metric assert metric is not None assert metric.name == "mnemonic_guards_in_core" assert metric.command == '{python} -c "print(12)"' assert metric.target == 0 assert metric.direction == "down" assert metric.start_value is None assert phases[1].closure_metric is None @pytest.mark.parametrize( ("metric", "message"), [ ("count things", "not a JSON object"), ({"name": "guards"}, "needs a name and a command"), ({"name": "guards", "command": "x", "target": "0"}, "target must be an integer"), ({"name": "guards", "command": "x", "target": True}, "target must be an integer"), ({"name": "guards", "command": "x", "direction": "sideways"}, "direction must be"), ], ) def test_plan_phase_roadmap_rejects_a_malformed_closure_metric( monkeypatch, tmp_path: Path, metric: object, message: str ) -> None: campaign = _campaign(tmp_path) registry, _backend = _fake_reasoner_registry([_roadmap_with_metric(metric)]) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) with pytest.raises(PhaseRoadmapError, match=message): plan_phase_roadmap(campaign, config=Config()) def test_make_phase_batch_goal_makes_the_residual_the_planner_problem(tmp_path: Path) -> None: campaign = _campaign(tmp_path) metric = ClosureMetric(name="guards", command="count-guards", target=0, start_value=78) campaign.phases = [ PhaseState( ordinal=1, name="Extract", goal="Extract.", task_ids=["a"], closure_metric=metric ) ] goal = make_phase_batch_goal(campaign, campaign.phases[0]) assert "Phase closure metric: 'guards'" in goal assert "`count-guards`" in goal assert "reads <= 0" in goal assert "It currently reads 78." in goal assert "final task must own whatever residual" in goal campaign.phases[0].closure_metric = None assert "closure metric" not in make_phase_batch_goal(campaign, campaign.phases[0]) def test_reflect_on_completed_phase_can_complete(monkeypatch, tmp_path: Path) -> None: campaign = _campaign(tmp_path) phase = PhaseState(ordinal=1, name="Bootstrap", goal="Set up the project.") registry, _backend = _fake_reasoner_registry( [json.dumps({"decision": "complete_phase", "summary": "Bootstrap finished cleanly."})] ) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) reflection = reflect_on_completed_phase( campaign, phase, config=Config(), completed_task_summaries=["init: passed"] ) assert reflection.decision == "complete_phase" assert reflection.summary == "Bootstrap finished cleanly." assert reflection.revised_next_phase_goal == "" def test_reflect_on_completed_phase_revision_needs_a_substantial_goal( monkeypatch, tmp_path: Path ) -> None: campaign = _campaign(tmp_path) phase = PhaseState(ordinal=1, name="Bootstrap", goal="Set up the project.") registry, _backend = _fake_reasoner_registry( [ json.dumps( { "decision": "revise_future_phases", "summary": "Needs a tweak.", "revised_next_phase_goal": "short", } ) ] ) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) reflection = reflect_on_completed_phase( campaign, phase, config=Config(), completed_task_summaries=[] ) assert reflection.decision == "escalate" assert reflection.revised_next_phase_goal == "" def test_reflect_on_completed_phase_rejects_an_unsupported_decision( monkeypatch, tmp_path: Path ) -> None: campaign = _campaign(tmp_path) phase = PhaseState(ordinal=1, name="Bootstrap", goal="Set up the project.") registry, _backend = _fake_reasoner_registry([json.dumps({"decision": "add_more_phases"})]) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) reflection = reflect_on_completed_phase( campaign, phase, config=Config(), completed_task_summaries=[] ) assert reflection.decision == "escalate" def test_make_phase_batch_goal_includes_phase_goal_and_criteria(tmp_path: Path) -> None: campaign = _campaign( tmp_path, max_tasks_per_phase=10, max_changed_files_per_task=4, max_changed_lines_per_task=250, ) campaign.phases = [ PhaseState( ordinal=1, name="Bootstrap", goal="Stand up the scaffolding.", task_sketch=["bootstrap"], acceptance_criteria=["Tests run", "Lint passes"], ) ] goal = make_phase_batch_goal(campaign, campaign.phases[0]) assert "Stand up the scaffolding." in goal assert "Tests run" in goal # The t=0 sketch must never reach the planner: showing it a guess made # before any file was read turns that guess into an anchor. assert "bootstrap" not in goal assert "task list of 5-10 tasks" in goal assert "at most 4 changed files and 250 changed lines" in goal assert "Split any contract that cannot fit those limits" in goal def test_make_batch_goal_includes_mutation_limits(tmp_path: Path) -> None: campaign = _campaign( tmp_path, max_changed_files_per_task=3, max_changed_lines_per_task=175, ) goal = make_batch_goal(campaign) assert "at most 3 changed files and 175 changed lines" in goal assert "Split any contract that cannot fit those limits" in goal def _roadmap_campaign(tmp_path: Path) -> CampaignState: campaign = _campaign(tmp_path) campaign.closure_metric = ClosureMetric(name="root", command="count-root", target=0) campaign.phases = [ PhaseState(ordinal=1, name="One", goal="First.", status=PhaseStatus.COMPLETED), PhaseState(ordinal=2, name="Two", goal="Second.", status=PhaseStatus.COMPLETED), PhaseState(ordinal=3, name="Three", goal="Third."), PhaseState(ordinal=4, name="Four", goal="Fourth."), ] return campaign def _amendment(**overrides) -> PhaseAmendment: defaults = { "target_ordinal": 3, "operation": "revise_goal", "reason": "Phase 2 measured a residual nobody owns.", "goal": "Third, now covering the measured residual.", } return PhaseAmendment(**{**defaults, **overrides}) def test_phase_amendment_revises_a_planned_phase(tmp_path: Path) -> None: campaign = _roadmap_campaign(tmp_path) applied = apply_phase_amendments(campaign, [_amendment()]) assert campaign.phases[2].goal == "Third, now covering the measured residual." assert "revise_goal phase 3" in applied[0] assert len(campaign.phase_amendments) == 1 # The destination stays pinned while the path moves. assert campaign.closure_metric is not None and campaign.closure_metric.name == "root" def test_phase_amendment_adds_a_phase_and_renumbers_only_the_unstarted_tail( tmp_path: Path, ) -> None: campaign = _roadmap_campaign(tmp_path) addition = _amendment( operation="add", name="Residual", goal="Close the residual phase 2 uncovered.", closure_metric=ClosureMetric(name="residual", command="count-residual", target=0), ) apply_phase_amendments(campaign, [addition]) assert [phase.name for phase in campaign.phases] == ["One", "Two", "Three", "Residual", "Four"] assert [phase.ordinal for phase in campaign.phases] == [1, 2, 3, 4, 5] # Completed phases keep the ordinals their persisted plan files are keyed to. assert [phase.ordinal for phase in campaign.phases[:2]] == [1, 2] def test_phase_amendment_drops_a_phase_by_skipping_it(tmp_path: Path) -> None: campaign = _roadmap_campaign(tmp_path) apply_phase_amendments(campaign, [_amendment(operation="drop", target_ordinal=4)]) assert campaign.phases[3].status is PhaseStatus.SKIPPED assert "Skipped by phase amendment" in campaign.phases[3].summary def test_phase_amendment_refuses_to_touch_a_started_phase(tmp_path: Path) -> None: campaign = _roadmap_campaign(tmp_path) with pytest.raises(PhaseAmendmentError, match="only phases the campaign has not started"): apply_phase_amendments(campaign, [_amendment(target_ordinal=2)]) assert campaign.phases[1].goal == "Second." def test_phase_amendment_refuses_an_added_phase_with_no_closure_metric(tmp_path: Path) -> None: campaign = _roadmap_campaign(tmp_path) addition = _amendment(operation="add", name="Unmeasured", goal="Do some more work.") with pytest.raises(PhaseAmendmentError, match="no closure metric"): apply_phase_amendments(campaign, [addition]) def test_phase_amendment_batch_is_all_or_nothing(tmp_path: Path) -> None: campaign = _roadmap_campaign(tmp_path) good = _amendment() bad = _amendment(target_ordinal=1) with pytest.raises(PhaseAmendmentError): apply_phase_amendments(campaign, [good, bad]) assert campaign.phases[2].goal == "Third." assert campaign.phase_amendments == [] def test_phase_amendment_respects_its_budget(tmp_path: Path) -> None: campaign = _roadmap_campaign(tmp_path) campaign.limits.max_phase_amendments = 1 apply_phase_amendments(campaign, [_amendment()]) with pytest.raises(PhaseAmendmentError, match="exceed the budget"): apply_phase_amendments(campaign, [_amendment(target_ordinal=4)]) def test_phase_amendment_respects_max_phases(tmp_path: Path) -> None: campaign = _roadmap_campaign(tmp_path) campaign.limits.max_phases = 4 addition = _amendment( operation="add", name="Residual", goal="Close the residual.", closure_metric=ClosureMetric(name="residual", command="count-residual", target=0), ) with pytest.raises(PhaseAmendmentError, match="over the max_phases limit"): apply_phase_amendments(campaign, [addition]) def test_phase_amendment_rejects_two_changes_to_one_phase(tmp_path: Path) -> None: campaign = _roadmap_campaign(tmp_path) with pytest.raises(PhaseAmendmentError, match="at most once per checkpoint"): apply_phase_amendments(campaign, [_amendment(), _amendment(goal="Another revision.")]) def test_reflect_on_completed_phase_parses_a_reshape(monkeypatch, tmp_path: Path) -> None: campaign = _roadmap_campaign(tmp_path) registry, _backend = _fake_reasoner_registry( [ json.dumps( { "decision": "reshape_future_phases", "summary": "Phase 2 left a residual no later phase owns.", "amendments": [ { "operation": "add", "target_ordinal": 3, "reason": "The closure metric still reads 12 unhandled opcodes.", "name": "Residual opcodes", "goal": "Handle the 12 opcodes no family owns.", "closure_metric": { "name": "inline", "command": "count-inline", "target": 0, "direction": "down", }, } ], } ) ] ) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) reflection = reflect_on_completed_phase( campaign, campaign.phases[1], config=Config(), completed_task_summaries=["t: passed"] ) assert reflection.decision == "reshape_future_phases" assert len(reflection.amendments) == 1 assert reflection.amendments[0].operation == "add" assert reflection.amendments[0].closure_metric is not None def test_reflect_on_completed_phase_escalates_an_ungrounded_reshape( monkeypatch, tmp_path: Path ) -> None: campaign = _roadmap_campaign(tmp_path) registry, _backend = _fake_reasoner_registry( [ json.dumps( { "decision": "reshape_future_phases", "summary": "Something feels off.", "amendments": [ {"operation": "add", "target_ordinal": 3, "reason": "too short"} ], } ) ] ) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) reflection = reflect_on_completed_phase( campaign, campaign.phases[1], config=Config(), completed_task_summaries=[] ) assert reflection.decision == "escalate" assert reflection.amendments == [] assert "at least 20 characters" in reflection.summary def test_phase_checkpoint_sees_measured_evidence_not_just_task_text( monkeypatch, tmp_path: Path ) -> None: campaign = _roadmap_campaign(tmp_path) campaign.closure_metric.start_value = 100 campaign.closure_metric.last_value = 88 phase = campaign.phases[1] phase.closure_metric = ClosureMetric( name="guards", command="count-guards", target=0, start_value=78, last_value=71 ) phase.divergence_note = "Phase 2 planned 9 tasks against a sketch of 5 (+4)." ledger = CampaignLedger( name="example", findings=[ LedgerEntry( kind="finding", hypothesis="The dispatch chain is one family.", observed="It is three unrelated families.", ) ], ) registry, backend = _fake_reasoner_registry( [json.dumps({"decision": "complete_phase", "summary": "Fine."})] ) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) reflect_on_completed_phase( campaign, phase, config=Config(), completed_task_summaries=["t: passed"], ledger=ledger, divergence_note=phase.divergence_note, ) _system_prompt, prompt = backend.requests[0] assert "started at 78, now reads 71" in prompt assert "started at 100, now reads 88" in prompt assert "planned 9 tasks against a sketch of 5" in prompt assert "It is three unrelated families." in prompt def _closeout_fixtures(tmp_path: Path): """A campaign mid-roadmap with a persisted store, ready for phase close-out.""" config = Config(projects_dir=tmp_path / "state") store = CampaignStore(config.projects_dir) campaign = CampaignState( name="campaign", project_dir=tmp_path, root_goal="Extract every opcode family.", closure_metric=ClosureMetric( name="root", command="count-root", target=0, start_value=100, last_value=12 ), phases=[ PhaseState( ordinal=1, name="One", goal="First.", status=PhaseStatus.COMPLETED, plan_name="campaign-phase-001", ), PhaseState( ordinal=2, name="Two", goal="Second.", status=PhaseStatus.ACTIVE, plan_name="campaign-phase-002", closure_metric=ClosureMetric( name="inline", command="count-inline", target=0, start_value=78, last_value=12 ), ), PhaseState(ordinal=3, name="Three", goal="Third."), ], ) store.save(campaign) plan = _plan("campaign-phase-002", TaskNode(id="extract", title="Extract", description="Go.")) return config, store, campaign, plan def test_close_out_phase_reshapes_the_roadmap_end_to_end(monkeypatch, tmp_path: Path) -> None: config, store, campaign, plan = _closeout_fixtures(tmp_path) campaign.phases[1].divergence_note = "Phase 2 planned 9 tasks against a sketch of 5 (+4)." registry, backend = _fake_reasoner_registry( [ json.dumps( { "decision": "reshape_future_phases", "summary": "Twelve opcodes are owned by no planned phase.", "amendments": [ { "operation": "add", "target_ordinal": 3, "reason": "The closure metric still reads 12 unhandled opcodes.", "name": "Residual opcodes", "goal": "Handle the 12 opcodes no family owns.", "closure_metric": { "name": "residual", "command": "count-residual", "target": 0, "direction": "down", }, } ], } ) ] ) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) _campaign_close_out_phase(config, store, campaign, campaign.phases[1], plan) reloaded = store.load("campaign") assert [phase.name for phase in reloaded.phases] == ["One", "Two", "Three", "Residual opcodes"] assert [phase.ordinal for phase in reloaded.phases] == [1, 2, 3, 4] assert reloaded.phases[1].status is PhaseStatus.COMPLETED assert len(reloaded.phase_amendments) == 1 # The destination stays pinned across a reshape. assert reloaded.closure_metric.name == "root" # The checkpoint actually saw the measurements and the divergence. _system_prompt, prompt = backend.requests[0] assert "started at 78, now reads 12" in prompt assert "planned 9 tasks against a sketch of 5" in prompt findings = LedgerStore(config.projects_dir).load(plan.effective_ledger_name).findings assert any("add phase 3" in entry.observed for entry in findings) def test_close_out_phase_escalates_when_a_reshape_is_refused(monkeypatch, tmp_path: Path) -> None: config, store, campaign, plan = _closeout_fixtures(tmp_path) registry, _backend = _fake_reasoner_registry( [ json.dumps( { "decision": "reshape_future_phases", "summary": "Phase 1 should have done more.", "amendments": [ { "operation": "revise_goal", "target_ordinal": 1, "reason": "Phase 1 left work that later phases assume is done.", "goal": "First, but properly this time.", } ], } ) ] ) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) with pytest.raises(click.ClickException, match="roadmap reshape that was refused"): _campaign_close_out_phase(config, store, campaign, campaign.phases[1], plan) reloaded = store.load("campaign") assert reloaded.status is CampaignStatus.ESCALATED assert "only phases the campaign has not started" in reloaded.stop_reason # A completed phase is never rewritten, even by a refused amendment. assert reloaded.phases[0].goal == "First." assert reloaded.phase_amendments == [] def test_close_out_phase_still_takes_the_narrow_revision_path(monkeypatch, tmp_path: Path) -> None: config, store, campaign, plan = _closeout_fixtures(tmp_path) registry, _backend = _fake_reasoner_registry( [ json.dumps( { "decision": "revise_future_phases", "summary": "Phase 3 needs a narrower goal.", "revised_next_phase_goal": "Third, narrowed to what phase 2 actually left.", } ) ] ) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) _campaign_close_out_phase(config, store, campaign, campaign.phases[1], plan) reloaded = store.load("campaign") assert reloaded.phases[2].goal == "Third, narrowed to what phase 2 actually left." assert reloaded.phase_amendments == [] def test_roadmap_drops_prose_sketch_entries_rather_than_comparing_them( monkeypatch, tmp_path: Path ) -> None: """A prose sketch must degrade to no sketch, not to a meaningless delta. Observed live on the 6502 campaign: the reasoner answered task_sketch with two sentences describing a phase's work, the planner produced nine real task IDs, and the divergence check reported +7 -- a number comparing two lists that did not measure the same thing. """ campaign = _campaign(tmp_path) registry, _backend = _fake_reasoner_registry( [ json.dumps( { "phases": [ { "name": "Hygiene", "goal": "Set up.", "task_sketch": [ "Add CONTRIBUTING.md, SECURITY.md, and a CI workflow.", "Run the full suite and record the baseline.", ], }, { "name": "Layout", "goal": "Move the package.", "task_sketch": ["move-package", "reinstall-editable"], }, {"name": "Polish", "goal": "Polish it.", "task_sketch": ["tidy_up.v2"]}, ] } ) ] ) monkeypatch.setattr(campaign_module, "BackendRegistry", registry) phases = plan_phase_roadmap(campaign, config=Config()) assert phases[0].task_sketch == [] assert phases[1].task_sketch == ["move-package", "reinstall-editable"] assert phases[2].task_sketch == ["tidy_up.v2"] def test_phase_divergence_skips_the_comparison_for_a_dropped_sketch(tmp_path: Path) -> None: campaign = _campaign(tmp_path) phase = _divergence_phase(task_sketch=[]) plan = _plan( "nine", *[ TaskNode(id=f"task-{index}", title=f"T{index}", description="Real planned work.") for index in range(9) ], ) _record_phase_divergence(Config(), campaign, plan, phase) assert phase.divergence_note == "" assert len(phase.task_ids) == 9 def test_phase_divergence_ignores_a_pure_rename_of_the_same_scope(tmp_path: Path) -> None: """Sketch and plan IDs are generated independently, so renames are expected. Observed live: the 6502 phase-1 note listed add-ci-workflow as dropped and add-ci-quality-workflow as unplanned -- the same task, named twice. Only a changed task COUNT is evidence the repository disagreed with the roadmap. """ campaign = _campaign(tmp_path) phase = _divergence_phase(task_sketch=["add-ci-workflow", "capture-baseline"]) plan = _plan( "renamed", TaskNode(id="add-ci-quality-workflow", title="CI", description="Same work, new slug."), TaskNode(id="capture-refactor-baseline", title="Base", description="Same work, new slug."), ) _record_phase_divergence(Config(), campaign, plan, phase) assert phase.divergence_note == "" assert LedgerStore(Config().projects_dir).load(plan.effective_ledger_name).findings == [] assert phase.task_ids == ["add-ci-quality-workflow", "capture-refactor-baseline"] def test_phase_divergence_note_says_the_id_lists_include_renames(tmp_path: Path) -> None: campaign = _campaign(tmp_path) phase = _divergence_phase(task_sketch=["add-ci-workflow"]) plan = _plan( "grown", TaskNode(id="add-ci-quality-workflow", title="CI", description="Renamed."), TaskNode(id="audit-packaging-contract", title="Audit", description="Genuinely new."), ) _record_phase_divergence(Config(), campaign, plan, phase) assert "(+1)" in phase.divergence_note assert "the count is the measurement" in phase.divergence_note