# AFK Developer — Scaling Briefing (for Fable-class planning model) > **2026-08-04 addendum**: confirmed root-cause numbers, a cost/capability tier discovery, and a > greenlit git-worktree fix design have been folded in below (marked *(addendum)*). Original > analysis is otherwise unchanged. > > **2026-08-04, later same day — implemented**: §6a's scoping fix (`make_batch_goal` sizing + > raised `CampaignLimits` + per-campaign bounded recovery defaults + effort-scaled `max_turns`) > and §8a's git worktree design are now implemented and merged (see repo memory > `/memories/repo/afk-developer.md` and session memory `/memories/session/plan.md` for exact > diffs). Treat those two sections as **done**, not proposals, in any future planning pass — > the remaining open surface is the phase tier (§9/§11) and foreman/coder-pool fan-out (§9/§11), > for which Stage 1 (worktrees) is now a real, tested prerequisite rather than a future one. ## 0. Purpose AFK Developer already exposes wall-clock budgets up to 24 hours (`afk campaign create --max-hours`), yet real runs stop after roughly 30 minutes of autonomous work. This document is a complete, dense context dump of the current architecture, the specific numeric governors that actually terminate a run early, the hard invariants any redesign must preserve, and the project owner's own (tentative, unresolved) ideas for extending it. **Ask**: produce a concrete, staged implementation plan that lets AFK Developer productively run unattended for multiple hours, by adding one (or more) orchestration tier(s) above "campaign" and by making the AI role roster elastic (able to escalate a struggling task to a smarter model that fans it out to a pool of coder workers) — reusing existing primitives listed in §10 wherever possible. ## 1. System in one paragraph AFK Developer is a Python/Click CLI that autonomously plans and executes coding work using routed LLM calls. A human goal is decomposed by a **reasoner** into a dependency-ordered task DAG (`TaskPlan`/`TaskNode`); a **coder** executes each task via a bounded tool-calling agent loop (read/write/edit file, shell, grep, glob, typed verification); a deterministic **reviewer** (tests/lint/format/diff-check) gates completion; optional **researcher**/**validator** roles handle read-only evidence gathering and independent acceptance checks for high-risk ("corpus-backed") work. All state (plans, attempts, evidence, recovery budgets) is persisted incrementally to disk/SQLite so any process can resume. A **campaign** is a durable wrapper that chains multiple such plans ("batches") toward one long-lived objective, bounded by human-set ceilings (hours, batches, tasks, cost). ## 2. Current role taxonomy | Role | Default model | Default effort | Read/Write | Purpose | |---|---|---|---|---| | `reasoner` | `gpt-5.6-terra` | (unset/normal) | n/a (text only) | Clarifying questions, task decomposition, campaign checkpoint reflection, stall consultation | | `coder` | `gpt-5.6-terra` (example configs show `gpt-5.6-luna` for the lighter/cheaper role) | medium (when using luna) | Read + write + shell | Executes exactly one `TaskNode` per attempt via tool loop | | `researcher` | inherits reasoner (`gpt-5.6-terra`) | high | **Read-only** | Proposes source-backed evidence packets; cannot write source, format, commit, merge, push, or use network/DB tools | | `validator` | inherits reasoner (`gpt-5.6-terra`) | high | **Read-only** | Independently validates a completed profiled task before merge | Naming convention already in place: **Terra = heavy/reasoning persona**, **Luna = lighter/execution persona**. This is exactly the "Luna coders" idea the project owner is reaching for — it already exists as a model-naming convention, just not yet as a multi-worker pool. `xhigh` reasoning effort exists but is never auto-selected (`xhigh_requires_explicit_enable: true`); all four roles today are a **1:1 role→single-model-call mapping**, resolved by `BackendRegistry.get_reasoner() /get_coder()/get_researcher()/get_validator()` (`afk_developer/backends/registry.py`). There is no concept today of *N* coders, a coder pool, or dynamic role instantiation. ## 2a. Cost/capability tier discovery *(addendum)* The project owner has since found that inexpensive routes are surprisingly capable: **DeepSeek v4 flash** (very cheap/fast), **DeepSeek v4 pro** (cheap, more capable), and the existing **Luna** coder route are all cheap enough to change the economics of an elastic team. This upgrades the role design from a binary Terra/Luna split to a **cost/capability ladder**: | Rung | Candidate route | Role | Cost | Best for | |---|---|---|---|---| | 0 | DeepSeek v4 flash (`openai_compatible`) | disposable executor | lowest | high-volume fan-out subtasks, first-try/best-of-N attempts, mechanical edits | | 1 | Luna / DeepSeek v4 pro | primary executor | low | today's normal `coder` role work | | 2 | Terra, `high` effort | reasoning/architect | high | decomposition, reflection, checkpoint judgment, stall/decompose consultation | | 3 | Terra, `xhigh` (explicit opt-in only) | last-resort reasoning | highest | only when rung 2 itself is stuck, human-gated | Implications for the elastic-team design in §9: - A coder-pool fan-out is now **cheap to over-provision** — running several parallel rung-0/1 workers on fanned-out subtasks, or even redundant/competing attempts on the same subtask (best-of-N, keep the first to pass review), is economically trivial, not just architecturally flexible. - "Escalate to a smarter model" doesn't have to mean a single jump straight to Terra — it can be a **ladder**: try cheap/fast first, escalate one rung at a time, only reaching Terra-guided decomposition (or a human) after cheaper rungs are exhausted. - DeepSeek is already a supported `EndpointType.OPENAI_COMPATIBLE` backend (`afk_developer/backends/openai_compatible.py`) — adding flash/pro as additional role routes is config-only, no new backend code required, so this ladder is cheap to prototype. ## 3. Execution hierarchy today ``` Task (TaskNode) — smallest unit; one bounded agent attempt (≤12 tool-calling turns) └─ Plan (TaskPlan) — flat dependency DAG of tasks, produced by ONE decomposer LLM call └─ Batch — one saved Plan, run to completion (or escalation) by the queue └─ Campaign — a named, durable objective spanning multiple batches ``` - `afk_developer/planner/decomposer.py::decompose_task()` — single LLM call turns a goal string into the **entire flat task list** for one batch. No recursive/hierarchical decomposition exists; a task cannot itself contain a sub-DAG. - `afk_developer/scheduler/queue.py` — executes one `TaskPlan` in topological/priority order, invoking worker → reviewer → (optional) acceptance validator → (optional) bounded recovery per task. - `afk_developer/scheduler/worker.py::Worker.execute_task()` — the actual tool-calling loop (`max_turns` turns, tools: `read_file`, `write_file`, `edit_file`, `glob_files`, `run_command`, `run_verification`, evidence readers, `task_complete`/`task_blocked`). - `afk_developer/campaign.py` — the durable, multi-batch orchestration layer (two modes, see §4). ## 4. Two campaign execution modes | | **Batch-reflect mode** (`campaign run`) | **Durable single-queue mode** (`campaign step` / `work`) | |---|---|---| | Planning | Reasoner re-plans a **new** small batch (own DAG) after every checkpoint | Reasoner plans the **whole queue once**; never re-plans | | Progress unit | One full batch run to completion, then a reflection call | Exactly one **leased task** per `continue_campaign_once()` call | | Reasoner touchpoints | Every batch boundary (create + reflect) | Only initial planning + on genuine **stall** (no ready task) | | Concurrency primitive | none | `TaskNode.leased_at/lease_expires_at/lease_owner` (PID) — lets independent short-lived processes safely claim one task each without double-execution | | Designed for | One long foreground/cron invocation | Repeated invocation from independent processes (cron/Task Scheduler) | | Stuck-task handling | Reflection can only choose `complete` / `continue` / `escalate` for the *whole batch* | `consult_terra_on_stall()` can retry **exactly one** `FAILED`/`ESCALATED` task with a short note, once per distinct stall fingerprint, else escalate | Both modes share the same underlying `execute_plan()` queue, worker, reviewer, and recovery machinery — they differ only in *when* the reasoner is consulted and how much is (re)planned at once. ## 5. Numeric governors (the real ceiling) | Governor | Default | CLI max | Where | |---|---|---|---| | `max_turns` per task attempt | **50** (Worker default; coder call sites never passed it explicitly) | — | `scheduler/worker.py` (the `12` at queue.py:271/481 is the **researcher/validator** turn cap, a different, correctly-small budget for their bounded read-only calls) | | `max_retries` per task (same-approach retry before escalation) | **3** | — | `TaskNode.max_retries` | | Coder call timeout | 900s | — | `config.example.yml` | | Reasoner/researcher/validator call timeout | 300s | — | `config.example.yml` | | `reflection_interval` (fading→permanent memory consolidation cadence) | every **5** fading writes | — | `Config.reflection_interval` | | Campaign `max_batches` | **4** | 24 | `CampaignLimits` / `--max-batches` | | Campaign `max_total_tasks` | **24** | 200 | `CampaignLimits` / `--max-total-tasks` | | Campaign `max_tasks_per_batch` | **8** | 30 | `CampaignLimits` / `--max-tasks-per-batch` | | Campaign `max_active_seconds` | 14 400s (4h) | **86 400s (24h)** | `CampaignLimits` / `--max-hours` | | Campaign `lease_seconds` (max time one task holds its lease) | 1 200s (20 min) | 14 400s | `CampaignLimits` | | Campaign `max_queue_steps` (durable mode) | **200** | 5 000 | `CampaignLimits` | | `max_auto_resume_passes` | 10–12 | 100 | `Config` / `CampaignLimits` | | Recovery: `semantic_repair_limit` | **1 per task** | — | `RecoverySettings` (mode defaults **off**) | | Recovery: `research_supplement_limit` | **1 per task** | — | `RecoverySettings` | | Recovery: `high_reasoning_repair_limit` | **1 per task** | — | `RecoverySettings` | | `terra_stall_retries_remaining` | **1 per task per campaign** | — | `TaskNode` | | Per-attempt bounded context | 12 000 chars (~3 000 tokens) | — | `scheduler/task_context.py::MAX_CONTEXT_CHARS` | | Durable safety loop cap | 10 000 iterations | — | `run_campaign_queue_until_terminal` (not a real constraint) | Verified real-world scale (from README "Verified Builds"): Game of Life = 7 tasks/450K tokens; Physics Sandbox = 12 tasks/214 tests/1.4M tokens; Block-World = 19 tasks/846 tests/5.8M tokens. **19 tasks is the largest run ever completed.** The `max_total_tasks` default (24) and `max_batches` default (4) sit right at that ceiling. ## 6. Why runs stop at ~30 minutes despite a 24h wall-clock allowance (analysis, not measured fact) The wall-clock/cost budgets are generous, but every *other* governor is tuned for short, cautious, closely-supervised bursts: - A batch is capped at 8 tasks; a campaign at 24 tasks / 4 batches total — far short of an "hours" scale project, which plausibly needs 50–200+ tasks. - Any task that fails deterministic review gets at most 3 same-approach retries, then escalates. - Any task needing acceptance recovery gets **exactly one** semantic repair *or* one research supplement, ever — never both, never a second attempt, and never a genuinely different strategy (e.g., breaking the task down). It just escalates. - A stalled durable queue gets **one** Terra-guided retry per distinct stall state, else escalates. - Batch-reflect mode's checkpoint reasoner can end the whole campaign by choosing `complete` after just one small batch if it judges the objective satisfied. - Net effect: the system is far more likely to hit an escalation or an early "complete" verdict than to exhaust its time/cost budget. **Escalation-for-a-human is the dominant terminal state today, not budget exhaustion** — which reads to a user as "it only ran for ~30 minutes." ## 6a. Confirmed empirical numbers *(addendum — ground truth, supersedes the hypothesis above)* The project owner confirms the actual pattern: **a Luna task attempt usually runs ~10 minutes, and a campaign is usually broken into ~3 tasks** → 3 × 10 min ≈ 30 min. Root cause per the owner: **"tunable variables set too low"** — i.e. this is a **configuration/scoping problem, not primarily an escalation problem**: - Each task finishing in ~10 minutes is well inside the 50-turn Worker default (corrected from an earlier misreading of this document — see §5), so the per-attempt turn budget is *not* the binding constraint. - ~3 tasks per campaign is far below the `max_tasks_per_batch` default (8) and `max_total_tasks` default (24) — meaning the **decomposer itself is scoping small batches**, and/or the owner has been accepting conservative `campaign create` flags (`--max-batches`, `--max-tasks-per-batch`, `--max-hours`) rather than pushing them toward the CLI-allowed maximums (24 / 30 / 24h). - The 1-shot recovery budgets (§5) remain a **real, latent secondary constraint**: they haven't been the dominant cause yet because campaigns have been small and short, but they *will* start binding as soon as batch/task ceilings are raised and runs get longer — more tasks and more wall-clock time both increase the odds of hitting a task that needs more than one repair attempt. Fable's plan should address both: (1) why batches are scoped small, and (2) the 1-shot recovery ceiling, since raising only the former will just relocate the ~30-minute wall from "campaign ends early" to "first hard task escalates." ## 7. Hard invariants — must survive any redesign These are deliberate safety properties documented across README/AGENTS.md/docs; do not erode them for the sake of scale: 1. **Durable, resumable, incremental state** — every transition is saved immediately (not just at the end); any process can resume after a crash/interruption. 2. **Escalation is a valid, safe terminal state**, not a bug to be papered over. A larger system should still know how to stop and ask a human, just less eagerly. 3. **Acceptance profiles and evidence roots are human-owned and immutable once a task starts** — no model (reasoner, coder, or a future "orchestrator" role) may create, alter, or approve them. 4. **Bounded, source-attributed context per attempt** — no role gets full historical memory; context is deliberately small and provenance-tracked (`context_source_ids`). 5. **One live process per campaign today** (`CampaignStore.acquire_run_lock`, PID-liveness checked cross-platform) — any concurrency design must explicitly renegotiate this lock, not silently bypass it. 6. **Deterministic review (tests/lint/format/diff-check) always gates completion** — no role can mark a task passed by assertion alone. 7. **Recovery budgets are small and explicit by design** (`recovery.mode` defaults **off**) — the project owner opts in deliberately; any new escalation/fan-out path should be similarly opt-in and budgeted, not unlimited. ## 8. Concrete capability gaps vs. "hours-scale autonomous development" - **Flat, single-shot decomposition.** `decompose_task()` produces the whole DAG in one call with no ability to recursively expand a single task into a sub-plan later. - **No re-decomposition on struggle.** Today's only "smarter model helps" path is *semantic repair* (same coder role, higher reasoning effort, same task, same scope) or a *research supplement* (more evidence). There is no path where a reasoner looks at a stuck task and says "split this into 3 smaller tasks for fresh attempts." the project owner's "Luna coders" idea directly targets this gap. - **Single coder role, no worker pool.** `BackendRegistry.get_coder()` returns exactly one backend. Nothing in the codebase instantiates multiple concurrent coder workers. - **Git is a single working tree, checked out sequentially.** `GitManager` wraps one `Repo(project_dir)` and calls `branch.checkout()` in place (`afk_developer/scheduler/git_manager.py`). Two tasks cannot run concurrently against the same project directory today without stepping on each other's checkout. `git worktree add` (separate working directories sharing one `.git`) or per-task clones would be required for true parallelism. Task **leasing already exists** as the concurrency-safety primitive for *independent process* dispatch, but it assumes serialized git access. - **Campaign-level exclusive run lock.** Only one live process may advance a *given* campaign at a time (`acquire_run_lock`). Parallel coder workers on one campaign would need this renegotiated (e.g., lock per task-lease instead of per-campaign, or a supervisor process that owns the lock and fans out sub-processes/threads internally). - **Memory is flat key/value.** Cortex has only `permanent` (durable) and `fading` (TTL'd) memory plus a reflection pass every 5 fading writes that promotes select insights. There is no per-phase or per-epic summarization tier — across a multi-hour, multi-phase run this will either lose context or grow unbounded. - **No notion of "phase"/"level" above campaign anywhere in the code.** This really would be new ground, not a rename of something existing. ## 8a. Git worktree fix — greenlit, recommended design *(addendum)* The project owner has decided it's time to fix this (previously deferred). Recommended shape, kept deliberately decoupled from the phases/roles decisions so it can land as a standalone, low-risk, backward-compatible prerequisite that unblocks *any* concurrent-execution design Fable proposes: - **Where worktrees live**: outside the project directory, alongside the existing evidence-packet convention — e.g. `~/.afk-developer/projects//worktrees//` — not nested inside `project_dir`, so codebase-discovery tools (`discover_project`, `glob_files`, `grep_codebase`) never accidentally wander into a sibling task's worktree. - **`GitManager` additions**: `create_task_worktree(task_id) -> Path` wrapping `git worktree add -b ` (or reusing an existing task branch, mirroring today's `checkout_or_create_task_branch` resume semantics); `remove_task_worktree(path)` wrapping `git worktree remove`/`prune` on completion, merge, or discard. - **Thread the working directory through, not just the branch**: today `Worker`, `review_task()`, and the file/shell/codebase tools all assume one shared `project_dir`. Concurrent execution needs each task attempt to resolve paths against *its own* worktree path instead — this is the main mechanical (if unglamorous) part of the change, touching `scheduler/worker.py`, `scheduler/reviewer.py`, `scheduler/tools/file_ops.py`, `scheduler/tools/shell.py`, and `scheduler/tools/codebase.py`. - **Merging stays centralized**: final merge to `main`/`master` still happens from the primary checkout (today's `merge_to_branch`), so merge ordering/conflicts are handled in one place even when several worktrees produced branches concurrently. - **Lease/cleanup symmetry**: an abandoned worktree (crashed process) should be reaped the same way `reap_expired_leases()` already reaps an abandoned task lease — a companion cleanup pass that removes orphaned worktrees for expired leases. - **Explicitly out of scope for this fix alone**: relaxing `CampaignStore.acquire_run_lock`'s one-process-per-campaign rule. Worktree support only gives the *ability* to check out multiple branches concurrently; whether that's exploited by threads/subprocesses within one `campaign work` invocation, or by relaxing the cross-process lock, is a bigger orchestration decision that should stay with Fable's phases/roles plan. - **Windows note** (relevant — this workspace is Windows): `git worktree` works fine via GitPython/CLI on Windows, but watch for path-length limits and antivirus/file-lock contention when multiple worktrees are created/removed in quick succession; add retry-on-remove as a defensive measure. - This is a good candidate to implement **now, independent of the Fable plan**, since it changes nothing about today's sequential behavior (nothing dispatches concurrently yet) and removes a blocker every version of the coder-pool idea would otherwise hit. ## 9. The project owner's own brainstormed directions (open hypotheses — evaluate, don't assume) Given verbatim/paraphrased because the owner is explicitly unsure of the right shape: - Suspects the **campaign pattern will get rebuilt again, one level higher** — tentatively called **"phases."** Also floated needing **one more level above that**, but is unsure ("I don't know"). Open question for Fable: is the right structure `Campaign → Phase → Batch → Task` (insert one tier), or `Phase → Campaign → Batch → Task` (add a tier *above* campaign, campaign keeps its current meaning), or something else entirely (e.g., collapse batch-vs-durable-queue into one concept first)? What distinguishes a "phase" from a "campaign" structurally — different reflection cadence? Different role permissions? Different human-approval requirements? - Wants **AI roles extended to mirror a larger team's division of labor**, with explicit flexibility as a goal in itself. Concrete example given: *if the coder model struggles to complete a task, escalate to a smarter model that breaks the task into smaller pieces for a set of "Luna coders" to work on* — i.e., dynamic task fan-out triggered by difficulty, not a fixed plan. This implies at minimum: - A new escalation outcome (beyond semantic-repair / research-supplement / escalate-to-human): **"decompose and fan out"**, invoked by the reasoner (Terra) when a coder (Luna) exhausts its normal retries. - Support for **multiple concurrent (or sequential) coder workers** consuming the resulting sub-tasks — which runs straight into the git-worktree and campaign-lock constraints in §8. - Possibly a **richer role roster** beyond reasoner/coder/researcher/validator (the owner does not specify new names/roles — this is open for Fable to propose, informed by the Terra=reasoning/Luna=execution convention already in place). - General ask: **flexibility** — the mechanism for "smarter model intervenes and reorganizes work for a pool of workers" should probably be a reusable pattern, not a one-off special case wired only into the "coder stuck" scenario. ## 10. Reusable building blocks already in the codebase (don't reinvent) - **Task leasing** (`leased_at`/`lease_expires_at`/`lease_owner`) + `reap_expired_leases()` — already solves "safely claim one unit of work from a shared durable queue across independent processes." Directly reusable for a coder pool, provided git access is also parallelized. - **Stall consultation pattern** (`consult_terra_on_stall` → `StallDecision` → `apply_stall_decision`, deduped by `plan.state_fingerprint()` hash) — a clean template for "consult a smarter model only when deterministic logic is stuck, apply a narrowly-typed decision, dedupe repeats." The fan-out/decompose idea in §9 could follow this exact shape: a new `StallDecision`-like type whose action is `"decompose_task"` with a list of new sub-`TaskNode`s. a smarter model when deterministic logic is stuck, apply a narrowly-typed decision, dedupe repeats." - **Recovery coordinator pattern** (`RecoveryDecision` dataclass: action + reason + budget check, `schedule_recovery()` persists the transition before the next call) — same shape could govern a new "decompose" recovery action with its own budget field (e.g., `decompositions_remaining`). - **Campaign statistics aggregation** (`build_campaign_statistics`, dedup by `attempt.id` across all batch plans) — already handles "roll up usage/cost across many plans without double-counting"; a phase-level rollup would follow the same dedup-by-attempt-id shape. - **Evidence/acceptance profile immutability model** — precedent for "the model proposes, only a human-set policy object approves/bounds it," which a new "team topology" or "fan-out budget" policy should probably copy (human sets max coder-pool size / max decompositions per campaign, same way `--max-tasks-per-batch` etc. work today). ## 11. Open questions for Fable to resolve 1. Where does the new hierarchy tier go: above campaign, between campaign and batch, or is "campaign" itself renamed/repurposed? How many tiers are actually justified (owner floated one, then wondered about a second, with no conviction)? 2. What triggers promotion to a new phase vs. just another batch/reflection cycle within the current campaign? (Time elapsed? Task-count threshold? A reasoner judgment call, like today's `complete`/`continue`/`escalate`?) 3. How is a coder-pool fan-out **bounded** (max concurrent Luna workers, max decomposition depth, max total sub-tasks spawned from one stuck task) so this doesn't become unbounded self-replication? 4. How does execution concurrency actually work given §8's constraints — `git worktree add` per concurrent task? Per-task ephemeral clones? Or keep execution serial but pipeline planning ahead of execution? 5. Does the campaign-level exclusive run lock get renegotiated (e.g., one supervisor process holds it and internally parallelizes), or replaced with finer-grained per-task locking layered on top of the existing lease mechanism? 6. Should "decompose and fan out" be allowed to trigger from *any* task failure kind, or only specific ones (e.g., not for `PROVIDER_UNAVAILABLE`/timeout-type failures, which aren't the coder's fault)? 7. How should memory/context scale across a multi-hour, multi-phase run without violating the bounded-context invariant (§7.4)? Does "phase" get its own reflection/summarization tier above today's 5-fading-writes cadence? 8. Should the new tier(s) get their own CLI verbs (`afk phase create/run/status`, mirroring `afk campaign ...`), or extend the existing campaign commands with new flags? 9. Backward compatibility: existing saved `CampaignState` JSON files must keep loading. What's the migration path if the data model gains a phase layer? ## 12. Ask Produce a concrete, staged implementation plan — new/changed data models (Pydantic classes), new CLI surface, execution/orchestration changes, and a migration path for existing saved campaign state — that lets AFK Developer productively run unattended for multiple hours instead of ~30 minutes, by (a) adding whatever new orchestration tier(s) above "campaign" are actually justified, and (b) making the AI role roster elastic enough that a stuck coder task can be escalated to a smarter reasoning pass that decomposes it for a bounded pool of coder workers. Reuse the primitives in §10 wherever the shape fits, and respect every invariant in §7. The git worktree fix in §8a is treated as a **given prerequisite** (either already landed or landing immediately before this plan starts) — assume it and design concurrency on top of it rather than re-deriving it. Also explicitly address the §6a risk: raising batch/task ceilings alone will just move the ~30-minute wall to the first task that needs more than one recovery attempt, unless the 1-shot recovery/stall budgets are redesigned in the same pass.