# AFK Developer Reliability and Baseline-Aware Lint Plan ## Context The PeopleSoft Developer run exposed two independent runner failures: 1. A task that reached `ESCALATED` left dependent tasks `BLOCKED`. With `--auto-resume`, the CLI treated blocked tasks as remaining work and repeatedly re-entered `execute_plan()` even though there was no runnable task. 2. A brownfield repository with existing Ruff debt failed every task review, even when the task's new files and all tests passed. The observed incident ran from approximately 8:00 PM PDT on July 16 through 2:11 AM PDT on July 17. It made no provider calls and performed no agent turns during the spin. It persisted 47,886 duplicate run records, enlarged the Cortex database, and accumulated misleading failure statistics. The UTF-8 subprocess capture and optional-output safety fixes already applied in `scheduler/reviewer.py`, `scheduler/tools/shell.py`, and `scheduler/tools/codebase.py` remain part of this work and need regression coverage. ## Goals - Stop automatic execution immediately when a plan needs human intervention or has no runnable work. - Make the stop reason explicit, preserve the resumable plan, and avoid duplicate state writes. - Keep linting a quality gate without allowing unrelated legacy lint debt to reject a task. - Preserve strict whole-repository linting for clean projects. - Limit automatic formatting to task-owned files so an agent never reformats an unrelated dirty repository. - Provide deterministic tests that do not need a model provider. ## Non-goals - Automatically fixing the PeopleSoft repository's existing Ruff debt. - Silently accepting a new lint violation. - Changing task dependency semantics: every declared dependency must still pass before its dependent task can run. - Rewriting existing plan or Cortex history without an explicit maintenance operation. ## Design decisions ### 1. Treat escalation and lack of runnable work as terminal auto-resume conditions `TaskPlan.get_ready_tasks()` already identifies work whose dependencies have passed and whose status is runnable. `TaskPlan.has_escalated()` identifies human-intervention states. Update the `_run_plan()` loop so that, after a complete queue pass and state save: 1. Exit successfully only when `plan.all_done()` is true. 2. If `plan.has_escalated()` is true, save once, report that automatic resumption is halted, show the escalated task IDs, and exit. 3. Otherwise, call `plan.get_ready_tasks()`. - If it is empty, save once, report that no runnable work remains, and exit. - Do not treat `BLOCKED` alone as a reason to resume. 4. Record a status fingerprint before and after each queue pass. If task status, retry count, and blocked reason did not change, halt with a no-progress diagnostic. 5. Add a configurable hard cap on automatic queue passes as defense in depth. The default should be modest (for example, 10) and must halt with an actionable message rather than silently looping. The existing `afk retry ` command remains the explicit recovery path for an escalated task. Once that task passes, `afk resume` can process its unblocked dependents. ### 2. Stop duplicate Cortex persistence during resume cycles Move the `last-plan` permanent-memory update out of the auto-resume loop or replace it with an explicit upsert method for that key. The current per-cycle append behavior multiplied a full task specification into the database during the blocked loop. Add a narrow Cortex maintenance operation that can: - prune duplicate `last-plan` entries while retaining the newest entry; - retain a bounded number of session-stat rows per project; - checkpoint and compact SQLite only when no AFK process is using the database. This maintenance operation must be opt-in and report exactly how many rows and bytes it reclaimed. It must not erase task plans or reflection data. ### 3. Add explicit lint policies Add a `review.lint_mode` setting with these values: - `strict` (default): current behavior; the entire project must pass its configured linter. - `baseline`: accept existing lint debt but reject diagnostics introduced by the AFK task. Expose a command-line override for a run and document the equivalent user configuration. The override must be visible in the terminal review summary and persisted with the saved plan, so a resume uses the original policy. `baseline` is an explicit brownfield mode; AFK must never silently downgrade a strict run. ### 4. Capture and persist a lint baseline before writes For a baseline-mode run, capture diagnostics after planning and before executing the first mutating task. Store the artifact at: `~/.afk-developer/projects//lint-baseline.json` The artifact should include: - schema version; - project name and canonical project path; - linter name and version; - command used; - capture time; - current Git HEAD when available; - normalized diagnostic fingerprints. For Ruff, use its machine-readable JSON output. Normalize paths relative to the project and create a stable fingerprint from the path, rule code, message, and a normalized source-line/context hash. The context hash allows a pre-existing diagnostic to remain recognized if unrelated edits shift its line number. Never refresh a saved baseline during `afk resume`. If a required baseline is missing or incompatible, stop with an actionable message. Provide an explicit baseline-create/refresh command that requires user intent and prints the current Git/working-tree state. ### 5. Apply formatting and local lint only to task-owned files Change `review_task()` to receive normalized task file paths and distinguish: - files newly created by the worker; - pre-existing files changed by the worker; - files outside the task's declared/observed change set. For Ruff: - run `ruff format` only against the task-owned Python files, never `ruff format .` in a dirty brownfield worktree; - run `ruff check` against those same files as an immediate, strict local gate; - in `strict` mode, additionally run the project-wide command and require it to pass; - in `baseline` mode, additionally run the project-wide JSON lint command and fail only on diagnostics absent from the baseline. For non-Ruff linters, retain strict behavior until a structured diagnostic parser is implemented. If baseline mode is requested for an unsupported linter, fail closed with a clear configuration error rather than treating the lint step as passed. Keep the full configured test suite and `git diff --check` as unconditional review gates in every mode. ### 6. Make review results explainable Extend `ReviewResult` with policy-aware fields, including: - lint mode; - local-lint result; - global baseline count; - introduced diagnostic count and short summary; - formatting scope; - whether the lint baseline was loaded successfully. Terminal output should distinguish these outcomes: - `Lint: PASS (strict)` - `Lint: PASS (baseline: 345 existing, 0 introduced)` - `Lint: FAIL (baseline: 3 introduced)` - `Lint: FAIL (baseline unavailable)` A task failure sent back to the coding worker should include only introduced diagnostics and the affected task files, not thousands of unrelated legacy findings. ### 7. Persist the origin of a failed attempt Persist a `failure_kind` and concise `failure_detail` on each task. At minimum, distinguish provider unavailability and provider timeout from worker, test, lint, diff-check, and other review failures. A Copilot authentication, VPN, service, or timeout failure must immediately place the task in `ESCALATED` without consuming an implementation retry. The result table must show that provider recovery is required, and `afk retry` remains the explicit recovery path once connectivity is restored. ## Implementation sequence 1. **Model and configuration** - Add typed lint-policy and auto-resume guard settings in `config.py`. - Parse, validate, and document the user configuration and CLI overrides. - Add serialization fields to the saved plan so resumption preserves review behavior. 2. **Task-plan and auto-resume safety** - Add a small plan-state fingerprint helper in `task_model.py` or `cli.py`. - Update `_run_plan()` to stop on escalation, zero ready tasks, unchanged state, and the hard pass cap. - Ensure a terminal auto-resume state saves and reports once, rather than immediately entering another loop. - Keep `retry` as the only automatic-status reset path for escalated tasks. 3. **Cortex persistence and maintenance** - Prevent repeated `last-plan` append writes during one run. - Implement bounded session-stat retention and opt-in compaction. - Add a command that reports the target state directory, active-process safety check, rows pruned, and database size before/after. 4. **Structured Ruff baseline implementation** - Implement JSON diagnostic capture, normalized fingerprints, atomic baseline save/load, and compatibility validation. - Add the explicit baseline management command. - Thread loaded baseline data through CLI, scheduler queue, and reviewer. 5. **Scoped formatter and reviewer behavior** - Resolve and validate task-owned relative paths before executing formatter/linter commands. - Make formatting task-scoped and keep it disabled for read-only tasks. - Add strict local checks plus policy-specific project-wide lint evaluation. - Preserve the current UTF-8 decoding and absent-stream protections. 6. **Reporting and recovery** - Add concise Rich summaries for halt reason, lint policy, baseline counts, and manual recovery commands. - Add a documented recovery procedure for the current PeopleSoft run: review the partial SRVM diff, retain a baseline deliberately, retry or mark the task only after independent validation, then resume descendants. ## Test plan ### Auto-resume safety - A plan with an escalated root and blocked descendants invokes the queue once under `--auto-resume`, writes one final session record, and exits without a provider call. - A plan with no ready tasks but no escalation exits with a no-progress result. - A plan whose status fingerprint does not change exits after one non-progressing pass. - The hard pass cap halts a deliberately cycling fake plan. - A manual retry that changes an escalated task to passed allows the formerly blocked descendant to run. - A Copilot authentication, network, or timeout failure is persisted as a provider failure, consumes no implementation retry, and does not enter an auto-resume loop. ### Persistence and maintenance - Repeated auto-resume passes do not append duplicate `last-plan` records. - Retention preserves the newest session records and newest permanent `last-plan` entry. - Maintenance refuses to run while an AFK process is active. - Compaction never removes the current `plan.json` or unrelated permanent memories. ### Baseline linting - Strict mode still fails when any project-wide Ruff diagnostic exists. - Baseline mode passes when diagnostics equal the stored baseline and task-owned files are clean. - Baseline mode fails for a newly introduced diagnostic in a newly created file. - Baseline mode fails for an introduced diagnostic in an existing changed file. - A line-number shift for an unchanged existing diagnostic does not create a false positive. - Missing, invalid, wrong-project, or wrong-linter baselines fail closed. - Unsupported linters reject baseline mode clearly. ### Reviewer robustness - UTF-8 output with invalid bytes is decoded with replacement rather than crashing. - Missing stdout or stderr does not cause a `NoneType.strip()` failure. - Ruff formatting is invoked only with task-owned paths. - Read-only reviews never invoke a formatter. ## Acceptance criteria - `--auto-resume` cannot re-enter a plan indefinitely once all remaining tasks are blocked or an escalation requires a person. - One blocked-plan incident yields one final result report and bounded state writes. - A clean project retains full strict lint enforcement by default. - A configured baseline-mode brownfield run rejects new Ruff violations while allowing unchanged legacy debt. - Task formatting never mutates unrelated files solely because the repository is dirty. - The AFK Developer test suite, Ruff lint, format check, and `git diff --check` pass. - The recovered PeopleSoft plan can validate the existing SRVM work under the baseline policy and resume only after explicit human review of the dirty main worktree.