import json
import threading
from pathlib import Path
from git import Repo
from afk_developer.backends.fake import FakeReasonerBackend
from afk_developer.backends.models import (
AcceptanceFinding,
AcceptanceOutcome,
AcceptanceValidationResult,
)
from afk_developer.config import Config, RoleRoute
from afk_developer.evidence import EvidencePacketDraft, EvidencePacketStore, ResearcherMetadata
from afk_developer.planner.task_model import (
AcceptanceProfile,
ReviewCommandEvidence,
TaskFailureKind,
TaskLifecyclePhase,
TaskNode,
TaskPlan,
TaskStatus,
VerificationAttemptEvent,
)
from afk_developer.recovery import RecoveryAction, RecoveryMode, RecoverySettings
from afk_developer.scheduler import queue, reviewer
from afk_developer.scheduler.git_manager import GitManager
from afk_developer.scheduler.reviewer import ReviewResult
def test_only_unreported_untracked_ownership_failure_is_mechanically_recoverable() -> None:
review = ReviewResult(
passed=False,
tests_passed=True,
lint_passed=True,
ownership_passed=False,
unreported_untracked_files=["scratch.py"],
)
assert queue._ownership_failure_is_mechanically_recoverable(review)
review.tests_passed = False
assert not queue._ownership_failure_is_mechanically_recoverable(review)
def test_scoped_test_review_kwargs_follow_task_policy() -> None:
scoped = TaskNode(
id="scoped",
title="Scoped",
description="Run only owned tests",
disallow_unscoped_pytest=True,
)
legacy = TaskNode(id="legacy", title="Legacy", description="Run project tests")
assert queue._scoped_test_review_kwargs(scoped) == {"disallow_unscoped_pytest": True}
assert queue._scoped_test_review_kwargs(legacy) == {}
def test_quarantine_rereview_excludes_moved_scratch_from_owned_files(
tmp_path: Path, monkeypatch
) -> None:
project = tmp_path / "project"
project.mkdir()
Repo.init(project, initial_branch="main")
product_file = project / "package.py"
scratch_file = project / "package.pyc"
product_file.write_text("VALUE = 1\n", encoding="utf-8")
scratch_file.write_bytes(b"bytecode")
reviewed_files: list[str] = []
def fake_review(*_args, **kwargs):
reviewed_files.extend(kwargs["files_changed"])
return ReviewResult(True, True, True)
monkeypatch.setattr(queue, "review_task", fake_review)
task = TaskNode(
id="bootstrap",
title="Bootstrap",
description="Create package",
files_created=["package.py", "package.pyc"],
)
plan = TaskPlan(project_name="quarantine-rereview", goal="goal", intent="implement", tasks=[task])
result = queue._quarantine_scratch_and_rereview(
task=task,
plan=plan,
config=Config(projects_dir=tmp_path / "state"),
project_dir=project,
linter="",
test_framework="",
review_files=["package.py", "package.pyc"],
reported_files=["package.py"],
lint_mode=queue.LintMode.STRICT,
lint_baseline=None,
)
assert result is not None and result.passed
assert reviewed_files == ["package.py"]
assert task.files_created == ["package.py"]
assert product_file.is_file()
assert not scratch_file.exists()
def test_red_regression_contract_accepts_only_declared_test_file(
tmp_path: Path, monkeypatch
) -> None:
task = TaskNode(
id="red-test",
title="Add red test",
description="test first",
red_regression_test_files=["tests/test_red_regression.py"],
)
monkeypatch.setattr(
queue,
"verify_red_regression_tests",
lambda *_args: (True, "Declared red-regression tests fail as expected before repair."),
)
assert queue._verify_red_regression_contract(
task, tmp_path, "pytest", ["tests/test_red_regression.py"]
) == (True, "Declared red-regression tests fail as expected before repair.")
def test_red_regression_contract_rejects_implementation_changes(tmp_path: Path) -> None:
task = TaskNode(
id="red-test",
title="Add red test",
description="test first",
red_regression_test_files=["tests/test_red_regression.py"],
)
passed, summary = queue._verify_red_regression_contract(
task, tmp_path, "pytest", ["tests/test_red_regression.py", "src/core.py"]
)
assert not passed
assert "may modify only" in summary
def test_declared_red_regression_task_supports_worker_free_validation() -> None:
red = TaskNode(
id="red-test",
title="Add red test",
description="test first",
red_regression_test_files=["tests/test_red_regression.py"],
)
ordinary = TaskNode(id="ordinary", title="Ordinary", description="implement")
assert queue._supports_validate_existing(red) is True
assert queue._supports_validate_existing(ordinary) is False
def test_red_regression_predecessor_requires_a_direct_dependency() -> None:
red = TaskNode(
id="red-test",
title="Add red test",
description="test first",
red_regression_test_files=["tests/test_red_regression.py"],
)
implement = TaskNode(
id="implement",
title="Repair implementation",
description="make it green",
dependencies=["red-test"],
)
plan = TaskPlan(project_name="example", goal="goal", intent="implement", tasks=[red, implement])
assert queue._red_regression_predecessor(implement, plan) is red
assert queue._red_regression_successor(red, plan) is implement
def test_red_regression_implementation_requires_retained_witnesses(tmp_path: Path) -> None:
red = TaskNode(
id="red-test",
title="Add red test",
description="test first",
red_regression_test_files=["tests/test_red_regression.py"],
)
implement = TaskNode(
id="implement",
title="Repair implementation",
description="make it green",
dependencies=["red-test"],
)
plan = TaskPlan(project_name="example", goal="goal", intent="implement", tasks=[red, implement])
assert queue._verify_red_regression_predecessor_files(implement, plan, tmp_path) == (
False,
"Implementation task is missing retained red-regression witnesses: "
"['tests/test_red_regression.py'].",
)
witness = tmp_path / "tests" / "test_red_regression.py"
witness.parent.mkdir()
witness.write_text("def test_red(): assert True\n", encoding="utf-8")
assert queue._verify_red_regression_predecessor_files(implement, plan, tmp_path) == (True, "")
def test_recreated_implementation_branch_keeps_red_predecessor_witnesses(tmp_path: Path) -> None:
repo = Repo.init(tmp_path, initial_branch="main")
with repo.config_writer() as config_writer:
config_writer.set_value("user", "name", "AFK Test")
config_writer.set_value("user", "email", "afk-test@example.invalid")
(tmp_path / "base.txt").write_text("base\n", encoding="utf-8")
repo.index.add(["base.txt"])
repo.index.commit("base")
git = GitManager(tmp_path)
red_branch = git.create_task_branch("red-test")
witness = tmp_path / "tests" / "test_red_regression.py"
witness.parent.mkdir()
witness.write_text("def test_red(): assert False\n", encoding="utf-8")
assert git.commit_changes("Retain red witness")
git.repo.heads["main"].checkout()
implementation_branch = git.create_task_branch("implementation", start_point=red_branch)
(tmp_path / "partial.py").write_text("unfinished = True\n", encoding="utf-8")
assert git.discard_task_branch(implementation_branch)
rebuilt_branch = queue._checkout_or_recreate_task_branch(
git, "implementation", start_point=red_branch
)
assert rebuilt_branch == implementation_branch
assert git.current_branch == implementation_branch
assert witness.exists()
assert not (tmp_path / "partial.py").exists()
assert git.repo.commit(implementation_branch).hexsha == git.repo.commit(red_branch).hexsha
def test_witnessless_existing_implementation_branch_is_rebuilt_from_red_predecessor(
tmp_path: Path,
) -> None:
repo = Repo.init(tmp_path, initial_branch="main")
with repo.config_writer() as config_writer:
config_writer.set_value("user", "name", "AFK Test")
config_writer.set_value("user", "email", "afk-test@example.invalid")
(tmp_path / "base.txt").write_text("base\n", encoding="utf-8")
repo.index.add(["base.txt"])
repo.index.commit("base")
git = GitManager(tmp_path)
red = TaskNode(
id="red-test",
title="Add red test",
description="test first",
red_regression_test_files=["tests/test_red_regression.py"],
)
implementation = TaskNode(
id="implementation",
title="Repair implementation",
description="make it green",
dependencies=[red.id],
)
plan = TaskPlan(
project_name="example", goal="goal", intent="implement", tasks=[red, implementation]
)
red_branch = git.create_task_branch(red.id)
witness = tmp_path / red.red_regression_test_files[0]
witness.parent.mkdir()
witness.write_text("def test_red(): assert False\n", encoding="utf-8")
assert git.commit_changes("Retain red witness")
git.repo.heads["main"].checkout()
implementation_branch = git.create_task_branch(implementation.id)
rebuilt_branch = queue._ensure_red_predecessor_witnesses_in_branch(
git,
implementation_branch,
implementation,
plan,
tmp_path,
start_point=red_branch,
)
assert rebuilt_branch == implementation_branch
assert witness.exists()
assert git.repo.commit(implementation_branch).hexsha == git.repo.commit(red_branch).hexsha
def test_rollup_persists_passing_parent_coherence_evidence(tmp_path: Path, monkeypatch) -> None:
plan = TaskPlan(
project_name="example",
goal="goal",
intent="implement",
tasks=[
TaskNode(
id="parent",
title="Parent",
description="parent",
status=TaskStatus.DECOMPOSED,
subtask_ids=["child"],
required_artifacts=["output.txt"],
),
TaskNode(
id="child",
title="Child",
description="child",
parent_task_id="parent",
status=TaskStatus.PASSED,
files_created=["output.txt"],
),
],
)
seen: dict[str, object] = {}
def fake_review(*_args, **kwargs):
seen.update(kwargs)
return ReviewResult(passed=True, tests_passed=True, lint_passed=True, summary="passed")
monkeypatch.setattr(queue, "review_task", fake_review)
queue._rollup_decomposed_parent(plan, plan.tasks[1], project_dir=tmp_path)
parent = plan.tasks[0]
assert seen["files_changed"] == ["output.txt"]
assert seen["required_artifacts"] == ["output.txt"]
assert parent.parent_coherence_evidence is not None
assert parent.parent_coherence_evidence.passed
assert parent.status is TaskStatus.DECOMPOSED
assert "await supervisor acceptance" in parent.blocked_reason
def test_rollup_blocks_parent_when_deterministic_coherence_fails(
tmp_path: Path, monkeypatch
) -> None:
plan = TaskPlan(
project_name="example",
goal="goal",
intent="implement",
tasks=[
TaskNode(
id="parent",
title="Parent",
description="parent",
status=TaskStatus.DECOMPOSED,
subtask_ids=["child"],
),
TaskNode(
id="child",
title="Child",
description="child",
parent_task_id="parent",
status=TaskStatus.PASSED,
files_created=["child.py"],
),
],
)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(
passed=False, tests_passed=False, lint_passed=True, summary="tests failed"
),
)
queue._rollup_decomposed_parent(plan, plan.tasks[1], project_dir=tmp_path)
parent = plan.tasks[0]
assert parent.parent_coherence_evidence is not None
assert not parent.parent_coherence_evidence.passed
assert parent.status is TaskStatus.DECOMPOSED
assert parent.blocked_reason == "Merged child coherence verification failed: tests failed"
def test_execute_plan_skips_tasks_that_already_passed(tmp_path: Path, monkeypatch) -> None:
executed: list[str] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, task):
executed.append(task.id)
raise AssertionError("A passed task must not execute again")
monkeypatch.setattr(queue, "Worker", FakeWorker)
plan = TaskPlan(
project_name="example",
goal="Skip completed work",
intent="analyze",
tasks=[
TaskNode(
id="complete",
title="Completed task",
description="Already done",
status=TaskStatus.PASSED,
)
],
)
assert queue.execute_plan(plan, Config(), object(), tmp_path, "", "")
assert executed == []
def test_execute_plan_reviews_declared_files_when_retry_writes_nothing(
tmp_path: Path, monkeypatch
) -> None:
output = tmp_path / "result.txt"
output.write_text("complete", encoding="utf-8")
reviewed_files: list[list[str] | None] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
return TaskStatus.PASSED, "Validated existing output", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
class NoGitManager:
def __init__(self, _project_dir) -> None:
raise ValueError("Not a git repository. Initialize with 'git init' first.")
def fake_review(_project_dir, _linter, _tests, files_changed=None, **_kwargs):
reviewed_files.append(files_changed)
return ReviewResult(True, True, True)
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "review_task", fake_review)
# Git is unavailable for this project (simulating a real "not a git repo, and
# auto-init isn't applicable" case), so review must fall back to the task's
# declared files instead of a worktree diff -- this is the fallback this test
# targets, not GitManager's own auto-init behavior (covered separately in
# test_git_manager.py).
monkeypatch.setattr(queue, "GitManager", NoGitManager)
plan = TaskPlan(
project_name="example",
goal="Validate existing output",
intent="implement",
tasks=[
TaskNode(
id="validate",
title="Validate output",
description="Check the existing result",
status=TaskStatus.FAILED,
files_created=["result.txt"],
)
],
)
assert queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
assert plan.tasks[0].status is TaskStatus.PASSED
assert reviewed_files == [["result.txt"]]
def test_execute_plan_uses_existing_git_worktree_files_over_stale_agent_declarations(
tmp_path: Path, monkeypatch
) -> None:
repo = Repo.init(tmp_path)
with repo.config_writer() as config_writer:
config_writer.set_value("user", "name", "AFK Test")
config_writer.set_value("user", "email", "afk-test@example.invalid")
(tmp_path / "seed.txt").write_text("seed\n", encoding="utf-8")
repo.git.add("seed.txt")
repo.index.commit("Initial project")
reviewed_files: list[list[str] | None] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
(tmp_path / "actual.py").write_text("value = 1\n", encoding="utf-8")
return TaskStatus.PASSED, "Completed", ["actual.py", "_temporary_fix.ps1"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
def fake_review(_project_dir, _linter, _tests, files_changed=None, **_kwargs):
reviewed_files.append(files_changed)
return ReviewResult(True, True, True)
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "review_task", fake_review)
plan = TaskPlan(
project_name="example",
goal="Use the trusted worktree diff",
intent="implement",
tasks=[TaskNode(id="task", title="Task", description="Implement")],
)
assert queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
assert reviewed_files == [["actual.py"]]
assert plan.tasks[0].files_created == ["actual.py"]
def test_execute_plan_worktree_isolation_runs_task_outside_shared_tree(
tmp_path: Path, monkeypatch
) -> None:
project = tmp_path / "project"
project.mkdir()
repo = Repo.init(project, initial_branch="main")
with repo.config_writer() as config_writer:
config_writer.set_value("user", "name", "AFK Test")
config_writer.set_value("user", "email", "afk-test@example.invalid")
(project / "seed.txt").write_text("seed\n", encoding="utf-8")
repo.git.add("seed.txt")
repo.index.commit("Initial project")
seen_dirs: list[str] = []
class FakeWorker:
def __init__(self, _config, _cortex, project_dir, **_kwargs) -> None:
self.project_dir_str = str(project_dir)
seen_dirs.append(self.project_dir_str)
def execute_task(self, _task):
Path(self.project_dir_str, "isolated.txt").write_text("value = 1\n", encoding="utf-8")
return TaskStatus.PASSED, "Completed", ["isolated.txt"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(True, True, True),
)
config = Config(projects_dir=tmp_path / "state")
plan = TaskPlan(
project_name="isolated-example",
goal="Run in an isolated worktree",
intent="implement",
tasks=[TaskNode(id="task", title="Task", description="Implement")],
)
assert queue.execute_plan(plan, config, FakeCortex(), project, "", "", isolation="worktree")
assert plan.tasks[0].status is TaskStatus.PASSED
worktree_dir = (
config.resolve_project_dir("isolated-example")
/ "worktrees"
/ f"{plan.branch_namespace}-task"
)
# The task ran against the isolated worktree, never the shared project directory.
assert seen_dirs == [str(worktree_dir)]
# After merge and cleanup, the change lands in the primary tree and the worktree is gone.
assert (project / "isolated.txt").read_text(encoding="utf-8") == "value = 1\n"
assert not worktree_dir.exists()
assert "afk/task" not in [head.name for head in repo.heads]
def test_red_regression_branch_merges_only_with_its_implementation(
tmp_path: Path, monkeypatch
) -> None:
project = tmp_path / "project"
project.mkdir()
repo = Repo.init(project, initial_branch="main")
with repo.config_writer() as config_writer:
config_writer.set_value("user", "name", "AFK Test")
config_writer.set_value("user", "email", "afk-test@example.invalid")
(project / "seed.txt").write_text("seed\n", encoding="utf-8")
repo.git.add("seed.txt")
repo.index.commit("Initial project")
seen_implementation_has_red_test: list[bool] = []
class FakeWorker:
def __init__(self, _config, _cortex, project_dir, **_kwargs) -> None:
self.project_dir = Path(project_dir)
def execute_task(self, task):
if task.id == "red-test":
(self.project_dir / "tests").mkdir()
(self.project_dir / "tests" / "test_red.py").write_text(
"def test_red(): assert False\n", encoding="utf-8"
)
return TaskStatus.PASSED, "Added red test", ["tests/test_red.py"]
seen_implementation_has_red_test.append(
(self.project_dir / "tests/test_red.py").is_file()
)
(self.project_dir / "src.py").write_text("VALUE = 1\n", encoding="utf-8")
return TaskStatus.PASSED, "Implemented repair", ["src.py"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(True, True, True),
)
monkeypatch.setattr(
queue,
"_verify_red_regression_contract",
lambda *_args: (True, "Expected red test failure."),
)
config = Config(projects_dir=tmp_path / "state")
plan = TaskPlan(
project_name="atomic-red-example",
goal="Keep red tests off main until repaired",
intent="implement",
tasks=[
TaskNode(
id="red-test",
title="Add red test",
description="Create the intentional failing test",
red_regression_test_files=["tests/test_red.py"],
),
TaskNode(
id="implement",
title="Repair implementation",
description="Make the regression green",
dependencies=["red-test"],
),
],
)
assert queue.execute_plan(plan, config, FakeCortex(), project, "", "", isolation="worktree")
assert seen_implementation_has_red_test == [True]
assert (project / "tests/test_red.py").is_file()
assert (project / "src.py").is_file()
assert "afk/red-test" not in [head.name for head in repo.heads]
assert "afk/implement" not in [head.name for head in repo.heads]
worktree_root = config.resolve_project_dir("atomic-red-example") / "worktrees"
assert not worktree_root.exists() or list(worktree_root.iterdir()) == []
def test_red_regression_review_failure_does_not_start_a_generic_retry(
tmp_path: Path, monkeypatch
) -> None:
"""A red witness task must not turn an expected-red review into coder thrash."""
project = tmp_path / "project"
project.mkdir()
repo = Repo.init(project, initial_branch="main")
with repo.config_writer() as config_writer:
config_writer.set_value("user", "name", "AFK Test")
config_writer.set_value("user", "email", "afk-test@example.invalid")
(project / "seed.txt").write_text("seed\n", encoding="utf-8")
repo.index.add(["seed.txt"])
repo.index.commit("Initial project")
executions: list[str] = []
class FakeWorker:
def __init__(self, _config, _cortex, project_dir, **_kwargs) -> None:
self.project_dir = Path(project_dir)
def execute_task(self, task):
executions.append(task.id)
witness = self.project_dir / "tests" / "test_red.py"
witness.parent.mkdir(exist_ok=True)
witness.write_text("def test_red(): assert False\n", encoding="utf-8")
return TaskStatus.PASSED, "Added red witness", ["tests/test_red.py"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(
True,
True,
True,
test_output="Unrelated baseline suite output.",
),
)
monkeypatch.setattr(
queue,
"_verify_red_regression_contract",
lambda *_args: (False, "Focused red verification failed."),
)
config = Config(projects_dir=tmp_path / "state")
task = TaskNode(
id="red-test",
title="Add red witness",
description="Create an intentional failing test",
red_regression_test_files=["tests/test_red.py"],
)
plan = TaskPlan(project_name="red-review", goal="goal", intent="implement", tasks=[task])
assert not queue.execute_plan(plan, config, FakeCortex(), project, "", "")
assert executions == ["red-test"]
assert task.status is TaskStatus.ESCALATED
assert task.retry_count == 0
assert task.failure_detail == "Focused red verification failed."
def test_failed_foundation_blocks_dependent_task(tmp_path: Path, monkeypatch) -> None:
executed: list[str] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, task):
executed.append(task.id)
return TaskStatus.FAILED, "foundation failed", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(False, False, True),
)
plan = TaskPlan(
project_name="example",
goal="Respect dependencies",
intent="implement",
tasks=[
TaskNode(
id="foundation",
title="Build foundation",
description="Create the core",
max_retries=0,
),
TaskNode(
id="feature",
title="Build feature",
description="Use the core",
dependencies=["foundation"],
),
],
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
assert executed == ["foundation"]
assert plan.tasks[0].status is TaskStatus.ESCALATED
assert plan.tasks[1].status is TaskStatus.BLOCKED
assert "foundation (escalated)" in plan.tasks[1].blocked_reason
def test_foreman_decomposes_stuck_task_into_independent_subtasks(
tmp_path: Path, monkeypatch
) -> None:
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
return TaskStatus.FAILED, "Task keeps failing", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
class FakeForemanRegistry:
def __init__(self, _config) -> None:
pass
def get_foreman(self) -> FakeReasonerBackend:
return FakeReasonerBackend(
[
json.dumps(
{
"decision": "decompose",
"subtasks": [
{
"title": "Sub A",
"description": "Do part A",
"covers": [
"criterion:A task that never passes review"
],
},
{
"title": "Sub B",
"description": "Do part B",
"covers": [],
"depends_on": [1],
},
],
"summary": "Split into two independent parts.",
}
)
]
)
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "BackendRegistry", FakeForemanRegistry)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(False, False, True),
)
plan = TaskPlan(
project_name="example",
goal="Decompose a stuck task",
intent="implement",
tasks=[
TaskNode(
id="stuck",
title="Stuck task",
description="A task that never passes review",
max_retries=0,
)
],
recovery=RecoverySettings(
mode=RecoveryMode.BOUNDED,
require_supervisor_decomposition_approval=False,
),
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
parent = plan.tasks[0]
assert parent.status is TaskStatus.DECOMPOSED
assert len(parent.subtask_ids) == 2
assert plan.decompositions_used == 1
assert len(plan.tasks) == 3
subtasks = [task for task in plan.tasks if task.id in parent.subtask_ids]
assert {task.title for task in subtasks} == {"Sub A", "Sub B"}
assert all(task.parent_task_id == "stuck" for task in subtasks)
assert all(task.decomposition_depth == 1 for task in subtasks)
assert all(task.acceptance_profile is AcceptanceProfile.NONE for task in subtasks)
subtasks_by_title = {task.title: task for task in subtasks}
assert subtasks_by_title["Sub A"].acceptance_criteria == [
"A task that never passes review"
]
assert subtasks_by_title["Sub B"].dependencies == [subtasks_by_title["Sub A"].id]
assert subtasks_by_title["Sub B"].acceptance_criteria == ["Do part B"]
def test_decomposed_task_is_not_reexecuted_on_a_later_pass(tmp_path: Path, monkeypatch) -> None:
"""A DECOMPOSED task's own work has been delegated to its subtasks -- a later
scheduler pass (e.g. the next --auto-resume iteration) must skip it, the same
way it already skips PASSED tasks, instead of re-running the worker on it."""
calls: list[str] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, task):
calls.append(task.id)
return TaskStatus.FAILED, "Task keeps failing", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
class FakeForemanRegistry:
def __init__(self, _config) -> None:
pass
def get_foreman(self) -> FakeReasonerBackend:
return FakeReasonerBackend(
[
json.dumps(
{
"decision": "decompose",
"subtasks": [
{
"title": "Sub A",
"description": "Do part A",
"covers": [
"criterion:A task that never passes review"
],
},
{
"title": "Sub B",
"description": "Do part B",
"covers": [],
"depends_on": [1],
},
],
"summary": "Split into two independent parts.",
}
)
]
)
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "BackendRegistry", FakeForemanRegistry)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(False, False, True),
)
plan = TaskPlan(
project_name="example",
goal="Decompose a stuck task",
intent="implement",
tasks=[
TaskNode(
id="stuck",
title="Stuck task",
description="A task that never passes review",
max_retries=0,
)
],
recovery=RecoverySettings(
mode=RecoveryMode.BOUNDED,
require_supervisor_decomposition_approval=False,
),
)
queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
assert plan.tasks[0].status is TaskStatus.DECOMPOSED
assert calls == ["stuck"]
queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
assert calls.count("stuck") == 1
def test_foreman_proposal_is_automatically_approved_when_contract_is_exact(
tmp_path: Path, monkeypatch
) -> None:
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
return TaskStatus.FAILED, "Task keeps failing", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
class FakeForemanRegistry:
def __init__(self, _config) -> None:
pass
def get_foreman(self) -> FakeReasonerBackend:
return FakeReasonerBackend(
[
json.dumps(
{
"decision": "decompose",
"subtasks": [
{
"title": "Fixture",
"description": "Create the fixture.",
"covers": ["criterion:Finish deterministically."],
},
{
"title": "Test",
"description": "Prove the fixture finishes.",
"covers": ["artifact:tests/test_finish.py"],
},
],
"summary": "A bounded split.",
}
)
]
)
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "BackendRegistry", FakeForemanRegistry)
monkeypatch.setattr(
queue, "review_task", lambda *_args, **_kwargs: ReviewResult(False, False, True)
)
plan = TaskPlan(
project_name="example",
goal="Govern a stuck task",
intent="implement",
tasks=[
TaskNode(
id="stuck",
title="Stuck task",
description="Finish deterministically.",
required_artifacts=["tests/test_finish.py"],
max_retries=0,
)
],
recovery=RecoverySettings(mode=RecoveryMode.BOUNDED),
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
assert plan.tasks[0].status is TaskStatus.DECOMPOSED
assert len(plan.tasks) == 3
assert plan.decompositions_used == 1
assert len(plan.foreman_proposals) == 1
assert plan.foreman_proposals[0].parent_task_id == "stuck"
def test_retrying_a_failed_task_on_a_later_pass_reuses_its_stale_branch(
tmp_path: Path, monkeypatch
) -> None:
"""A task's branch survives a failed attempt (discard_branch_on_failure
defaults to False). If a LATER pass (e.g. the next --auto-resume
invocation) retries it after main has since advanced -- an independent
sibling task passed and merged in the meantime -- branch creation must
resume/checkout the stale branch instead of crashing with a raw OSError
from GitPython (the ref already exists, pointing at an older commit than
current HEAD)."""
attempts: dict[str, int] = {}
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, task):
attempts[task.id] = attempts.get(task.id, 0) + 1
if task.id == "flaky" and attempts["flaky"] <= 2:
return TaskStatus.FAILED, f"flaky failure {attempts['flaky']}", []
(tmp_path / f"{task.id}.txt").write_text("done\n", encoding="utf-8")
return TaskStatus.PASSED, f"{task.id} done", [f"{task.id}.txt"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(True, True, True),
)
plan = TaskPlan(
project_name="example",
goal="Retry a task on a later pass after main has moved on",
intent="implement",
tasks=[
TaskNode(id="flaky", title="Flaky task", description="Fails twice then passes"),
TaskNode(id="steady", title="Steady task", description="Passes immediately"),
],
)
# Retries climb the altitude ladder, never repeat a rung. A three-rung ladder
# (coder_light -> coder -> reasoner) is what leaves "flaky" FAILED-but-retriable
# after its two in-pass attempts, so a later pass can pick it up again.
config = Config(coder_light=RoleRoute(endpoint="copilot", model="cheap"))
queue.execute_plan(plan, config, FakeCortex(), tmp_path, "", "")
tasks_by_id = {t.id: t for t in plan.tasks}
assert tasks_by_id["steady"].status is TaskStatus.PASSED
assert tasks_by_id["flaky"].status is TaskStatus.FAILED
assert tasks_by_id["flaky"].altitude == "reasoner"
# Must not raise -- this is exactly the scenario that used to crash with a
# raw OSError ("Reference ... does already exist ...") from GitPython.
queue.execute_plan(plan, config, FakeCortex(), tmp_path, "", "")
assert tasks_by_id["flaky"].status is TaskStatus.PASSED
def test_a_stale_dirty_branch_from_an_earlier_task_does_not_block_the_next_task(
tmp_path: Path, monkeypatch
) -> None:
"""A failed task's branch can be left dirty (uncommitted edits + stray
scratch files) since discard_branch_on_failure defaults to False. The
NEXT task in the same pass must still get its own clean, isolated branch
instead of silently limping along without git isolation (real symptom
observed live: "Cannot switch to a task branch while the current branch
has uncommitted changes." repeating on every subsequent task for the
rest of the run)."""
attempts: dict[str, int] = {}
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, task):
if task.id == "messy":
attempts[task.id] = attempts.get(task.id, 0) + 1
# Leave real uncommitted dirt behind: a tracked-file edit
# plus an untracked scratch file, mirroring a real failed
# attempt that never cleaned up after itself.
(tmp_path / "tracked.txt").write_text("dirty\n", encoding="utf-8")
(tmp_path / "scratch.py").write_text("# leftover\n", encoding="utf-8")
return TaskStatus.FAILED, f"messy failure {attempts[task.id]}", []
(tmp_path / f"{task.id}.txt").write_text("done\n", encoding="utf-8")
return TaskStatus.PASSED, f"{task.id} done", [f"{task.id}.txt"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(True, True, True),
)
(tmp_path / "tracked.txt").write_text("clean\n", encoding="utf-8")
plan = TaskPlan(
project_name="example",
goal="A dirty task must not block the next task's git isolation",
intent="implement",
tasks=[
TaskNode(id="messy", title="Messy task", description="Leaves dirty state behind"),
TaskNode(
id="tidy", title="Tidy task", description="Must still get its own clean branch"
),
],
)
queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
tasks_by_id = {t.id: t for t in plan.tasks}
# coder then reasoner both failed: the ladder is exhausted, so the breaker
# sends the task up to a human rather than sideways to another attempt.
assert tasks_by_id["messy"].status is TaskStatus.ESCALATED
assert tasks_by_id["messy"].failure_kind is TaskFailureKind.ALTITUDE_EXHAUSTED
assert tasks_by_id["tidy"].status is TaskStatus.PASSED
assert (tmp_path / "tidy.txt").exists()
# The discarded stale branch's scratch file must be gone, and its branch
# deleted -- proof the mess was actually cleaned up, not left to recur.
assert not (tmp_path / "scratch.py").exists()
repo = Repo(tmp_path)
assert "afk/messy" not in [head.name for head in repo.heads]
assert repo.active_branch.name == "main"
def test_cleanup_failure_preserves_original_task_failure(tmp_path: Path, monkeypatch) -> None:
repo = Repo.init(tmp_path, initial_branch="main")
with repo.config_writer() as config_writer:
config_writer.set_value("user", "name", "AFK Test")
config_writer.set_value("user", "email", "afk-test@example.invalid")
(tmp_path / "base.txt").write_text("base\n", encoding="utf-8")
repo.index.add(["base.txt"])
repo.index.commit("base")
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
(tmp_path / "generated.py").write_text("generated = True\n", encoding="utf-8")
return TaskStatus.PASSED, "worker completed", ["generated.py"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(
False,
True,
True,
summary="Mutation scope exceeded: 2 files/10 lines.",
scope_passed=False,
),
)
monkeypatch.setattr(GitManager, "discard_task_branch", lambda *_args: False)
task = TaskNode(
id="oversized",
title="Oversized task",
description="Exceed deterministic scope.",
max_retries=0,
discard_branch_on_failure=True,
)
plan = TaskPlan(project_name="example", goal="Preserve cause", intent="implement", tasks=[task])
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
assert task.status is TaskStatus.ESCALATED
assert task.failure_kind is TaskFailureKind.MUTATION_SCOPE_EXCEEDED
assert "Mutation scope exceeded: 2 files/10 lines." in task.failure_detail
assert "Cleanup also failed" in task.failure_detail
def test_a_stale_dirty_branch_from_a_previous_invocation_does_not_disable_the_whole_session(
tmp_path: Path, monkeypatch
) -> None:
"""A previous `afk resume` invocation can end with an unrelated task's
branch left dirty (discard_branch_on_failure defaults to False). The
NEXT invocation's session-start dirty-tree check must discard that stale
branch and keep git isolation for the whole session, instead of giving up
on git entirely the moment ANY dirty state is found at startup (real
symptom observed live: "Running without git branch isolation for this
session" on every subsequent invocation, forever, even though nothing
is actually still in progress)."""
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, task):
(tmp_path / f"{task.id}.txt").write_text("done\n", encoding="utf-8")
return TaskStatus.PASSED, f"{task.id} done", [f"{task.id}.txt"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(True, True, True),
)
# Simulate a previous invocation leaving a failed task's branch dirty.
repo = Repo.init(tmp_path, initial_branch="main")
with repo.config_writer() as config_writer:
config_writer.set_value("user", "name", "AFK Test")
config_writer.set_value("user", "email", "afk-test@example.invalid")
(tmp_path / "tracked.txt").write_text("base\n", encoding="utf-8")
repo.index.add(["tracked.txt"])
repo.index.commit("Initial project")
repo.create_head("afk/messy").checkout()
(tmp_path / "tracked.txt").write_text("dirty\n", encoding="utf-8")
(tmp_path / "scratch.py").write_text("# leftover\n", encoding="utf-8")
plan = TaskPlan(
project_name="example",
goal="A stale dirty branch at startup must not disable isolation for the session",
intent="implement",
tasks=[
TaskNode(
id="messy",
title="Messy task",
description="Already recorded as failed",
status=TaskStatus.FAILED,
),
TaskNode(
id="tidy", title="Tidy task", description="Must still get its own clean branch"
),
],
)
queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
tasks_by_id = {t.id: t for t in plan.tasks}
assert tasks_by_id["tidy"].status is TaskStatus.PASSED
assert (tmp_path / "tidy.txt").exists()
assert not (tmp_path / "scratch.py").exists()
assert "afk/messy" not in [head.name for head in repo.heads]
assert repo.active_branch.name == "main"
def test_foreman_decline_leaves_task_escalated_and_records_fingerprint(
tmp_path: Path, monkeypatch
) -> None:
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
return TaskStatus.FAILED, "Task keeps failing", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
class FakeForemanRegistry:
def __init__(self, _config) -> None:
pass
def get_foreman(self) -> FakeReasonerBackend:
return FakeReasonerBackend(
[json.dumps({"decision": "escalate", "summary": "Needs a human."})]
)
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "BackendRegistry", FakeForemanRegistry)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(False, False, True),
)
plan = TaskPlan(
project_name="example",
goal="Decline decomposition",
intent="implement",
tasks=[TaskNode(id="stuck", title="Stuck task", description="Never passes", max_retries=0)],
recovery=RecoverySettings(mode=RecoveryMode.BOUNDED),
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
task = plan.tasks[0]
assert task.status is TaskStatus.ESCALATED
assert len(plan.tasks) == 1
assert plan.decompositions_used == 0
assert len(task.decomposition_fingerprints) == 1
def test_decompose_disabled_by_default_still_escalates_after_retries(
tmp_path: Path, monkeypatch
) -> None:
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
return TaskStatus.FAILED, "Task keeps failing", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
class ExplodingRegistry:
def __init__(self, _config) -> None:
pass
def get_foreman(self):
raise AssertionError("Foreman must not be consulted when recovery is off")
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "BackendRegistry", ExplodingRegistry)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(False, False, True),
)
plan = TaskPlan(
project_name="example",
goal="No decomposition without bounded recovery",
intent="implement",
tasks=[TaskNode(id="stuck", title="Stuck task", description="Never passes", max_retries=0)],
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
assert plan.tasks[0].status is TaskStatus.ESCALATED
assert len(plan.tasks) == 1
def test_rollup_flips_decomposed_parent_to_passed_once_all_subtasks_pass(
tmp_path: Path, monkeypatch
) -> None:
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
return TaskStatus.PASSED, "Subtask done", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(True, True, True),
)
parent = TaskNode(
id="stuck",
title="Stuck task",
description="Was decomposed",
status=TaskStatus.DECOMPOSED,
subtask_ids=["stuck-sub-1", "stuck-sub-2"],
)
sub1 = TaskNode(
id="stuck-sub-1",
title="Sub A",
description="Part A",
parent_task_id="stuck",
decomposition_depth=1,
status=TaskStatus.PASSED,
)
sub2 = TaskNode(
id="stuck-sub-2",
title="Sub B",
description="Part B",
parent_task_id="stuck",
decomposition_depth=1,
)
plan = TaskPlan(
project_name="example",
goal="Roll up once every subtask passes",
intent="implement",
tasks=[parent, sub1, sub2],
recovery=RecoverySettings(require_supervisor_parent_coherence=False),
)
assert queue.execute_plan(
plan, Config(), FakeCortex(), tmp_path, "", "", only_task_id="stuck-sub-2"
)
assert plan.tasks[0].status is TaskStatus.PASSED
def test_maybe_decompose_task_budget_is_race_safe_under_concurrent_callers(monkeypatch) -> None:
"""Two stuck tasks racing to decompose against a shared plan-wide budget of one
must never both succeed -- the loser must escalate cleanly instead of the plan
overspending its decomposition budget."""
barrier = threading.Barrier(2)
class BarrierSyncedForeman(FakeReasonerBackend):
def complete(self, *, system_prompt, user_prompt, temperature=0.0):
# Force both threads to be mid-flight on their own (slow, real-world)
# foreman call at the same time, so both reach the commit section's
# budget re-check at effectively the same moment.
barrier.wait(timeout=5)
return super().complete(
system_prompt=system_prompt, user_prompt=user_prompt, temperature=temperature
)
class FakeForemanRegistry:
def __init__(self, _config) -> None:
pass
def get_foreman(self) -> BarrierSyncedForeman:
return BarrierSyncedForeman(
[
json.dumps(
{
"decision": "decompose",
"subtasks": [
{
"title": "Sub A",
"description": "Do part A",
"covers": ["criterion:Never passes"],
},
{
"title": "Sub B",
"description": "Do part B",
"covers": [],
"depends_on": [1],
},
],
"summary": "Split into two independent parts.",
}
)
]
)
monkeypatch.setattr(queue, "BackendRegistry", FakeForemanRegistry)
plan = TaskPlan(
project_name="example",
goal="Race two stuck tasks against one shared decompose budget",
intent="implement",
tasks=[
TaskNode(
id="stuck-a",
title="Stuck task A",
description="Never passes",
max_retries=0,
failure_kind=TaskFailureKind.TESTS_FAILED,
failure_detail="failure a",
),
TaskNode(
id="stuck-b",
title="Stuck task B",
description="Never passes",
max_retries=0,
failure_kind=TaskFailureKind.TESTS_FAILED,
failure_detail="failure b",
),
],
recovery=RecoverySettings(
mode=RecoveryMode.BOUNDED,
max_decompositions=1,
require_supervisor_decomposition_approval=False,
),
)
config = Config()
results: dict[str, bool] = {}
def _run(task_id: str) -> None:
task = next(item for item in plan.tasks if item.id == task_id)
results[task_id] = queue._maybe_decompose_task(task=task, plan=plan, config=config)
threads = [threading.Thread(target=_run, args=(task_id,)) for task_id in ("stuck-a", "stuck-b")]
for thread in threads:
thread.start()
for thread in threads:
thread.join(timeout=10)
assert not any(thread.is_alive() for thread in threads)
assert plan.decompositions_used == 1
assert sorted(results.values()) == [False, True]
winner_id = next(task_id for task_id, won in results.items() if won)
loser_id = next(task_id for task_id, won in results.items() if not won)
winner = next(item for item in plan.tasks if item.id == winner_id)
loser = next(item for item in plan.tasks if item.id == loser_id)
assert winner.status is TaskStatus.DECOMPOSED
assert len(winner.subtask_ids) == 2
# _maybe_decompose_task's own contract is just its return value + recording
# a fingerprint so the caller doesn't re-offer the same failure to the
# foreman again; flipping task.status to ESCALATED on a `False` return is
# execute_plan's job (already covered by the single-threaded decline test),
# not this function's -- see its docstring.
assert not loser.subtask_ids
assert loser.decomposition_fingerprints
assert len(plan.tasks) == 4
def test_merge_conflict_retries_once_before_escalating(tmp_path: Path, monkeypatch) -> None:
repo = Repo.init(tmp_path)
with repo.config_writer() as config_writer:
config_writer.set_value("user", "name", "AFK Test")
config_writer.set_value("user", "email", "afk-test@example.invalid")
(tmp_path / "seed.txt").write_text("seed\n", encoding="utf-8")
repo.git.add("seed.txt")
repo.index.commit("Initial project")
repo.close()
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
return TaskStatus.PASSED, "Completed", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(True, True, True),
)
monkeypatch.setattr(queue, "_finalize_task_branch", lambda *_args, **_kwargs: False)
plan = TaskPlan(
project_name="example",
goal="Simulate a persistent merge conflict",
intent="implement",
tasks=[TaskNode(id="task", title="Task", description="Implement")],
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
task = plan.tasks[0]
assert task.status in (TaskStatus.PENDING, TaskStatus.RETRYING)
assert task.merge_conflict_retries_remaining == 0
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
assert plan.tasks[0].status is TaskStatus.ESCALATED
def test_post_merge_missing_primary_artifact_never_marks_task_passed(
tmp_path: Path, monkeypatch
) -> None:
repo = Repo.init(tmp_path, initial_branch="main")
with repo.config_writer() as config_writer:
config_writer.set_value("user", "name", "AFK Test")
config_writer.set_value("user", "email", "afk-test@example.invalid")
(tmp_path / "seed.txt").write_text("seed\n", encoding="utf-8")
repo.git.add("seed.txt")
repo.index.commit("Initial project")
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
return TaskStatus.PASSED, "Completed", ["missing.py"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(True, True, True),
)
monkeypatch.setattr(queue, "_finalize_task_branch", lambda *_args, **_kwargs: True)
plan = TaskPlan(
project_name="example",
goal="Reject a false merge success",
intent="implement",
tasks=[
TaskNode(
id="task",
title="Task",
description="Implement",
required_artifacts=["missing.py"],
)
],
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
task = plan.tasks[0]
assert task.status in (TaskStatus.PENDING, TaskStatus.RETRYING)
assert task.failure_kind is TaskFailureKind.REQUIRED_ARTIFACT_MISSING
assert not (tmp_path / "missing.py").exists()
def test_best_of_n_keeps_first_passing_candidate_and_discards_others(
tmp_path: Path, monkeypatch
) -> None:
project = tmp_path / "project"
project.mkdir()
repo = Repo.init(project, initial_branch="main")
with repo.config_writer() as config_writer:
config_writer.set_value("user", "name", "AFK Test")
config_writer.set_value("user", "email", "afk-test@example.invalid")
(project / "seed.txt").write_text("seed\n", encoding="utf-8")
repo.git.add("seed.txt")
repo.index.commit("Initial project")
class FakeWorker:
def __init__(self, _config, _cortex, project_dir, **_kwargs) -> None:
self.project_dir_str = str(project_dir)
def execute_task(self, _task):
if "attempt-1" in self.project_dir_str:
Path(self.project_dir_str, "winner.txt").write_text("value = 1\n", encoding="utf-8")
return TaskStatus.PASSED, "Attempt 1 completed", ["winner.txt"]
return TaskStatus.FAILED, "Attempt 2 failed", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue, "review_task", lambda *_args, **_kwargs: ReviewResult(True, True, True)
)
config = Config(projects_dir=tmp_path / "state")
plan = TaskPlan(
project_name="best-of-example",
goal="Best of two",
intent="implement",
tasks=[TaskNode(id="task", title="Task", description="Implement")],
)
task = plan.tasks[0]
assert queue.execute_best_of_n(task, plan, config, FakeCortex(), project, "", "", n=2)
assert task.status is TaskStatus.PASSED
assert (project / "winner.txt").read_text(encoding="utf-8") == "value = 1\n"
assert not any(head.name.startswith("afk/") for head in repo.heads)
worktree_root = config.resolve_project_dir("best-of-example") / "worktrees"
assert not worktree_root.exists() or list(worktree_root.iterdir()) == []
def test_best_of_n_escalates_when_every_candidate_fails(tmp_path: Path, monkeypatch) -> None:
project = tmp_path / "project"
project.mkdir()
repo = Repo.init(project, initial_branch="main")
with repo.config_writer() as config_writer:
config_writer.set_value("user", "name", "AFK Test")
config_writer.set_value("user", "email", "afk-test@example.invalid")
(project / "seed.txt").write_text("seed\n", encoding="utf-8")
repo.git.add("seed.txt")
repo.index.commit("Initial project")
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
return TaskStatus.FAILED, "Never passes", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(False, False, True),
)
config = Config(projects_dir=tmp_path / "state")
plan = TaskPlan(
project_name="best-of-fail",
goal="Best of two, both fail",
intent="implement",
tasks=[TaskNode(id="task", title="Task", description="Implement")],
)
task = plan.tasks[0]
assert not queue.execute_best_of_n(task, plan, config, FakeCortex(), project, "", "", n=2)
assert task.status is TaskStatus.ESCALATED
assert "best-of-2" in task.failure_detail
def test_best_of_n_rejects_profiled_tasks(tmp_path: Path) -> None:
config = Config(projects_dir=tmp_path / "state")
plan = TaskPlan(
project_name="best-of-profiled",
goal="Profiled tasks cannot use best-of-N",
intent="implement",
tasks=[
TaskNode(
id="task",
title="Task",
description="Implement",
acceptance_profile=AcceptanceProfile.CORPUS_RAW_OUTPUT,
)
],
)
task = plan.tasks[0]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
assert not queue.execute_best_of_n(task, plan, config, FakeCortex(), tmp_path, "", "", n=2)
assert task.status is TaskStatus.ESCALATED
def test_verified_insufficient_evidence_skips_implementation_and_allows_release(
tmp_path: Path, monkeypatch
) -> None:
project = tmp_path / "project"
project.mkdir()
corpus = tmp_path / "corpus"
corpus.mkdir()
(corpus / "source.xml").write_text("BEGIN pointer-only END", encoding="utf-8")
config = Config(projects_dir=tmp_path / "state")
discovery = TaskNode(
id="discover",
title="Discover source form",
description="Read corpus",
read_only=True,
status=TaskStatus.PASSED,
evidence_roots=[str(corpus.resolve())],
)
packet = EvidencePacketStore(config.projects_dir).create_packet(
project_name="example",
task_id="discover",
approved_roots=discovery.evidence_roots,
draft=EvidencePacketDraft.model_validate(
{
"sources": [
{
"root": str(corpus),
"relative_path": "source.xml",
"start_marker": "BEGIN",
"end_marker": "END",
}
],
"facts": ["Only the pointer-only form occurs in the approved source."],
"observed_rules": [
{
"category": "search-coverage",
"statement": "No populated form was found in the inspected source.",
"source_indices": [0],
}
],
"support_boundary": {
"supported_forms": ["pointer-only form"],
"exclusions": ["No populated form is source-backed."],
},
"conclusion": "insufficient",
}
),
researcher=ResearcherMetadata(endpoint="copilot", model="gpt-5.6-terra"),
)
EvidencePacketStore(config.projects_dir).apply_to_task(discovery, packet)
discovery.status = TaskStatus.PASSED
discovery.lifecycle_phase = TaskLifecyclePhase.PASSED
implementation = TaskNode(
id="implement",
title="Implement source form",
description="Mutate only when discovery proves a contract.",
dependencies=["discover"],
evidence_gated_by=["discover"],
)
release = TaskNode(
id="release",
title="Verify release",
description="Read-only release check.",
dependencies=["implement"],
accepts_not_applicable_dependencies=True,
read_only=True,
)
executed: list[str] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, task):
executed.append(task.id)
return TaskStatus.PASSED, "Release verification complete", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue, "review_task", lambda *_args, **_kwargs: ReviewResult(True, True, True)
)
plan = TaskPlan(
project_name="example",
goal="Respect negative evidence",
intent="implement",
tasks=[discovery, implementation, release],
)
assert queue.execute_plan(plan, config, FakeCortex(), project, "ruff", "pytest")
assert implementation.status is TaskStatus.NOT_APPLICABLE
assert "verified insufficient" in implementation.not_applicable_reason
assert implementation.attempts == []
assert executed == ["release"]
assert release.status is TaskStatus.PASSED
def test_evidence_gate_source_uses_researcher_before_normal_worker(
tmp_path: Path, monkeypatch
) -> None:
discovery = TaskNode(
id="discover",
title="Discover source form",
description="Read corpus",
read_only=True,
)
implementation = TaskNode(
id="implement",
title="Implement source form",
description="Mutate only when discovery proves a contract.",
dependencies=["discover"],
evidence_gated_by=["discover"],
)
researched: list[str] = []
executed: list[str] = []
def fake_research(*, task, **_kwargs) -> bool:
researched.append(task.id)
task.evidence_packet_id = "example/discover"
task.evidence_revision = 1
task.evidence_fingerprint = "a" * 64
return True
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, task):
executed.append(task.id)
return TaskStatus.PASSED, "Completed", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "_run_research_supplement", fake_research)
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "_evidence_gate_decision", lambda *_args: (False, ""))
monkeypatch.setattr(
queue, "review_task", lambda *_args, **_kwargs: ReviewResult(True, True, True)
)
plan = TaskPlan(
project_name="example",
goal="Attach discovery evidence before mutation",
intent="implement",
tasks=[discovery, implementation],
)
assert queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "ruff", "pytest")
assert researched == ["discover"]
assert discovery.status is TaskStatus.PASSED
assert executed == ["implement"]
def test_profiled_evidence_gate_requires_raw_output_discovery(tmp_path: Path) -> None:
discovery = TaskNode(
id="discover",
title="Discover source form",
description="Read corpus",
read_only=True,
)
implementation = TaskNode(
id="implement",
title="Implement source form",
description="Write only source-proven output.",
dependencies=["discover"],
evidence_gated_by=["discover"],
acceptance_profile=AcceptanceProfile.CORPUS_RAW_OUTPUT,
)
plan = TaskPlan(
project_name="example",
goal="Use source evidence",
intent="implement",
tasks=[discovery, implementation],
)
assert (
queue._evidence_gate_acceptance_profile(discovery, plan)
is AcceptanceProfile.CORPUS_RAW_OUTPUT
)
discovery.evidence_packet_id = "example/discover/revision-1"
discovery.evidence_revision = 1
discovery.evidence_fingerprint = "a" * 64
queue._inherit_evidence_gate_packet(implementation, plan)
assert implementation.evidence_packet_id == discovery.evidence_packet_id
assert implementation.evidence_revision == discovery.evidence_revision
assert implementation.evidence_fingerprint == discovery.evidence_fingerprint
def test_provider_failure_escalates_without_consuming_an_implementation_retry(
tmp_path: Path, monkeypatch
) -> None:
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
return (
TaskStatus.FAILED,
"Copilot error: failed to fetch authenticated GitHub user after VPN loss",
[],
)
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("must not review")),
)
plan = TaskPlan(
project_name="example",
goal="Pause safely while Copilot is unavailable",
intent="analyze",
tasks=[TaskNode(id="task", title="Task", description="Do work")],
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "ruff", "pytest")
task = plan.tasks[0]
assert task.status is TaskStatus.ESCALATED
assert task.retry_count == 0
assert task.failure_kind is TaskFailureKind.PROVIDER_UNAVAILABLE
assert "VPN loss" in task.failure_detail
def test_verification_policy_failure_escalates_without_an_implementation_retry(
tmp_path: Path, monkeypatch
) -> None:
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
return (
TaskStatus.ESCALATED,
"VERIFICATION_POLICY_REJECTED: pytest paths must remain inside the project.",
[],
)
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("must not review")),
)
plan = TaskPlan(
project_name="example",
goal="Treat verifier policy as runner infrastructure",
intent="analyze",
tasks=[TaskNode(id="task", title="Task", description="Do work")],
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "ruff", "pytest")
task = plan.tasks[0]
assert task.status is TaskStatus.ESCALATED
assert task.retry_count == 0
assert task.failure_kind is TaskFailureKind.VERIFICATION_POLICY_REJECTED
def test_regular_worker_failure_still_uses_an_implementation_retry(
tmp_path: Path, monkeypatch
) -> None:
calls: list[str] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
calls.append("execute")
if len(calls) == 1:
return TaskStatus.FAILED, "Copilot ended without calling task_complete.", []
return TaskStatus.PASSED, "Completed on retry", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(True, True, True),
)
plan = TaskPlan(
project_name="example",
goal="Retry normal worker failures",
intent="analyze",
tasks=[TaskNode(id="task", title="Task", description="Do work")],
)
assert queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "ruff", "pytest")
task = plan.tasks[0]
assert calls == ["execute", "execute"]
assert task.status is TaskStatus.PASSED
assert task.retry_count == 1
assert task.failure_kind is None
assert task.failure_detail == ""
def test_identical_deterministic_failure_stops_after_one_repair_cycle(
tmp_path: Path, monkeypatch
) -> None:
calls: list[str] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
calls.append("execute")
return TaskStatus.PASSED, "Worker completed", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(
False,
False,
True,
test_output="same assertion failure",
summary="Tests FAILED.",
),
)
plan = TaskPlan(
project_name="example",
goal="Stop an unchanged repair loop",
intent="implement",
tasks=[TaskNode(id="task", title="Task", description="Do work", max_retries=3)],
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "pytest")
task = plan.tasks[0]
assert calls == ["execute", "execute"]
assert task.status is TaskStatus.ESCALATED
assert task.failure_kind is TaskFailureKind.REPEATED_FAILURE
assert len(task.deterministic_failure_fingerprints) == 1
def test_retry_worker_rejection_does_not_mask_repeated_review_failure(
tmp_path: Path, monkeypatch
) -> None:
calls: list[str] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
self.last_failure_kind = None
def execute_task(self, _task):
calls.append("execute")
if len(calls) == 1:
return TaskStatus.PASSED, "Worker completed", []
return TaskStatus.FAILED, "REJECTED: Create or edit at least one file", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(
False,
False,
True,
test_output="same assertion failure",
summary="Tests FAILED.",
),
)
plan = TaskPlan(
project_name="example",
goal="Stop an unchanged repair masked by a worker rejection",
intent="implement",
tasks=[TaskNode(id="task", title="Task", description="Do work", max_retries=3)],
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "pytest")
task = plan.tasks[0]
assert calls == ["execute", "execute"]
assert task.status is TaskStatus.ESCALATED
assert task.failure_kind is TaskFailureKind.REPEATED_FAILURE
assert len(task.deterministic_failure_fingerprints) == 1
def test_command_policy_rejection_stops_before_review_and_retry(
tmp_path: Path, monkeypatch
) -> None:
calls: list[str] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
self.last_failure_kind = TaskFailureKind.COMMAND_POLICY_REJECTED
def execute_task(self, _task):
calls.append("execute")
return (
TaskStatus.FAILED,
"TASK_COMMAND_POLICY_REJECTED: include a project-relative test path",
[],
)
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: (_ for _ in ()).throw(
AssertionError("Policy-rejected worker output must not enter review")
),
)
plan = TaskPlan(
project_name="example",
goal="Stop a task command-policy rejection",
intent="implement",
tasks=[TaskNode(id="task", title="Task", description="Do work", max_retries=3)],
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "ruff", "pytest")
task = plan.tasks[0]
assert calls == ["execute"]
assert task.status is TaskStatus.ESCALATED
assert task.failure_kind is TaskFailureKind.COMMAND_POLICY_REJECTED
assert task.retry_count == 0
assert len(task.attempts) == 1
def test_review_command_evidence_persists_with_the_task_attempt(tmp_path: Path, monkeypatch) -> None:
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
self.last_verification_events = [
VerificationAttemptEvent(
kind="file_sha256",
normalized_path_count=1,
elapsed_seconds=0.01,
outcome_code="verification_passed",
return_code=0,
output_sha256="a" * 64,
output_character_count=80,
)
]
def execute_task(self, _task):
return TaskStatus.PASSED, "Worker completed", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
evidence = ReviewCommandEvidence(
command="python -m pytest",
exit_code=0,
output_head="1 passed",
output_artifact_path=str(tmp_path / "command-001.log"),
)
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(
True,
True,
True,
command_evidence=[evidence],
),
)
plan = TaskPlan(
project_name="example",
goal="Persist review proof",
intent="analyze",
tasks=[TaskNode(id="task", title="Task", description="Do work")],
)
assert queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "pytest")
restored = TaskPlan.model_validate_json(plan.model_dump_json())
persisted = restored.tasks[0].attempts[0].review_commands[0]
assert persisted.command == "python -m pytest"
assert persisted.exit_code == 0
assert persisted.output_artifact_path.endswith("command-001.log")
verification = restored.tasks[0].attempts[0].verification_events[0]
assert verification.kind == "file_sha256"
assert verification.outcome_code == "verification_passed"
assert verification.output_sha256 == "a" * 64
def test_readme_only_task_skips_python_tools_during_real_deterministic_review(
tmp_path: Path, monkeypatch
) -> None:
repo = Repo.init(tmp_path, initial_branch="main")
with repo.config_writer() as config_writer:
config_writer.set_value("user", "name", "AFK Test")
config_writer.set_value("user", "email", "afk-test@example.invalid")
(tmp_path / "seed.txt").write_text("seed\n", encoding="utf-8")
repo.git.add("seed.txt")
repo.index.commit("Initial project")
class FakeWorker:
def __init__(self, _config, _cortex, project_dir, **_kwargs) -> None:
self.project_dir = Path(project_dir)
def execute_task(self, _task):
(self.project_dir / "README.md").write_text("# Public API\n", encoding="utf-8")
return TaskStatus.PASSED, "Documented the public API", ["README.md"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
def unexpected_python_tool(*_args, **_kwargs):
raise AssertionError("README-only deterministic review must not run Python tools")
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(reviewer, "_auto_format", unexpected_python_tool)
monkeypatch.setattr(reviewer, "_run_linter", unexpected_python_tool)
monkeypatch.setattr(reviewer, "_run_tests", unexpected_python_tool)
task = TaskNode(
id="document-api",
title="Document the bounded public API",
description="Modify README.md only; invoke no pytest or Ruff command.",
required_artifacts=["README.md"],
)
plan = TaskPlan(
project_name="readme-review-regression",
goal="Document the public API without Python tooling",
intent="implement",
tasks=[task],
)
assert queue.execute_plan(
plan,
Config(projects_dir=tmp_path / "state"),
FakeCortex(),
tmp_path,
"ruff",
"pytest",
)
assert task.disallow_unscoped_pytest is True
assert task.status is TaskStatus.PASSED
assert task.retry_count == 0
assert len(task.attempts) == 1
review_commands = [evidence.command for evidence in task.attempts[0].review_commands]
assert review_commands
assert not any("pytest" in command or "ruff" in command for command in review_commands)
restored = TaskPlan.model_validate_json(plan.model_dump_json())
assert restored.tasks[0].disallow_unscoped_pytest is True
assert restored.tasks[0].attempts[0].review_commands == task.attempts[0].review_commands
def test_blocked_task_runs_after_dependency_recovers(tmp_path: Path, monkeypatch) -> None:
executed: list[str] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, task):
executed.append(task.id)
return TaskStatus.PASSED, "feature complete", ["feature.txt"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
(tmp_path / "feature.txt").write_text("done", encoding="utf-8")
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(True, True, True),
)
plan = TaskPlan(
project_name="example",
goal="Resume blocked work",
intent="implement",
tasks=[
TaskNode(
id="foundation",
title="Build foundation",
description="Create the core",
status=TaskStatus.PASSED,
),
TaskNode(
id="feature",
title="Build feature",
description="Use the core",
dependencies=["foundation"],
status=TaskStatus.BLOCKED,
blocked_reason="Waiting for: foundation (failed)",
),
],
)
assert queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
assert executed == ["feature"]
assert plan.tasks[1].status is TaskStatus.PASSED
assert plan.tasks[1].blocked_reason == ""
def test_read_only_task_runs_baseline_validation_without_formatting(
tmp_path: Path, monkeypatch
) -> None:
review_calls: list[dict] = []
worker_routes: list[tuple[str, str]] = []
class FakeWorker:
def __init__(self, config, *_args, **_kwargs) -> None:
route = config.route_for("coder")
worker_routes.append((route.endpoint, route.model))
def execute_task(self, _task):
return TaskStatus.PASSED, "Baseline inspected", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
def fake_review(*_args, **kwargs):
review_calls.append(kwargs)
return ReviewResult(True, True, True)
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "review_task", fake_review)
plan = TaskPlan(
project_name="example",
goal="Audit baseline",
intent="implement",
tasks=[
TaskNode(
id="audit",
title="Audit",
description="Inspect without modifying files",
read_only=True,
)
],
)
config = Config()
researcher_route = config.route_for("researcher")
assert queue.execute_plan(plan, config, FakeCortex(), tmp_path, "ruff", "pytest")
assert plan.tasks[0].status is TaskStatus.PASSED
assert worker_routes == [(researcher_route.endpoint, researcher_route.model)]
assert review_calls == [
{
"apply_format": False,
"lint_mode": queue.LintMode.STRICT,
"lint_baseline": None,
"test_timeout": config.max_shell_timeout,
"diagnostic_dir": queue._review_diagnostic_dir(config, plan, plan.tasks[0]),
}
]
def test_successful_retry_commits_and_merges_all_task_changes(tmp_path: Path, monkeypatch) -> None:
calls: list[str] = []
saved_statuses: list[TaskStatus] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
calls.append("execute")
if len(calls) == 1:
return TaskStatus.FAILED, "first attempt", ["initial.py"]
return TaskStatus.PASSED, "retry completed", ["retry.py"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
class FakeGitManager:
instances: list["FakeGitManager"] = []
def __init__(self, _project_dir) -> None:
self.commits: list[tuple[str, list[str] | None]] = []
self.merges = 0
self.deleted: list[str] = []
self.has_changes_calls = 0
self.instances.append(self)
@property
def current_branch(self) -> str:
return "main"
def has_changes(self) -> bool:
self.has_changes_calls += 1
return self.has_changes_calls > 1
def create_task_branch(self, task_id: str) -> str:
return f"afk/{task_id}"
def checkout_or_create_task_branch(self, task_id: str) -> str:
return f"afk/{task_id}"
def commit_changes(self, message: str, files=None) -> bool:
self.commits.append((message, files))
return True
def merge_to_branch(self) -> bool:
self.merges += 1
return True
def delete_branch(self, branch_name: str) -> None:
self.deleted.append(branch_name)
reviews = iter(
[
ReviewResult(False, False, True),
ReviewResult(True, True, True),
]
)
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "GitManager", FakeGitManager)
monkeypatch.setattr(queue, "review_task", lambda *_args, **_kwargs: next(reviews))
plan = TaskPlan(
project_name="example",
goal="Commit successful retries",
intent="implement",
tasks=[TaskNode(id="retry", title="Retry task", description="Write output")],
)
assert queue.execute_plan(
plan,
Config(),
FakeCortex(),
tmp_path,
"ruff",
"pytest",
save_callback=lambda: saved_statuses.append(plan.tasks[0].status),
)
git = FakeGitManager.instances[0]
assert calls == ["execute", "execute"]
assert plan.tasks[0].status is TaskStatus.PASSED
assert git.commits == [("AFK: Retry task [retry]", None)]
assert git.merges == 1
assert git.deleted == ["afk/retry"]
assert saved_statuses[-1] is TaskStatus.PASSED
def test_commit_all_respects_gitignore_for_generated_artifacts(tmp_path: Path) -> None:
repo = Repo.init(tmp_path)
with repo.config_writer() as config:
config.set_value("user", "name", "AFK Test")
config.set_value("user", "email", "afk-test@example.invalid")
(tmp_path / ".gitignore").write_text("__pycache__/\n*.pyc\n", encoding="utf-8")
source = tmp_path / "app.py"
source.write_text("value = 1\n", encoding="utf-8")
repo.git.add("--all")
repo.index.commit("Initial project")
source.write_text("value = 2\n", encoding="utf-8")
cache = tmp_path / "__pycache__" / "app.cpython-313.pyc"
cache.parent.mkdir()
cache.write_bytes(b"generated")
manager = GitManager(tmp_path)
assert manager.commit_changes("Update source")
assert "app.py" in repo.git.show("--name-only", "--format=").splitlines()
assert "__pycache__/app.cpython-313.pyc" not in repo.git.ls_files().splitlines()
assert cache.exists()
def test_required_profile_rejects_dirty_worktree_before_worker_runs(
tmp_path: Path, monkeypatch
) -> None:
executed: list[str] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, task):
executed.append(task.id)
return TaskStatus.PASSED, "must not run", []
class FakeGitManager:
def __init__(self, _project_dir) -> None:
pass
@property
def current_branch(self) -> str:
return "main"
def has_changes(self) -> bool:
return True
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "GitManager", FakeGitManager)
plan = TaskPlan(
project_name="example",
goal="Reject unsafe execution",
intent="implement",
tasks=[
TaskNode(
id="corpus",
title="Corpus output",
description="Preserve the corpus output.",
acceptance_profile=AcceptanceProfile.CORPUS_RAW_OUTPUT,
)
],
)
assert not queue.execute_plan(plan, Config(), object(), tmp_path, "", "")
task = plan.tasks[0]
assert executed == []
assert task.status is TaskStatus.ESCALATED
assert task.lifecycle_phase is TaskLifecyclePhase.ESCALATED
assert task.failure_kind is TaskFailureKind.ACCEPTANCE_POLICY_REJECTED
assert "dirty" in task.failure_detail.lower()
def test_required_profile_resumes_dirty_retained_semantic_repair_branch(
tmp_path: Path, monkeypatch
) -> None:
executed: list[str] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def set_task_context(self, _context: str) -> None:
pass
def execute_task(self, task):
executed.append(task.id)
return TaskStatus.PASSED, "semantic repair completed", ["generated.xml"]
class FakeGitManager:
def __init__(self, _project_dir) -> None:
pass
@property
def current_branch(self) -> str:
return "afk/corpus"
def has_changes(self) -> bool:
return True
def task_branch_name(self, task_id: str) -> str:
return f"afk/{task_id}"
def checkout_or_create_task_branch(self, task_id: str) -> str:
return f"afk/{task_id}"
def worktree_files(self) -> list[str]:
return ["generated.xml"]
def merge_to_branch(self) -> bool:
return True
def commit_changes(self, _message: str) -> bool:
return True
def primary_contains_files(self, _paths: list[str]) -> bool:
return True
def delete_branch(self, _branch_name: str) -> None:
pass
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "GitManager", FakeGitManager)
monkeypatch.setattr(
queue,
"review_task",
lambda *_args, **_kwargs: ReviewResult(True, True, True),
)
monkeypatch.setattr(
queue,
"validate_profiled_task",
lambda **_kwargs: AcceptanceValidationResult(
outcome=AcceptanceOutcome.PASS,
summary="Trusted validation passed.",
),
)
monkeypatch.setattr(
queue,
"_run_independent_validator",
lambda **_kwargs: AcceptanceValidationResult(
outcome=AcceptanceOutcome.PASS,
summary="Independent validator passed.",
),
)
task = TaskNode(
id="corpus",
title="Corpus output",
description="Repair an accepted raw-output contract.",
acceptance_profile=AcceptanceProfile.CORPUS_RAW_OUTPUT,
evidence_packet_id="example/corpus/revision-1",
status=TaskStatus.RETRYING,
recovery_action=RecoveryAction.SEMANTIC_REPAIR,
)
plan = TaskPlan(project_name="example", goal="Repair output", intent="implement", tasks=[task])
assert queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "ruff", "pytest")
assert executed == ["corpus"]
assert task.status is TaskStatus.PASSED
def test_required_profile_rejects_non_git_target_before_worker_runs(
tmp_path: Path, monkeypatch
) -> None:
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
raise AssertionError("Required-profile task must fail before worker mutation")
class NoGitManager:
def __init__(self, _project_dir) -> None:
raise ValueError("Not a git repository. Initialize with 'git init' first.")
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "GitManager", NoGitManager)
plan = TaskPlan(
project_name="example",
goal="Reject unsafe execution",
intent="implement",
tasks=[
TaskNode(
id="corpus",
title="Corpus output",
description="Preserve the corpus output.",
acceptance_profile=AcceptanceProfile.CORPUS_RAW_OUTPUT,
)
],
)
assert not queue.execute_plan(plan, Config(), object(), tmp_path, "", "")
task = plan.tasks[0]
assert task.status is TaskStatus.ESCALATED
assert task.failure_kind is TaskFailureKind.ACCEPTANCE_POLICY_REJECTED
assert "not a git repository" in task.failure_detail.lower()
def test_required_profile_without_evidence_packet_never_starts_coder(
tmp_path: Path, monkeypatch
) -> None:
executed: list[str] = []
evidence_root = tmp_path / "evidence"
evidence_root.mkdir()
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, task):
executed.append(task.id)
return TaskStatus.PASSED, "must not run", []
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
class FakeGitManager:
def __init__(self, _project_dir) -> None:
pass
@property
def current_branch(self) -> str:
return "main"
def has_changes(self) -> bool:
return False
def checkout_or_create_task_branch(self, task_id: str) -> str:
return f"afk/{task_id}"
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "GitManager", FakeGitManager)
plan = TaskPlan(
project_name="example",
goal="Block unsafe mutation",
intent="implement",
tasks=[
TaskNode(
id="corpus",
title="Corpus output",
description="Preserve source-backed output.",
acceptance_profile=AcceptanceProfile.CORPUS_RAW_OUTPUT,
evidence_roots=[str(evidence_root)],
)
],
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
task = plan.tasks[0]
assert executed == []
assert task.status is TaskStatus.ESCALATED
assert task.failure_kind is TaskFailureKind.VALIDATOR_MISSING_EVIDENCE
def test_required_profile_validator_passes_before_branch_merges(
tmp_path: Path, monkeypatch
) -> None:
calls: list[str] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
calls.append("worker")
return TaskStatus.PASSED, "generated output", ["generated.xml"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
class FakeGitManager:
instances: list["FakeGitManager"] = []
def __init__(self, _project_dir) -> None:
self.checked_out: list[str] = []
self.merges = 0
self.deleted: list[str] = []
self.instances.append(self)
@property
def current_branch(self) -> str:
return "main"
def has_changes(self) -> bool:
return False
def checkout_or_create_task_branch(self, task_id: str) -> str:
self.checked_out.append(task_id)
return f"afk/{task_id}"
def merge_to_branch(self) -> bool:
self.merges += 1
return True
def delete_branch(self, branch_name: str) -> None:
self.deleted.append(branch_name)
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "GitManager", FakeGitManager)
monkeypatch.setattr(
queue, "review_task", lambda *_args, **_kwargs: ReviewResult(True, True, True)
)
monkeypatch.setattr(
queue,
"validate_profiled_task",
lambda **_kwargs: AcceptanceValidationResult(
outcome=AcceptanceOutcome.PASS,
summary="Trusted contract comparison passed.",
),
)
monkeypatch.setattr(
queue,
"_run_independent_validator",
lambda **_kwargs: AcceptanceValidationResult(
outcome=AcceptanceOutcome.PASS,
summary="Independent validator passed.",
),
)
plan = TaskPlan(
project_name="example",
goal="Validate before merge",
intent="implement",
tasks=[
TaskNode(
id="corpus",
title="Corpus output",
description="Preserve raw output.",
acceptance_profile=AcceptanceProfile.CORPUS_RAW_OUTPUT,
evidence_packet_id="example/corpus/revision-1",
)
],
)
assert queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
task = plan.tasks[0]
git = FakeGitManager.instances[0]
assert calls == ["worker"]
assert git.checked_out == ["corpus"]
assert git.merges == 1
assert git.deleted == ["afk/corpus"]
assert task.status is TaskStatus.PASSED
assert [attempt.role for attempt in task.attempts] == ["coder", "validator"]
assert all(attempt.completed for attempt in task.attempts)
def test_validator_findings_retain_branch_and_prevent_merge(tmp_path: Path, monkeypatch) -> None:
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
return TaskStatus.PASSED, "generated output", ["generated.xml"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
class FakeGitManager:
instances: list["FakeGitManager"] = []
def __init__(self, _project_dir) -> None:
self.merges = 0
self.deleted: list[str] = []
self.instances.append(self)
@property
def current_branch(self) -> str:
return "main"
def has_changes(self) -> bool:
return False
def checkout_or_create_task_branch(self, task_id: str) -> str:
return f"afk/{task_id}"
def merge_to_branch(self) -> bool:
self.merges += 1
return True
def delete_branch(self, branch_name: str) -> None:
self.deleted.append(branch_name)
finding = AcceptanceFinding(
id="AFK-RAW-OUTPUT-0123456789ABCDEF",
summary="Wrapper order differs.",
expected="",
actual="",
affected_paths=["generated.xml"],
)
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "GitManager", FakeGitManager)
monkeypatch.setattr(
queue, "review_task", lambda *_args, **_kwargs: ReviewResult(True, True, True)
)
monkeypatch.setattr(
queue,
"validate_profiled_task",
lambda **_kwargs: AcceptanceValidationResult(
outcome=AcceptanceOutcome.PASS,
summary="Trusted comparison passed.",
),
)
monkeypatch.setattr(
queue,
"_run_independent_validator",
lambda **_kwargs: AcceptanceValidationResult(
outcome=AcceptanceOutcome.FINDINGS,
summary="Independent validator found a mismatch.",
findings=[finding],
),
)
plan = TaskPlan(
project_name="example",
goal="Prevent unvalidated merge",
intent="implement",
tasks=[
TaskNode(
id="corpus",
title="Corpus output",
description="Preserve raw output.",
acceptance_profile=AcceptanceProfile.CORPUS_RAW_OUTPUT,
evidence_packet_id="example/corpus/revision-1",
)
],
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
task = plan.tasks[0]
git = FakeGitManager.instances[0]
assert task.status is TaskStatus.ESCALATED
assert task.failure_kind is TaskFailureKind.VALIDATOR_FINDINGS
assert task.validator_finding_ids == [finding.id]
assert task.retry_count == 0
assert git.merges == 0
assert git.deleted == []
def test_successful_coder_retry_cannot_bypass_required_acceptance_validation(
tmp_path: Path, monkeypatch
) -> None:
calls: list[str] = []
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, _task):
calls.append("worker")
if len(calls) == 1:
return TaskStatus.FAILED, "first attempt failed", ["generated.xml"]
return TaskStatus.PASSED, "retry completed", ["generated.xml"]
class FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
class FakeGitManager:
instances: list["FakeGitManager"] = []
def __init__(self, _project_dir) -> None:
self.merges = 0
self.instances.append(self)
@property
def current_branch(self) -> str:
return "main"
def has_changes(self) -> bool:
return False
def checkout_or_create_task_branch(self, task_id: str) -> str:
return f"afk/{task_id}"
def merge_to_branch(self) -> bool:
self.merges += 1
return True
def delete_branch(self, _branch_name: str) -> None:
pass
finding = AcceptanceFinding(
id="AFK-RETRY-VALIDATION-0123456789AB",
summary="The retry still differs from the contract.",
)
reviews = iter([ReviewResult(False, False, True), ReviewResult(True, True, True)])
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "GitManager", FakeGitManager)
monkeypatch.setattr(queue, "review_task", lambda *_args, **_kwargs: next(reviews))
monkeypatch.setattr(
queue,
"validate_profiled_task",
lambda **_kwargs: AcceptanceValidationResult(
outcome=AcceptanceOutcome.PASS,
summary="Trusted comparison passed.",
),
)
monkeypatch.setattr(
queue,
"_run_independent_validator",
lambda **_kwargs: AcceptanceValidationResult(
outcome=AcceptanceOutcome.FINDINGS,
summary="Independent validator found a retry mismatch.",
findings=[finding],
),
)
plan = TaskPlan(
project_name="example",
goal="Protect retry branch",
intent="implement",
tasks=[
TaskNode(
id="corpus",
title="Corpus output",
description="Preserve raw output.",
acceptance_profile=AcceptanceProfile.CORPUS_RAW_OUTPUT,
evidence_packet_id="example/corpus/revision-1",
)
],
)
assert not queue.execute_plan(plan, Config(), FakeCortex(), tmp_path, "", "")
task = plan.tasks[0]
assert calls == ["worker", "worker"]
assert task.status is TaskStatus.ESCALATED
assert task.failure_kind is TaskFailureKind.VALIDATOR_FINDINGS
assert task.validator_finding_ids == [finding.id]
assert [attempt.role for attempt in task.attempts] == ["coder", "coder", "validator"]
assert FakeGitManager.instances[0].merges == 0
def _read_only_audit_plan(review: ReviewResult, monkeypatch, **task_kwargs) -> TaskPlan:
class FakeWorker:
def __init__(self, *_args, **_kwargs) -> None:
pass
def execute_task(self, task):
return TaskStatus.PASSED, "Audit complete", []
monkeypatch.setattr(queue, "Worker", FakeWorker)
monkeypatch.setattr(queue, "review_task", lambda *_args, **_kwargs: review)
return TaskPlan(
project_name="example",
goal="Audit an existing project",
intent="implement",
tasks=[
TaskNode(
id="audit",
title="Audit the baseline",
description="Read every module and record the existing public contracts.",
read_only=True,
**task_kwargs,
)
],
)
class _FakeCortex:
def write_fading(self, **_kwargs) -> None:
pass
def test_read_only_task_is_not_charged_for_a_red_baseline(tmp_path: Path, monkeypatch) -> None:
plan = _read_only_audit_plan(
ReviewResult(
passed=False,
tests_passed=False,
lint_passed=False,
summary="Tests FAILED.",
),
monkeypatch,
)
assert queue.execute_plan(plan, Config(), _FakeCortex(), tmp_path, "ruff", "pytest")
audit = plan.tasks[0]
assert audit.status is TaskStatus.PASSED
assert audit.retry_count == 0
assert audit.failure_kind is None
def test_read_only_contract_breach_escalates_instead_of_retrying_forever(
tmp_path: Path, monkeypatch
) -> None:
plan = _read_only_audit_plan(
ReviewResult(
passed=False,
tests_passed=True,
lint_passed=True,
ownership_passed=False,
unreported_untracked_files=["stray.py"],
summary="Untracked files were left behind.",
),
monkeypatch,
max_retries=2,
)
audit = plan.tasks[0]
for _ in range(6):
if audit.status is TaskStatus.ESCALATED:
break
queue.execute_plan(plan, Config(), _FakeCortex(), tmp_path, "ruff", "pytest")
assert audit.status is TaskStatus.ESCALATED
assert audit.retry_count == 2
assert audit.id not in {ready.id for ready in plan.get_ready_tasks()}