import json from collections import Counter from types import SimpleNamespace from afk_developer.config import Config, EndpointProfile, EndpointType, LintMode, RoleRoute from afk_developer.cortex.db import CortexDB from afk_developer.planner.task_model import TaskFailureKind, TaskNode, TaskStatus from afk_developer.scheduler import worker as worker_module from afk_developer.scheduler.worker import ( Worker, _build_progress_summary, _compact_transcript, ) # --------------------------------------------------------------------------- # _build_progress_summary (pure, no mocking needed) # --------------------------------------------------------------------------- def test_build_progress_summary_warns_when_no_files_changed_yet(): counts = Counter({"read_file": 5}) summary = _build_progress_summary( turn=7, max_turns=50, tool_name_counts=counts, files_changed=[] ) assert "turn 8 of 50" in summary assert "No files have been written or edited yet" in summary assert "read_file x5" in summary def test_build_progress_summary_lists_tool_counts_and_files_changed(): counts = Counter({"read_file": 3, "run_command": 2}) summary = _build_progress_summary( turn=10, max_turns=20, tool_name_counts=counts, files_changed=["app.py", "utils.py"] ) assert "read_file x3" in summary assert "run_command x2" in summary assert "Files changed so far: app.py, utils.py" in summary assert "No files have been written" not in summary def test_scoped_pytest_prompt_forbids_interpreter_wrappers(tmp_path): worker = Worker(Config(), CortexDB(tmp_path / "cortex.db", "example"), tmp_path) task = TaskNode( id="focused", title="Focused test task", description="Create a red witness", disallow_unscoped_pytest=True, ) prompt = worker._build_system_prompt(task, "") assert "pytest.main(...)" in prompt assert "ad-hoc probes" in prompt def test_worker_prompt_treats_task_contract_as_binding(tmp_path): worker = Worker(Config(), CortexDB(tmp_path / "cortex.db", "example"), tmp_path) task = TaskNode( id="contract", title="Contract", description="Verify the contract", read_only=True, ) prompt = worker._build_system_prompt(task, "") assert "every required artifact and acceptance criterion" in prompt assert "verify each one before calling task_complete" in prompt assert "manifest references already supplied in the trusted Task Contract" in prompt assert "not as project files" in prompt def test_native_worker_records_typed_verification_events(tmp_path): worker = Worker(Config(), CortexDB(tmp_path / "cortex.db", "example"), tmp_path) contract = tmp_path / "contract.py" contract.write_text("FROZEN = True\n", encoding="utf-8") result = worker._execute_tool( "run_verification", json.dumps({"kind": "file_sha256", "paths": ["contract.py"]}), ) assert result.startswith("VERIFICATION_PASSED:") assert len(worker.last_verification_events) == 1 event = worker.last_verification_events[0] assert event.kind == "file_sha256" assert event.outcome_code == "verification_passed" assert event.return_code == 0 assert event.output_character_count > 0 assert not event.rejection_reason def test_worker_uses_effective_lint_mode_without_mutating_shared_config(tmp_path): config = Config(lint_mode=LintMode.BASELINE) worker = Worker( config, CortexDB(tmp_path / "cortex.db", "example"), tmp_path, lint_mode=LintMode.STRICT, ) assert worker.config.lint_mode is LintMode.STRICT assert config.lint_mode is LintMode.BASELINE # --------------------------------------------------------------------------- # _compact_transcript (pure, no mocking needed) # --------------------------------------------------------------------------- def _msg(role: str, tag: str) -> dict: return {"role": role, "content": tag} def test_compact_transcript_is_noop_when_not_enough_turns_recorded(): messages = [ _msg("system", "SYS"), _msg("user", "TASK"), _msg("assistant", "A0"), _msg("tool", "T0"), ] turn_start_indices = [2, 4] new_messages, new_indices = _compact_transcript(messages, turn_start_indices, 5, "SUMMARY") assert new_messages == messages assert new_indices == turn_start_indices def test_compact_transcript_collapses_older_turns_keeping_system_and_task_message(): messages = [ _msg("system", "SYS"), _msg("user", "TASK"), _msg("assistant", "A0"), _msg("tool", "T0"), _msg("assistant", "A1"), _msg("tool", "T1"), _msg("assistant", "A2"), _msg("tool", "T2"), _msg("assistant", "A3"), _msg("tool", "T3"), _msg("assistant", "A4"), _msg("tool", "T4"), ] turn_start_indices = [2, 4, 6, 8, 10, 12] new_messages, new_indices = _compact_transcript(messages, turn_start_indices, 2, "SUMMARY") assert new_messages == [ _msg("system", "SYS"), _msg("user", "TASK"), {"role": "user", "content": "SUMMARY"}, _msg("assistant", "A3"), _msg("tool", "T3"), _msg("assistant", "A4"), _msg("tool", "T4"), ] assert new_indices == [3, 5, 7] def test_compact_transcript_keeps_exactly_one_summary_message_across_repeated_calls(): messages = [ _msg("system", "SYS"), _msg("user", "TASK"), _msg("assistant", "A0"), _msg("tool", "T0"), _msg("assistant", "A1"), _msg("tool", "T1"), _msg("assistant", "A2"), _msg("tool", "T2"), _msg("assistant", "A3"), _msg("tool", "T3"), _msg("assistant", "A4"), _msg("tool", "T4"), ] turn_start_indices = [2, 4, 6, 8, 10, 12] messages, turn_start_indices = _compact_transcript(messages, turn_start_indices, 2, "SUMMARY1") # Simulate two more turns (5, 6) being appended after the first compaction. messages = messages + [ _msg("assistant", "A5"), _msg("tool", "T5"), _msg("assistant", "A6"), _msg("tool", "T6"), ] turn_start_indices = turn_start_indices + [9, 11] new_messages, new_indices = _compact_transcript(messages, turn_start_indices, 2, "SUMMARY2") serialized = json.dumps(new_messages) assert "SUMMARY1" not in serialized assert serialized.count("SUMMARY2") == 1 assert new_messages == [ _msg("system", "SYS"), _msg("user", "TASK"), {"role": "user", "content": "SUMMARY2"}, _msg("assistant", "A5"), _msg("tool", "T5"), _msg("assistant", "A6"), _msg("tool", "T6"), ] assert new_indices == [3, 5, 7] def test_compact_transcript_enforces_a_character_budget_with_large_tool_results(): large_result = "x" * 2_000 messages = [ _msg("system", "SYS"), _msg("user", "TASK"), _msg("assistant", "A0"), _msg("tool", large_result), _msg("assistant", "A1"), _msg("tool", large_result), _msg("assistant", "A2"), _msg("tool", large_result), ] turn_start_indices = [2, 4, 6, 8] new_messages, new_indices = _compact_transcript( messages, turn_start_indices, keep_recent_turns=12, summary_content="SUMMARY", max_context_chars=1_000, ) assert new_messages == [ _msg("system", "SYS"), _msg("user", "TASK"), {"role": "user", "content": "SUMMARY"}, ] assert new_indices == [3] assert len(json.dumps(new_messages, ensure_ascii=False)) <= 1_000 # --------------------------------------------------------------------------- # Integration: Worker.execute_task actually compacts a long-running attempt # --------------------------------------------------------------------------- class _FakeCompletions: def __init__(self, responses): self._responses = responses self.seen_message_lengths: list[int] = [] self.seen_messages: list[list[dict]] = [] def create(self, *, model, messages, tools, temperature): self.seen_message_lengths.append(len(messages)) self.seen_messages.append([dict(m) for m in messages]) index = len(self.seen_message_lengths) - 1 return self._responses[index] def _fake_response(tool_calls): message = SimpleNamespace(content=None, tool_calls=tool_calls) choice = SimpleNamespace(message=message) return SimpleNamespace(choices=[choice], usage=None) def _fake_tool_call(call_id: str, name: str, arguments: dict): return SimpleNamespace( id=call_id, function=SimpleNamespace(name=name, arguments=json.dumps(arguments)) ) def test_execute_task_compacts_a_long_research_tangent_and_still_completes(tmp_path, monkeypatch): config = Config(api_key="fake-key") config.endpoints = { "deepseek": EndpointProfile( name="deepseek", type=EndpointType.OPENAI_COMPATIBLE, base_url="https://fake" ), } config.coder = RoleRoute(endpoint="deepseek", model="fake-model") config.summarization_window_turns = 3 cortex = CortexDB(tmp_path / "cortex.db", "example") worker = Worker(config, cortex, tmp_path) task = TaskNode(id="t1", title="Test task", description="Do the thing.") (tmp_path / "existing.py").write_text("value = 1\n", encoding="utf-8") responses = [ _fake_response([_fake_tool_call("c0", "read_file", {"path": "UNIQUE_MARKER_TURN_0.py"})]), ] for i in range(1, 4): responses.append( _fake_response( [_fake_tool_call(f"c{i}", "read_file", {"path": "existing.py", "offset": i * 10})] ) ) responses.append( _fake_response( [_fake_tool_call("c4", "write_file", {"path": "app.py", "content": "x = 1\n"})] ) ) for i in range(5, 10): responses.append( _fake_response( [_fake_tool_call(f"c{i}", "read_file", {"path": "existing.py", "offset": i * 10})] ) ) responses.append( _fake_response( [ _fake_tool_call( "c10", "task_complete", {"summary": "Implemented app.py", "files_changed": ["app.py"]}, ) ] ) ) fake_completions = _FakeCompletions(responses) fake_client = SimpleNamespace(chat=SimpleNamespace(completions=fake_completions)) monkeypatch.setattr(worker_module, "OpenAI", lambda **_kwargs: fake_client) status, summary, files_changed = worker.execute_task(task, max_turns=20) assert status is TaskStatus.PASSED assert files_changed == ["app.py"] # Without compaction the transcript would have grown to system + task + # 11 turns * 2 messages = 24 messages by the final call. Compaction should # keep every call's transcript well below that regardless of turn count. assert max(fake_completions.seen_message_lengths) <= 12 last_call_serialized = json.dumps(fake_completions.seen_messages[-1]) assert "UNIQUE_MARKER_TURN_0.py" not in last_call_serialized assert "Progress summary" in last_call_serialized def test_execute_task_rejects_an_unscoped_pytest_run_before_completion(tmp_path, monkeypatch): config = Config(api_key="fake-key") config.endpoints = { "deepseek": EndpointProfile( name="deepseek", type=EndpointType.OPENAI_COMPATIBLE, base_url="https://fake" ), } config.coder = RoleRoute(endpoint="deepseek", model="fake-model") cortex = CortexDB(tmp_path / "cortex.db", "example") worker = Worker(config, cortex, tmp_path) task = TaskNode( id="focused", title="Focused task", description="Write a witness, then run it. No full suite from worker.", ) responses = [ _fake_response( [_fake_tool_call("write", "write_file", {"path": "app.py", "content": "x = 1\n"})] ), _fake_response( [_fake_tool_call("full-suite", "run_command", {"command": "python -m pytest -q"})] ), _fake_response( [_fake_tool_call("complete", "task_complete", {"summary": "done", "files_changed": ["app.py"]})] ), ] fake_completions = _FakeCompletions(responses) fake_client = SimpleNamespace(chat=SimpleNamespace(completions=fake_completions)) monkeypatch.setattr(worker_module, "OpenAI", lambda **_kwargs: fake_client) status, summary, _files_changed = worker.execute_task(task, max_turns=3) assert status is TaskStatus.FAILED assert summary.startswith("TASK_COMMAND_POLICY_REJECTED:") assert worker.last_failure_kind is TaskFailureKind.COMMAND_POLICY_REJECTED assert len(fake_completions.seen_message_lengths) == 2 def _governed_worker(tmp_path, *, tool_limit: int = 1): config = Config(api_key="fake-key") config.endpoints = { "deepseek": EndpointProfile( name="deepseek", type=EndpointType.OPENAI_COMPATIBLE, base_url="https://fake" ), } config.coder = RoleRoute(endpoint="deepseek", model="fake-model") config.discovery_progress_turn_limit = 0 config.discovery_progress_tool_limit = tool_limit return Worker(config, CortexDB(tmp_path / "governor-cortex.db", "example"), tmp_path) def test_execute_task_rejects_post_budget_discovery_before_dispatch_then_accepts_write( tmp_path, monkeypatch ): worker = _governed_worker(tmp_path) task = TaskNode(id="governed", title="Governed task", description="Create app.py") dispatched: list[str] = [] def fake_dispatch(name, args, **_kwargs): dispatched.append(name) if name == "read_file": return "source" if name == "write_file": return "Wrote app.py" return "ok" responses = [ _fake_response([_fake_tool_call("read-1", "read_file", {"path": "source.py"})]), _fake_response([_fake_tool_call("read-2", "grep_codebase", {"pattern": "more"})]), _fake_response( [_fake_tool_call("write", "write_file", {"path": "app.py", "content": "x = 1\n"})] ), _fake_response( [_fake_tool_call("read-after", "read_file", {"path": "app.py"})] ), _fake_response( [_fake_tool_call("done", "task_complete", {"summary": "done", "files_changed": ["app.py"]})] ), ] fake_completions = _FakeCompletions(responses) monkeypatch.setattr( worker_module, "OpenAI", lambda **_kwargs: SimpleNamespace(chat=SimpleNamespace(completions=fake_completions)), ) monkeypatch.setattr(worker_module, "dispatch_tool_call", fake_dispatch) status, _summary, files = worker.execute_task(task, max_turns=5) assert status is TaskStatus.PASSED assert files == ["app.py"] assert dispatched == ["read_file", "write_file", "read_file"] assert "DISCOVERY_PROGRESS_REJECTED:" in json.dumps(fake_completions.seen_messages[2]) assert "bounded discovery phase is over" in json.dumps( fake_completions.seen_messages[1] ).lower() def test_execute_task_does_not_treat_multiple_rejections_from_one_response_as_defiance( tmp_path, monkeypatch ): worker = _governed_worker(tmp_path) task = TaskNode(id="multi", title="Multi-call task", description="Create app.py") responses = [ _fake_response( [ _fake_tool_call("read", "read_file", {"path": "source.py"}), _fake_tool_call("grep", "grep_codebase", {"pattern": "more"}), _fake_tool_call("glob", "glob_files", {"pattern": "**/*.py"}), ] ), _fake_response( [_fake_tool_call("write", "write_file", {"path": "app.py", "content": "x = 1\n"})] ), _fake_response( [_fake_tool_call("done", "task_complete", {"summary": "done", "files_changed": ["app.py"]})] ), ] fake_completions = _FakeCompletions(responses) monkeypatch.setattr( worker_module, "OpenAI", lambda **_kwargs: SimpleNamespace(chat=SimpleNamespace(completions=fake_completions)), ) status, _summary, _files = worker.execute_task(task, max_turns=3) assert status is TaskStatus.PASSED assert worker.last_failure_kind is None def test_execute_task_ends_after_later_turn_ignores_write_or_block(tmp_path, monkeypatch): worker = _governed_worker(tmp_path) task = TaskNode(id="defiant", title="Defiant task", description="Create app.py") responses = [ _fake_response([_fake_tool_call("read-1", "read_file", {"path": "source.py"})]), _fake_response([_fake_tool_call("read-2", "grep_codebase", {"pattern": "more"})]), _fake_response([_fake_tool_call("read-3", "glob_files", {"pattern": "**/*.py"})]), ] fake_completions = _FakeCompletions(responses) monkeypatch.setattr( worker_module, "OpenAI", lambda **_kwargs: SimpleNamespace(chat=SimpleNamespace(completions=fake_completions)), ) status, summary, files = worker.execute_task(task, max_turns=20) assert status is TaskStatus.FAILED assert summary.startswith("DISCOVERY_PROGRESS_STALLED:") assert files == [] assert worker.last_failure_kind is TaskFailureKind.DISCOVERY_PROGRESS_STALLED assert len(fake_completions.seen_messages) == 3