# AFK Developer Autonomous background-coding engine with GitHub Copilot and OpenAI-compatible model routes. It plans, implements, reviews, and preserves resumable task state. ## Installation ```bash # Clone and install pip install -e . # Requires Python 3.12+ ``` ## Configuration AFK Developer supports separate model routes for reasoning/planning and coding. The default route uses the locally authenticated GitHub Copilot CLI. Copy [config.example.yml](config.example.yml) to `~/.afk-developer/config.yml` to select endpoints and models explicitly. Install and authenticate the Copilot CLI before using a Copilot route: ``` npm install -g @github/copilot copilot ``` AFK Developer automatically prefers that standalone CLI over an SDK-bundled runtime. Set `AFK_COPILOT_CLI_PATH` to use a specific CLI executable instead. For a DeepSeek or other OpenAI-compatible endpoint, store the API key in the OS credential vault and reference it from the configuration as `${secret:name}`. During the migration, the legacy `.env` configuration remains supported: ``` DEEPSEEK_API_KEY=sk-your-key-here ``` The loader checks three locations (in order): `~/.afk-developer/.env`, the package directory `.env`, and the current directory `.env`. First one found wins. ### Model routes AFK routes planning and implementation independently. `reasoner` and `coder` are the normal roles. `researcher` and `validator` are read-only roles used only by the high-risk acceptance workflow; when omitted, they inherit the `reasoner` route. The built-in Copilot default is `gpt-5.6-terra`; choose a different coder route when a task needs it. The supplied [config.example.yml](config.example.yml) intentionally assigns Terra with `high` reasoning effort to the researcher and validator. They can read target-project files, approved external evidence roots, and typed verification results, but they cannot write source files, format, commit, merge, push, use an arbitrary shell, or access a database/network tool. Role routes can be overridden for one execution with `AFK_REASONER_*`, `AFK_CODER_*`, `AFK_RESEARCHER_*`, or `AFK_VALIDATOR_*` environment variables for `ENDPOINT`, `MODEL`, `TIMEOUT`, and `REASONING_EFFORT`. ### Copilot usage and cost reporting For Copilot SDK routes, AFK subscribes to the SDK's `assistant.usage` events and persists actual model calls, input/output/cache tokens, agent turns, and per-model GitHub AI credit consumption with the session. The Session Statistics report labels the dollar amount as **Copilot Metered Value**, not billed cost: GitHub values one AI credit at $0.01, but included plan or organization credits may cover all or part of that value. AFK does not claim to know the final invoice, shared-pool balance, or account-specific discounts. If an installed Copilot SDK does not emit usage events, AFK records submitted prompts and explicitly reports telemetry as unavailable rather than treating the unobserved values as zero. > AFK Developer executes ordinary coding commands on the target machine. > Sandboxing is not implemented; use `--hitl` when reviewing potentially > destructive work. The separate verifier is intentionally narrower: it only > accepts typed pytest, Ruff check, Ruff format-check, Git inspection, and > immutable lint-baseline comparison requests. It constructs arguments itself > and never executes model-provided shell text. ### Execution environments AFK has two independent Python environments. The runner interpreter executes AFK itself; the target interpreter executes the project's Ruff, pytest, and typed verification commands. They are fingerprinted separately and do not need to have the same path, version, prefix, or installed packages. AFK resolves the target from `execution.target_python`, `AFK_TARGET_PYTHON`, or the target project's `.venv`. It never falls back to AFK's interpreter or an ambient `python` command. Normal execution, campaign queue and best-of-N dispatch, and manual retry all cross the same preflight boundary before an agent or target command can run. A changed accepted target fingerprint blocks until it receives an explicit environment-repair approval. ```yaml execution: isolation: inplace target_python: C:/projects/example/.venv/Scripts/python.exe ``` ## Usage ### New project ```bash # Interactive — interviews you, clarifies, then builds afk grillme -d /path/to/project # Direct — non-interactive, auto-answers all prompts afk grillme -d /path/to/project -g "Build a pygame platformer with..." ``` ### Resume a plan ```bash afk resume project-name afk resume project-name -y # non-interactive afk resume project-name --auto-resume # stops on escalation, no progress, or its pass cap ``` ### See all durable work ```bash afk status # campaigns and standalone plans, with the next operator action afk status --watch # continuously refresh the fleet index afk status project-name # detailed task, lease, governance, and validation state ``` ### Extended, checkpointed campaigns Use a campaign when one approved objective may require several small batches over a few active hours. A campaign plans **one batch at a time**; after every fully completed batch it runs a read-only checkpoint reflection that can mark the objective complete, queue one narrowly scoped follow-up batch, or stop for human direction. ```bash # This only stores the objective and explicit ceilings; it does not plan or modify code. afk campaign create exporter-hardening -d /path/to/project \ -g "Improve offline exporter coverage with source-backed tests" \ --max-hours 4 --max-batches 4 --max-total-tasks 24 --max-tasks-per-batch 8 \ --profile corpus_raw_output --evidence-root /path/to/canonical-corpus # Explicitly authorize the bounded run. afk campaign run exporter-hardening --yes afk campaign status exporter-hardening ``` Campaign state is saved outside the target repository at `~/.afk-developer/projects/campaigns/.json`. It records every generated batch plan name, checkpoint decision, follow-up-goal fingerprint, active time, and stop reason. A campaign stops rather than autonomously continuing when a batch is incomplete or escalated, a reflection is invalid/repeated, a plan exceeds the task ceiling, the active-time/batch/task ceiling is reached, or another AFK execution is active. The creator may supply an enabled acceptance profile and immutable evidence roots; AFK applies that exact fixed policy to every future batch. Campaign reflection cannot add, remove, or change these permissions. ### Oracle-backed processor cores `campaign create-core` packages the recurring processor-core setup into one deterministic command. It requires a clean isolated Git target and a target-local `.venv`, validates the full pinned oracle revision, generates a bounded validation contract and visible milestones, and saves an ordinary unapproved campaign. It does not call a model, draft a roadmap, approve work, or modify the target. ```bash afk campaign create-core m68k-core -d /path/to/m68k-core \ --architecture "Motorola 68000" --package-name m68k \ --oracle-name "68000 SingleStepTests" \ --oracle-repository https://example.invalid/68000-vectors.git \ --oracle-revision 0123456789abcdef0123456789abcdef01234567 \ --oracle-scale "65,536 partitioned instruction-state transitions" \ --scope-file /path/to/human-approved-m68k-scope.md # First model call: draft the phased roadmap and phase-one task DAG. afk campaign plan m68k-core # Watch milestones, task counts, active leases, and required operator action. afk status --watch # Review the generated roadmap, then authorize it explicitly. afk campaign approve m68k-core afk campaign work m68k-core --yes --workers 1 --best-of 1 ``` The optional scope file supplies architecture-specific instruction families, interrupt behavior, and exclusions. Without it, the pinned primary oracle defines the complete requested instruction scope. Core campaigns default to 16 active hours, 8 batches, 120 total tasks, and 20 tasks per batch; these ceilings can be lowered or raised within the normal campaign limits at creation time. ### Corpus-backed or other high-risk work Acceptance profiles are deliberately human configured. Before a profiled task starts, attach a profile and one or more **external** evidence roots to explicit task IDs in the saved plan: ```bash # Create and review the saved plan first. afk grillme -d /path/to/project -g "Generate the exporter" --plan-only # corpus_raw_output is the currently enabled high-risk profile. afk acceptance-profile project-name --task-id exporter \ --profile corpus_raw_output --evidence-root /path/to/canonical-corpus ``` The profile command refuses unknown task IDs, duplicate IDs, roots inside the target project, or changes after a task starts. A profiled task must have a clean Git worktree and an AFK-managed task branch before it can mutate code. It cannot merge until deterministic review and independent acceptance validation both pass. A failed validator retains the branch for inspection. `corpus_raw_output` requires an immutable source-backed evidence packet. AFK compares each declared generated artifact byte-for-byte with the referenced raw source excerpt; parsed common fields are not enough. Profile names for API, migration, security, and deployment work are reserved but fail closed until their trusted validators are implemented. See [the safety and recovery guide](docs/research-validation-recovery.md) for the complete lifecycle, migration notes, and recovery procedure. ### Recovery and manual retry Automatic recovery is off by default. Enable `recovery.mode: bounded` before creating a new plan to permit at most the configured researcher supplement or high-reasoning semantic repair. Repeated validator findings, repeated evidence, provider failures, verifier failures, and exhausted budgets remain escalated. An unchanged deterministic failure is fingerprinted from its kind, diagnostics, evidence identity, and relevant file hashes. Reproducing that fingerprint stops automatic repair with `repeated_failure` instead of spending another pass. Use `afk retry project-name task-id` to review the selected recovery action and perform an explicit retry. If a bounded automatic budget is exhausted, add `--force-recovery` only after inspecting the retained task branch and evidence. An explicit missing-evidence retry invokes the read-only researcher before it invokes the coder. When that retry resolves the final escalated task in a campaign plan, AFK also clears the stale campaign escalation so `campaign work` can resume. ### HITL (Human-in-the-Loop) ```bash afk grillme -d ./project --hitl # approve each destructive action ``` ### Flags | Flag | Description | |---|---| | `-d`, `--project-dir` | Project directory (default: `.`) | | `-g`, `--goal` | Goal string (skips interactive interview) | | `-y`, `--yes` | Auto-approve all prompts | | `--hitl` | Approve each file write and shell command | | `--auto-resume` | Run additional queue passes until completion or a safe stop condition | | `--max-auto-resume-passes` | Hard cap on automatic queue passes | | `--lint-mode` | Explicit `strict` or brownfield `baseline` review policy | ## How It Works 1. **Interview** — asks about your goal, language, framework, constraints 2. **Clarify** — LLM asks 2-3 clarifying questions before planning 3. **Decompose** — breaks the goal into a dependency-ordered task DAG 4. **Execute** — each task runs in an agent loop with a bounded, task-specific context rather than all historical memory 5. **Review** — AFK runs task-scoped formatting, lint, tests, Git whitespace checks, and the selected strict/baseline lint policy 6. **Validate** — profiled tasks additionally require immutable evidence and an independent read-only validator before branch merge 7. **Save** — plans, attempts, evidence references, recovery budgets, and context provenance are persisted incrementally ### Reporting and operations The result report includes task status plus evidence revision/fingerprint, validator findings, recovery state, and a per-attempt table with role, endpoint/model, reasoning effort, outcome, and bounded-context source/token counts. Verification and recovery infrastructure failures are identified separately from source, test, and lint failures. Reviewer output shown in the terminal is bounded, but the complete UTF-8 stdout and stderr for each deterministic command is stored outside the target project under `~/.afk-developer/projects//diagnostics/`. Each attempt persists the command, exit code, elapsed time, display truncation metadata, output hash, and full artifact path in the saved plan. For brownfield lint debt, create or deliberately refresh a baseline before a baseline-mode run; AFK never refreshes it during resume. Use `afk maintain-state project-name` only when no other AFK process is active to prune redundant state and compact the Cortex database. The reliability and baseline policy is in [docs/reliability-and-baseline-lint-plan.md](docs/reliability-and-baseline-lint-plan.md). ## Engineering case study [AFK runner case study](docs/afk-runner-case-study.md) records the live-run failures that shaped bounded recovery, durable state, transcript/discovery controls, and supervised task-contract correction. It distinguishes observed results from remaining proof obligations rather than treating a green task table as a general autonomy claim. [The stabilization fitness review](docs/stabilization-fitness-review.md) records the execution-parity, decomposition, repeated-failure, and diagnostic changes required before the next controlled canary. Round 3 remains frozen. ## Architecture ``` afk_developer/ ├── cli.py # CLI entry point (Click) ├── config.py # Config, SessionStats, .env loader ├── execution.py # Canonical environment/governance preflight ├── utils.py # Robust JSON extraction from LLM responses ├── reporter.py # Results table + session statistics ├── grillme/ │ ├── interviewer.py # Interactive project interview │ ├── questions.py # Auto-detect language/framework/test/linter │ └── spec_model.py # TaskSpec, TaskIntent models ├── planner/ │ ├── decomposer.py # LLM-driven task decomposition │ ├── task_model.py # TaskNode, TaskPlan, priorities │ └── clarify.py # Pre-planning clarifying questions ├── scheduler/ │ ├── queue.py # Plan executor (topological order) │ ├── worker.py # Per-task LLM agent loop with tool calling │ ├── verification.py # Typed read-only pytest/Ruff/Git/baseline verifier │ ├── acceptance.py # Trusted acceptance-profile validation │ ├── task_context.py # Bounded, source-attributed per-attempt context │ ├── reviewer.py # Post-task linter + test runner │ ├── git_manager.py # Git branch isolation per task │ └── tools/ │ ├── file_ops.py # read_file, write_file, edit_file, glob │ ├── shell.py # run_command │ └── codebase.py # discover_project, list_directory, grep └── cortex/ ├── db.py # SQLite persistent + fading memory ├── models.py # Memory models └── reflector.py # LLM-powered memory consolidation ``` Immutable evidence packets are stored outside the target project under `~/.afk-developer/projects//evidence//revision-.json`. ## Verified Builds The runner has autonomously built and tested: | Project | Tasks | Tests | Tokens | |---|---|---|---| | Game of Life | 7 | 30 | 450K | | 2D Physics Sandbox | 12 | 214 | 1.4M | | Block-World (Terraria-like) | 19 | 846 | 5.8M | ## Development ```bash pip install -e ".[dev]" # install with pytest and ruff ruff check . # lint python -m pytest tests/ # test ```