# Session 1 of 3: Split oversized files (mechanical, zero behavior change) You are working in `d:\dev\afk-developer` (Windows, PowerShell, branch `master`). This is the first of three sequential refactor sessions. Your job is **purely mechanical file splitting** — move code between modules with zero behavior change. Session 2 (deduplication/redesign) and Session 3 (event seam + live status view) build on your output; do NOT start their work. In particular: do NOT redesign the `retry` pipeline, do NOT deduplicate anything, do NOT touch console/reporting seams. Move code, keep everything green, commit, stop. ## What this codebase is afk-developer is an autonomous LLM coding orchestrator: a Click CLI (`afk`) that decomposes a goal into a task DAG (`planner/`), executes tasks via LLM worker loops (`scheduler/`, `backends/`), with git branch/worktree isolation per task, deterministic review (ruff + pytest), a recovery/escalation ladder (retries → semantic repair → foreman decompose → escalate), and a durable multi-phase "campaign" layer (`campaign.py`, `campaign_runner.py`). State persists as atomic-write JSON under `~/.afk-developer/projects//plan.json` and `~/.afk-developer/projects/campaigns/.json`. `AGENTS.md` at the repo root documents module boundaries and conventions — read it first. ## Ground rules (non-negotiable) 1. **Re-measure everything first.** Line numbers in this document are approximate snapshots (taken 2026-08-07); the file may have drifted. Locate every span yourself before cutting. 2. **Zero behavior change.** Every move is verbatim relocation + import fixups. If you find a bug while moving, note it in the completion report — do not fix it in this session. 3. **Full test suite green between every move, one commit per move.** Never batch two moves into one commit. If a move breaks tests in a way you can't cleanly resolve, revert it and record why in the completion report. 4. **Known env-specific test failures — never "fix" these, never touch them.** Baseline on this machine is approximately **310 passed, 3 failed**. The 3 expected failures: - `tests/test_config.py::test_default_environment_config_prefers_copilot_without_api_key` (a real `DEEPSEEK_API_KEY` leaks from the repo's gitignored `.env`) - `tests/test_auto_resume_guards.py::test_retry_commits_and_merges_the_resumed_task_branch` - `tests/test_auto_resume_guards.py::test_retry_required_profile_runs_validator_before_merging` (both hardcode branch `"main"`; this machine's git has no `init.defaultBranch` so repos init as `master`) Record their exact failure output at baseline. After each move they must fail **the same way** — a changed failure mode in those tests means your move broke something. Note the last two are `retry` tests: your Task 1 moves exactly the code they exercise. Watch them closely. 5. **Never `git add -A` / `git add --all`.** Stage specific files only. The repo has stray untracked scratch files (e.g. `prompts/*.md`) that must never be swept into a commit. Never touch `projects/` (gitignored demo builds) or `.env` (contains a real API key — never print or commit it). 6. **Commit locally; do not push.** The repo owner pushes manually. 7. **Monkeypatch-preservation rule (this is the key technique for the whole session):** tests monkeypatch module attributes at their historical locations, e.g. `monkeypatch.setattr(queue_module, "review_task", ...)`, `afk_developer.campaign.BackendRegistry`, `afk_developer.cli._save_plan`. When you move code that references such names, have the moved code do a **function-body-local `import afk_developer.cli as cli` (or `import afk_developer.scheduler.queue as queue_mod`) and access names as attributes** (`cli._save_plan(...)`, `queue_mod.review_task(...)`). Attribute access resolves at call time, so every existing patch target keeps working with **zero test edits**. Before each move, inventory the patch targets: `grep -rn "monkeypatch.setattr" tests/` and grep for the names you're moving. 8. **Circular-import rule (established precedent in this repo — see `campaign_runner.py`):** any new module that `cli.py` imports at module level must never import `cli.py` at module level itself — only function-body-local imports. Both modules finish loading before any function runs, so call-time imports are safe. 9. **For large verbatim moves, do not hand-transcribe.** Write a throwaway Python script that reads the source file, slices exact line ranges, adjusts indentation if needed, and prints the assembled new-file content for your review before writing it. This technique was already used successfully in this repo for an ~730-line move (`execute_plan` split). Delete the throwaway script afterward; never commit it. ## Baseline verification (do this before anything) ```powershell cd d:\dev\afk-developer git log -1 --format="%H %s" # record HEAD (expected 5cd1f87 or a descendant) git status --short # must be clean (untracked prompts/*.md strays are OK — leave them) python -m pytest -q # record exact counts; expect ~310 passed, the 3 named failures python -m ruff check . # expect clean ``` Record all four outputs in the completion report as your baseline. ## Current size snapshot (2026-08-07 — re-measure) | File | Lines | Notes | |---|---|---| | `afk_developer/cli.py` | ~2,735 | `retry` command ≈ lines 1587–2633 (~1,050 lines) | | `afk_developer/scheduler/queue.py` | ~1,960 | `execute_best_of_n` ≈ 792–991; `_execute_one_task` ≈ 1152–1918 | | `afk_developer/backends/copilot.py` | ~1,540 | leave alone this session | | `afk_developer/campaign.py` | ~1,240 | models + store + reasoner calls all in one file | | `afk_developer/scheduler/worker.py` | ~850 | leave alone | | `afk_developer/campaign_runner.py` | ~500 | leave alone (already extracted previously) | ## Task 1 — Move the `retry` command body → `afk_developer/scheduler/manual_retry.py` The single biggest win: `retry` in `cli.py` is ~1,050 lines (~38% of the file). 1. Locate the full span: the `@main.command()` decorator stack through the end of `def retry(...)`. Read the decorator stack and note every option/argument (at minimum `project_name`, `task_id`, `--force-recovery`, `--validate-existing` — mirror whatever is actually there). 2. Create `afk_developer/scheduler/manual_retry.py` containing one public function `run_manual_retry(...)` whose parameters mirror the Click command's parameters exactly. Move the command body into it **verbatim** (indentation depth should be unchanged: function body → function body). 3. In the moved body, apply the monkeypatch-preservation rule: at the top of `run_manual_retry`, `import afk_developer.cli as cli` and rewrite references to names that were resolved from `cli.py`'s module namespace (helpers like `_save_plan`, `_load_plan`, `_init_cortex`, `_get_plan_path`, `_safe`, `console`, and anything cli.py imported at module level that the body uses, e.g. `review_task`) as `cli.` attribute access. This keeps every existing `afk_developer.cli.X` patch target working. Names never patched by tests may instead be imported normally at manual_retry's module level from their true source modules — but when in doubt, use the `cli.` attribute form; it is always safe. 4. Reduce `cli.py`'s `retry` to the decorator stack + docstring + a delegate call (`run_manual_retry(project_name, task_id, ...)`). `cli.py` gets a module-level `from afk_developer.scheduler.manual_retry import run_manual_retry` (safe one-way: manual_retry.py has no module-level cli import). 5. Do NOT restructure, deduplicate, or "clean up" the moved body. Session 2 redesigns it; your verbatim move is its required starting point. 6. Verify: full suite (same counts, same 3 failures failing the same way), ruff clean, `afk retry --help` output unchanged. Commit: `Extract manual retry pipeline body into scheduler/manual_retry.py (verbatim move)`. ## Task 2 — Move the `campaign` Click group → `afk_developer/campaign_cli.py` The campaign group (`create`, `plan`, `approve`, `run`, `step`, `work`, `status`, `cancel`) is ~521 lines of `cli.py`. This mirrors a prior successful extraction (`campaign_runner.py`), and the circular-import approach below was already verified against this exact code. 1. Create `afk_developer/campaign_cli.py` defining its **own** group: `@click.group("campaign")` / `def campaign(): ...` — do not decorate `main`. Move every subcommand verbatim, decorated `@campaign.command(...)`. 2. Imports in campaign_cli.py: module-level imports of `campaign_runner`, `campaign`, click, etc. are fine (no cycle). Anything hosted in `cli.py` (`_load_plan`, `_save_plan`, `_validate_plan_name`, `_other_afk_processes_active`, `_init_cortex`, `_prepare_lint_baseline`, `_resolve_lint_mode`, `_get_plan_path`, `_safe`, ...) must be reached via function-body-local `import afk_developer.cli as cli` + attribute access (rules 7/8). 3. In `cli.py`: delete the moved group, add module-level `from afk_developer.campaign_cli import campaign` and `main.add_command(campaign)`. 4. Note: `tests/test_cli.py` imports `_campaign_ensure_queue` (and possibly other `_campaign_*` helpers) `from afk_developer.cli` — those live in `campaign_runner.py` and are re-exported by cli.py's existing import; do not disturb that re-export. 5. Verify: full suite, ruff, `afk campaign --help` and each subcommand's `--help` unchanged. CliRunner-based tests invoking `main` with `["campaign", ...]` must pass untouched. Commit: `Extract campaign Click group into campaign_cli.py`. ## Task 3 — Split `campaign.py` into models / store / orchestration `campaign.py` (~1,240 lines) mixes three concerns. Split by rule, keeping `campaign.py` as the orchestration module and the compatibility façade: 1. Inventory every top-level name in `campaign.py`, then bucket: - **`afk_developer/campaign_models.py`**: pydantic models and enums with no BackendRegistry / queue / IO dependencies — expect `CampaignStatus`, `PhaseStatus`, `PhaseState`, `CampaignLimits`, `CampaignState` (and its pure helper methods like `active_phase`), batch-record and statistics models (`CampaignBatchStatistics`, `CampaignStatistics`), decision models (`StallDecision`, `PhaseReflection`, `QueueStepResult`), and pure helpers like `phase_roadmap_fingerprint` if dependency-free. - **`afk_developer/campaign_store.py`**: `CampaignStore`, `CampaignBusyError`, `_pid_is_alive` and the PID/run-lock machinery (Windows `OpenProcess` via ctypes — move intact, it's deliberate). Imports models; nothing else circular. - **stays in `campaign.py`**: everything that calls `BackendRegistry` or orchestrates queue stepping — `make_batch_goal`, `make_phase_batch_goal`, `plan_phase_roadmap`, `reflect_on_completed_batch`, `reflect_on_completed_phase`, `consult_terra_on_stall`, `continue_campaign_once`, `run_campaign_queue_until_terminal`, `apply_campaign_policy`, `build_campaign_statistics` (aggregation — keep here to minimize churn). 2. `campaign.py` re-imports **every moved name explicitly** (no star imports) so `afk_developer.campaign.X` keeps resolving for all existing callers and tests. Tests patch `afk_developer.campaign.BackendRegistry` — that import stays in campaign.py, unaffected. 3. Verify: full suite (watch `tests/test_campaign.py` closely, including its legacy-JSON migration tests), ruff. Commit: `Split campaign.py into campaign_models.py and campaign_store.py (re-exported)`. ## Task 4 — Extract `execute_best_of_n` → `afk_developer/scheduler/best_of_n.py` 1. Move `execute_best_of_n` (~200 lines) plus any private helper used **only** by it out of `queue.py`. Inside the moved function, use function-body-local `import afk_developer.scheduler.queue as queue_mod` and access former queue-module names as attributes (`queue_mod.Worker`, `queue_mod.review_task`, `queue_mod._finalize_task_branch`, ...) — `tests/test_queue.py`'s best-of-n tests monkeypatch those names on the queue module, and attribute access at call time keeps the patches effective. 2. `queue.py` keeps a module-level re-export: `from afk_developer.scheduler.best_of_n import execute_best_of_n` (safe because best_of_n.py has no module-level queue import). Grep for callers (`grep -rn "execute_best_of_n" afk_developer/ tests/`) — `campaign_runner.py` calls it; leave caller imports working via the re-export. 3. **Hard boundary: do not split `_execute_one_task` itself.** A prior analysis established its ~18 bare `continue` statements make a phase-split risky; it stays intact (Session 2 modifies it deliberately, with design intent). 4. Verify: full suite, ruff. Commit: `Extract execute_best_of_n into scheduler/best_of_n.py`. ## Task 5 (stretch — only if Tasks 1–4 are fully green and committed) Move the acceptance-profile section of `cli.py` (`_configure_acceptance_profile` + its private predicate helpers + the `acceptance-profile` command, ~200 lines) into a new `afk_developer/acceptance_cli.py`, same pattern as Task 2 (own command registered on `main`, function-local cli imports). Skip freely if time or confidence is low. ## What must NOT move (deliberate, previously-litigated decisions) - `cli.py`'s shared primitives: `_safe`, `_validate_plan_name`, `_prepare_lint_baseline`, `_resolve_lint_mode`, `_other_afk_processes_active`, `_run_plan`, `_init_cortex`, `_get_plan_path`, `_existing_project_files`, `_save_plan`, `_replace_with_retry`, `_load_plan`. Moving them reintroduces the circular-import problem the function-local-import pattern exists to solve. (Session 2 relocates the atomic-write primitive properly; not you.) - `backends/copilot.py`, `scheduler/worker.py`, `evidence.py`, `config.py` — untouched this session. ## Definition of done - `cli.py` ≈ 1,000–1,400 lines; `queue.py` ≈ 1,700–1,800; `campaign.py` ≈ 700–800; every new module < 600 lines. - Full suite: same pass count as your recorded baseline (or higher only if unavoidable — you should not be adding tests this session), same 3 env failures failing identically. Ruff clean. - `afk --help` lists the same commands; `--help` for `retry`, `campaign` (and every subcommand) byte-identical to baseline. - `AGENTS.md`'s Module Boundaries section updated with one line per new module. - 4–6 commits, one per move, none pushed. ## Completion report (fill in before ending the session) Append here: baseline HEAD + test counts; per-task outcome (done/skipped/reverted + commit hash); final line counts of every touched file; any test whose monkeypatch target you had to change (should be none — explain if not); anything you noticed but deliberately did not fix (bugs, dead code, further split candidates) for Session 2's awareness. ### Filled in 2026-08-07 **Baseline**: HEAD `5cd1f87` "Add progressive transcript compaction to bound worker context growth". `git status --short` clean except the untracked `docs/refactor-handoffs/` folder itself (left alone, not ours to add). `python -m pytest -q`: 310 passed, 3 failed (the 3 named env-specific failures — `test_default_environment_config_prefers_copilot_without_api_key`, `test_retry_commits_and_merges_the_resumed_task_branch`, `test_retry_required_profile_runs_validator_before_merging`). `python -m ruff check .`: clean. **Per-task outcome — all 5 done (4 required + the Task 5 stretch), nothing skipped or reverted.** Test suite stayed at exactly 310 passed / the same 3 named failures (failing for the same reason each time) after every single commit; ruff stayed clean after every commit (some intermediate `--fix` cleanup of now-dead imports was needed after each move — see below). | Task | Outcome | Commit | |---|---|---| | 1 — `retry` → `scheduler/manual_retry.py` | Done | `66cea9d` | | 2 — `campaign` group → `campaign_cli.py` | Done | `3e5881f` | | 3 — `campaign.py` → `campaign_models.py` + `campaign_store.py` | Done | `13d91da` | | 4 — `execute_best_of_n` → `scheduler/best_of_n.py` | Done | `22ecf82` | | 5 (stretch) — `acceptance-profile` → `acceptance_cli.py` | Done | `3e9c3f6` | | AGENTS.md Module Boundaries update | Done | `d388fb1` | All 6 commits are local only; `git log origin/master..HEAD` matches `git log -6` exactly — nothing pushed. **Final line counts** (vs. the doc's "definition of done" targets): - `cli.py`: 1,033 (target 1,000–1,400 ✓) - `afk_developer/scheduler/queue.py`: 1,656 (target 1,700–1,800; slightly under, fine) - `afk_developer/campaign.py`: 822 (target 700–800; slightly over, fine — see note below) - `afk_developer/scheduler/manual_retry.py`: 837 (new module; this one's inherently large since it's a verbatim move of the single biggest command body — no target given) - `afk_developer/campaign_cli.py`: 556 (< 600 ✓) - `afk_developer/campaign_models.py`: 233 (< 600 ✓) - `afk_developer/campaign_store.py`: 83 (< 600 ✓) - `afk_developer/scheduler/best_of_n.py`: 213 (< 600 ✓) - `afk_developer/acceptance_cli.py`: 212 (< 600 ✓) `campaign.py` (822) is a bit over its 700–800 target because `apply_campaign_policy`, `make_batch_goal`/`make_phase_batch_goal`, and the aggregation helpers (`_USAGE_FIELDS`/`_add_usage`/`_increment_status`/`build_campaign_statistics`) all stay there per the doc's own explicit "stays in campaign.py" list even though several are pure/dependency- free — moving them would have been an easy further trim but would have contradicted that explicit instruction, so left as specified. **Monkeypatch targets**: no existing test's monkeypatch target needed to change. The `import as alias` + attribute-access technique (rule 7) preserved every one verbatim. One thing this technique doesn't cover — a **direct `module.` attribute reference inside a test body** (not a `monkeypatch.setattr` target, just `cli.some_function(...)` called directly) — did bite once and needed a fix, not a monkeypatch change: - **`tests/test_evidence_packets.py`** calls `cli._configure_acceptance_profile(...)` directly (module-attribute access, no top-level import) in 7 places, and `cli.acceptance_profile.callback.__wrapped__(...)` in 1 place. This wasn't flagged anywhere in this doc (unlike Task 2's explicit `_campaign_ensure_queue` warning) and doesn't show up as a lint error since ruff can't see across files — it only surfaces as a test failure. Fixed by adding an explicit re-export in `cli.py`: `from afk_developer.acceptance_cli import acceptance_profile, _configure_acceptance_profile # noqa: F401`. **Lesson for future sessions**: after any extraction, grep the whole `tests/` tree for `\.` (not just `monkeypatch.setattr` calls) before considering the move done — a hand-off doc's own list of what to preserve is not guaranteed exhaustive. Other re-exports needed for the same reason (found by grepping `tests/` directly, not from this doc's text): `cli.py` also keeps `from afk_developer.campaign_runner import _campaign_ensure_queue # noqa: F401` (Task 2, doc-flagged) and, after Task 3, `campaign.py` needed `# noqa: F401` on 4 of its re-exported names (`CampaignLimits`, `PhaseStatus`, `phase_roadmap_fingerprint`, `CampaignBusyError`) that `test_campaign.py` imports directly but that campaign.py's own remaining orchestration code no longer references internally. **Nothing noticed but deliberately left unfixed** — no bugs or dead code spotted during any of the 5 moves (all were exactly as described: real, verified duplication/size problems, no surprises in the actual logic). One observation for Session 2's awareness, not a problem: as predicted in Task 1's own notes, `scheduler/manual_retry.py` (837 lines, almost entirely the old `retry` command body moved verbatim) is now the single largest file this session touched — exactly the ~1,050-line pipeline Session 2's Task 1 is scoped to shrink to ~150–300 lines via unification with `execute_plan`/`_execute_one_task`. No further split candidates identified beyond what Session 2/3 already scope.