# AGENTS.md — AFK Developer Instructions for AI coding assistants contributing to this project. ## Project A Python CLI tool that uses configurable AI endpoints to autonomously decompose coding goals into tasks and execute them with an agent loop. Stack: Click (CLI), Pydantic (models), Rich (terminal), GitPython (branch isolation), sqlite3 (memory), GitHub Copilot SDK, and OpenAI-compatible endpoints. ## Setup ```bash pip install -e ".[dev]" ``` Requires Python 3.12+. The default endpoint uses local GitHub Copilot authentication. OpenAI-compatible credentials may be supplied through the legacy `.env` path or via OS keyring references in `~/.afk-developer/config.yml`. ## Commands ```bash ruff check . # lint ruff format . # format python -m pytest tests/ # test afk --help # verify CLI works ``` ## Code Conventions - Python 3.12+, all type hints - Pydantic v2 for data models (use `BaseModel`, not `@dataclass` for serialized types) - Rich `Console()` for all terminal output; never use `print()` directly - Click decorators for CLI: `@click.option`, `@click.argument` - Dataclasses for internal state (Config, SessionStats, ReviewResult) - 100 char line limit (ruff configured) - No comments unless explaining a non-obvious decision — code should be self-documenting ## Key Design Decisions 1. **Config is a dataclass, not a singleton** — passed explicitly to every component. `Config.from_env()` loads from `.env` files and environment variables. 2. **SessionStats is mutable** — attached to Config and updated in-place by all API call sites via `config.stats.add_usage(response.usage)`. 3. **Task statuses saved incrementally** — `save_callback` in queue.py saves the plan after each task completes, not just at the end. This is critical for resume to work. 4. **Worker message ordering matters** — DeepSeek requires `assistant(tool_calls)` before `tool` messages. Assistant message (with content + tool_calls) must be appended first, then tool results follow. 5. **task_complete rejection** — if the LLM calls `task_complete` without having written any files, the worker rejects it with a tool result saying "REJECTED". The tool is not executed — the rejection message replaces the execution result. 6. **extract_json()** — LLM responses often include markdown fences or trailing commas. The utility handles stripping fences, removing trailing commas, and unescaping characters before `json.loads()`. 7. **Reviewer file existence** — `review_task()` accepts `files_changed` and verifies each file exists on disk. Tasks with no files created auto-fail review. 8. **PhysicsWorld partitioning** — bodies are split into `_dynamics` and `_statics` lists. Collision detection only checks dynamic×dynamic and dynamic×static, skipping static×static entirely. This is essential for performance with terrain-heavy worlds. ## Testing - Tests live in `tests/` alongside each project - Unit tests use deterministic fake provider backends and real temporary file systems; they must not require credentials or make paid model calls - Live provider tests are opt-in integration tests and must be clearly marked - Pytest fixtures are preferred for shared setup - `test_vector.py` is a good example of concise, thorough unit tests ## Module Boundaries - `grillme/` — user-facing interview; no LLM calls - `planner/` — task decomposition with LLM; produces TaskPlan - `scheduler/` — executes plans; worker calls LLM, reviewer runs shell commands - `cortex/` — persistence layer; no business logic - `backends/` — provider-neutral reasoner/coder contracts and endpoint adapters - `tools/` — pure functions for file ops, shell, codebase discovery - `cli.py` — orchestration; connects interview → decompose → execute → report - `campaign_runner.py` — campaign/phase queue-advancement business logic (the `_campaign_*` helpers); imported by `campaign_cli.py`'s `campaign` commands, which stay thin. Uses deferred (function-local) imports back into `cli.py` for a handful of shared plan-persistence primitives (`_load_plan`/`_save_plan`/ `_prepare_lint_baseline`/`_init_cortex`/`_run_plan`/`_get_plan_path`) that intentionally stayed in `cli.py` since non-campaign commands use them too — this avoids a module-load-time circular import between the two files. - `scheduler/manual_retry.py` — the `afk retry` command's manual-only preamble (`run_manual_retry`): evidence-gate checks, the research-supplement recovery path (kept inline rather than delegated -- its `restore_automatic_budget` semantics differ from the automatic path's, see the comment above that call in the source), and the bounded-recovery-budget override check. Everything after that (branch/worktree setup, worker execution, deterministic review, the acceptance gate, and finalize/merge) delegates to `scheduler/queue.py`'s `execute_plan(only_task_id=..., recovery_decision=..., manual_dispatch=True, validate_existing=...)` -- the same pipeline the automatic scheduler loop uses (Session 2 dedup, docs/refactor-handoffs/02-dedup.md Task 1; was a ~1,050-line hand-duplicated copy before, now ~320 lines). `cli.py`'s `retry` command is a thin decorator-stack delegate. Uses a deferred `import afk_developer.cli as cli` for cli.py-owned primitives (`_load_plan`/`_save_plan`/`_save_retry_session`/ `_prepare_lint_baseline`/`_estimate_cost`/`console`), same avoid-circular- import pattern as `campaign_runner.py`. Tests that fake `Worker`/ `review_task`/`validate_profiled_task` for a `cli.retry` call must patch them on the `queue` module (e.g. `monkeypatch.setattr(queue, "Worker", ...)`), not on `worker`/`reviewer`/`acceptance` directly -- `_execute_one_task` resolves those via `queue.py`'s own top-level imports, bound once at `queue.py`'s import time, same as every existing `test_queue.py` test. - `campaign_cli.py` — the `campaign` Click command group (create/plan/approve/ run/status/step/work/cancel), extracted from `cli.py`; defines its own `click.group`, registered onto `main` via `main.add_command(campaign)` in `cli.py`. Same deferred-`cli`-import pattern for `console`/`_load_plan`/ `_other_afk_processes_active`/`_validate_plan_name` (the last via a small `_validate_plan_name_callback` wrapper, since a Click `callback=` argument is resolved at import time, not call time). - `campaign_models.py` — pure campaign pydantic models/enums with no `BackendRegistry`/queue/IO dependency (`CampaignState`, `CampaignLimits`, `PhaseState`, `StallDecision`, etc.), extracted from `campaign.py`. - `campaign_store.py` — durable, atomic campaign state storage and the per-campaign run lock (`CampaignStore`, `CampaignBusyError`, `_pid_is_alive`), extracted from `campaign.py`. `campaign.py` itself now holds only the orchestration that calls `BackendRegistry` or steps the queue (`plan_phase_roadmap`, `reflect_on_completed_*`, `consult_terra_on_stall`, `continue_campaign_once`, `run_campaign_queue_until_terminal`, `run_campaign`, `build_campaign_statistics`), and re-imports every name that moved (explicitly, not via `import *`) so `afk_developer.campaign.X` keeps resolving for existing callers/tests. - `scheduler/best_of_n.py` — the best-of-N redundant `coder_light` attempt pipeline (`execute_best_of_n`), extracted from `scheduler/queue.py`, which keeps a module-level re-export. Uses a deferred `import afk_developer.scheduler.queue as queue_mod` for shared helpers still owned by `queue.py` (`_finalize_task_branch`/`_record_failure`/`_clear_failure`/ `_rollup_decomposed_parent`) plus the monkeypatch-relevant `Worker`/ `GitManager`/`review_task`/`console`. - `acceptance_cli.py` — the `acceptance-profile` command plus its `_configure_acceptance_profile` helper, extracted from `cli.py`; defines its own `click.command`, registered onto `main` via `main.add_command(acceptance_profile)`. `cli.py` re-exports `_configure_acceptance_profile` (tests call it as `cli._configure_acceptance_profile`). - `scheduler/tools/schemas.py` — the single canonical source of LLM tool schemas (`TOOL_SCHEMAS`, `build_tool_schemas(*, read_only, has_evidence_roots)`), shared by `scheduler/worker.py`'s OpenAI-compatible loop and `backends/copilot.py`'s Copilot SDK loop (Session 2 dedup, docs/refactor-handoffs/02-dedup.md Task 2). Each loop adapts the canonical `(name, description, properties, required)` tuples to its own wire format (`to_openai_tool_definitions`/`tool_parameters` for worker.py; copilot.py builds its own `Tool(...)` SDK objects from the same tuples). Filtering (mutating tools excluded read-only, `run_verification` excluded otherwise, evidence tools excluded with no evidence roots) previously only applied in `copilot.py`; `worker.py` now gets the same filter (a real, previously- unenforced gap: a read-only task's OpenAI-compatible coder could otherwise have a `write_file`/`edit_file`/`run_command` call actually dispatched). - `scheduler/tools/dispatch.py` — `dispatch_tool_call`, the shared sync dispatch body (~14 tools) both agent loops call for their non-terminal tool calls; `task_complete`/`task_blocked` are deliberately NOT included (each loop's own outer control flow still owns those -- what happens next differs structurally per loop). Fixed a real gap found while unifying this: `worker.py`'s `run_command` never capped the model-requested timeout against `config.max_shell_timeout` (copilot.py already did); both now cap consistently via the shared dispatcher. - `fsutil.py` — `atomic_write_text`, the one retry-hardened NamedTemporaryFile-then-replace pattern (Windows `PermissionError: [WinError 5]` retry/backoff), consolidated from three hand-duplicated copies (`cli.py::_save_plan`, `campaign_store.py::CampaignStore.save`, `config.py::save_user_config` -- only `_save_plan` had the retry before; the other two deliberately gain it now, Session 2 dedup Task 3.1). A leaf module: imports nothing from `afk_developer` itself, zero circular-import risk for any caller. - `events.py` — the `RunEvent`/`EventSink` seam (Session 3, docs/refactor-handoffs/03-tui-watch.md Part 1): **orchestration code emits events, sinks render them** -- `scheduler/queue.py`, `scheduler/worker.py` (`_log_tool_action` only), and `scheduler/best_of_n.py` call `events.emit(kind, text, **data)` instead of `console.print(...)` directly. `ConsoleSink` (the default sink) renders `event.text` verbatim, so this is a zero-behavior-change seam today, not a new UI -- it exists so a future sink (a JSONL event log, `afk status --watch`, ...) could observe the same events without any orchestration code changing again. Deliberately NOT migrated: `cli.py`'s ~115 interactive command-UX prints, `reporter.py`'s end-of-run summary tables (pure rendering already), and `scheduler/worker.py`'s HITL approval prompts (`Panel.fit` renderables plus a blocking `click.getchar()` read -- interactive command UX, not a one-way run event, same category as `cli.py`'s prints). A leaf module: imports nothing from `afk_developer` itself. - `watch.py` — read-only rendering for `afk status [--watch]` / `afk campaign status --watch` (Session 3 Part 2). `build_status_view(plan_payload, campaign_state, *, now, stale, plan_mtime)` is a pure function (no filesystem, no `rich.live` loop) taking raw loaded JSON dicts, not typed pydantic models, so a viewer never crashes on a plan/campaign file a newer or older binary wrote. `load_json_snapshot` tolerates a poll landing mid atomic-replace (keeps serving the last good payload marked stale rather than crashing); `watch_loop` drives a shared `rich.live.Live` poll loop used by both CLI commands. Strictly read-only: never writes a state file, never acquires `CampaignStore.acquire_run_lock`. ASCII-only markers throughout (`[ ]`/`[>]`/`[x]`/`[skip]`, `[>] RUNNING (pid ...)`) -- each is escaped via `rich.markup.escape` since a bare `[x]`/`[skip]` looks enough like a Rich style tag that Rich silently swallows it otherwise (a real, independently confirmed pre-existing bug in `campaign_cli.py`'s own older phase-list print, fixed the same session). Imports nothing from `cli.py`/`campaign_cli.py` at module level (both import `watch.py`, not the other way around); defines its own tiny private `_safe()` rather than importing `cli.py`'s, since a two-line helper isn't worth a circular-import risk.