---
name: rewrite-minimal
description: "Minimal-LOC project rewrite pipeline. Deep-scans a project or chosen subsystem, extracts user-observable features with evidence, validates the feature list independently, captures golden I/O fixtures from the running system, researches alternative stacks/languages, discusses features with the user in batches with LOC deltas, rewrites TDD-first with minimal LOC, validates implementation conformance independently. Use when the user wants to reduce AI slop / LOC in a project without losing features, wants to rewrite a subsystem minimally, or invokes /rewrite-minimal."
argument-hint: "[--resume] [--rewind <phase>] [--scope <id>] [--new-scope]"
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash
  - Glob
  - Grep
  - AskUserQuestion
  - Agent
  - WebSearch
  - WebFetch
---

# rewrite-minimal

Pipeline for rewriting a project (or a chosen part) to minimal LOC via feature extraction, TDD, and independent validation. The orchestrator (you) drives phases, spawns subagents, enforces output discipline, and persists state to files so any phase can resume or rewind.

## Core principles — read before every phase

1. **Feature = testable invariant with file:line evidence.** Not a fuzzy noun. If a feature has no evidence anchor, it's a hallucination — drop it.
2. **Validators are independent subagents with zero producer context.** Same context = rubber stamp. Spawn via `Agent` tool as fresh instances.
3. **File-based state.** Every subagent writes only its own namespace. You read the union. No in-memory handoff.
4. **Hard output budget per phase gate: ≤15 visible lines, one question, overflow → file path cited.** The user wants features and decisions, not narration.
5. **Loop, don't fail.** P2 and P8 validators produce findings; the producer subagent re-runs with findings as input. User only sees the loop iteration count and any disputed items.
6. **Work in scope.** Every phase respects the active scope (directory / module / subsystem). Cross-scope references are contract boundaries, not rewrite targets.
7. **Parallelize where safe.** Extraction, research, and fixture capture per-surface run as parallel `Agent` calls in a single message.

## Invocation handling

On start, read `pipeline/registry.json` if present.

- `--resume`: load `state.json` for active scope, continue from current phase.
- `--rewind <phase>`: roll state back to `<phase>`, mark downstream artifacts stale in state, re-enter phase.
- `--scope <id>`: switch active scope.
- `--new-scope`: force scope selection prompt.
- No args, no state: enter Scope Selection.
- No args, state present: show 1-line status + `AskUserQuestion` {resume current scope | pick another | new scope | rewind}.

## Phase map

```
P_scope  Scope Selection          (pre-phase, runs once per scope)
P0       Dead Code Purge
P1       Feature Extraction       (parallel subagents)
P2       Feature List Validation  (independent validator + fix loop)
P3       Golden Fixture Capture   (requires real config/data)
P4       Stack Research           (parallel, web, open-ended)
P5       Feature Discussion       (batched, LOC deltas, anti-features)
P6       Architecture & Plan      (per-phase split)
P7       TDD Implementation       (plan-phase loop)
P8       Implementation Validation (independent validator + fix loop)
P9       Diff Report
```

Read `PHASES.md` for per-phase instructions. Read `SCHEMAS.md` for file formats. Read `AGENTS.md` for subagent prompt templates. See `README.md` for install instructions.

## State and layout

Everything for a scope lives under `pipeline/scopes/<scope_id>/`. Registry of scopes lives at `pipeline/registry.json`. See `SCHEMAS.md` for JSON shapes and feature file frontmatter.

```
pipeline/
  registry.json
  scopes/
    <scope_id>/
      state.json
      scope.md                  # scope definition + boundary contract
      scan/deadcode.md
      features/<feat_id>.md     # one file per feature
      fixtures/<feat_id>/*.jsonl
      research/<stack>.md
      anti-features.md
      validation/
        features.md             # P2 report
        implementation.md       # P8 report
      plan/phase-NN.md
      diff.md                   # P9 report
```

## Output discipline (hard rules)

Before any user-visible text, count your lines. If over 15, move detail to a file and cite the path. Never emit code, examples, stack traces, or long lists in visible text — cite a file path. The only tables allowed are short enumerable facts (file counts, pass/fail). Prose between tool calls ≤25 words.

One `AskUserQuestion` per phase gate. If you need multiple answers, batch them into a single question's options or defer to next gate. Validation fix loops do not gate on the user unless the producer disputes a finding.

## Subagent spawn rules

- **Validators (P2, P8):** spawn with `Agent` tool, fresh context, prompt from `AGENTS.md#validator`. Must read code + producer output and independently re-derive findings. Do not pass them prior conversation context.
- **Extractors (P1) and Fixture capturers (P3):** spawn in parallel — one subagent per module / surface. Single message, multiple `Agent` tool calls.
- **Researchers (P4):** spawn in parallel, one per candidate stack. Open-ended — let them explore. At P4 start, detect notebooklm in two steps: (a) scan session skills for any skill whose name contains `notebooklm`, (b) run `command -v notebooklm` via Bash for CLI presence. If skill AND CLI are both present, set `notebooklm_mode: cli` and pass to researchers so they use the `notebooklm` CLI for RAG over official docs. If skill is present but CLI is missing, emit the install hint once (`uv tool install "notebooklm-py[browser]"` + `uvx --from "notebooklm-py[browser]" playwright install chromium` + `notebooklm login`) and proceed this run without notebooklm. If no skill is present, do not recommend notebooklm-py at all — the user has no skill-level integration. After P4 research returns, spawn a loc-matrix subagent to consolidate `per_feature_loc` from every research file into `research/LOC_MATRIX.md`.
- **Planner (P6), Test-writer / Implementer / Verifier (P7):** separate subagents per role, separate contexts. Verifier must not share context with implementer.
- **Anti-feature check (P8):** LLM-based subagent reads new code + `anti-features.md`, reports violations. Do not use grep for this step — anti-features are semantic, not textual.

## Validation fix loop protocol

Used by P2 and P8.

1. Validator subagent writes findings to `validation/<phase>.md` with severity, file:line, and rationale per finding.
2. You read the findings. If any critical: spawn producer subagent again with findings + original inputs, instruct "fix or dispute". Producer either updates artifacts or writes a dispute block per finding.
3. Re-spawn validator (fresh context) on updated artifacts.
4. Repeat until zero critical findings or producer has disputed a finding that the validator continues to raise.
5. On persistent dispute (iteration ≥2 with same finding disputed): surface to user via `AskUserQuestion` with validator position, producer position, and "who's right" options. This is the only user gate inside a fix loop.
6. Record iteration count, final state, and any dispute resolutions in `state.json` under the phase entry.

User sees only: iteration count, current failing count, disputes awaiting decision. Never the raw findings in chat — only file path.

## Scope selection (P_scope)

On first run for a project, enumerate natural boundaries via quick scan:

- Top-level source dirs (`src/`, `crates/*`, `packages/*`, `apps/*`, `services/*`)
- Language / framework boundaries
- Declared modules from manifest (`Cargo.toml` members, `package.json` workspaces, `go.mod`, `pyproject.toml` packages)

Present ≤10 candidates via `AskUserQuestion` with options: "whole project", each candidate, or "custom path". On custom, ask via follow-up question for a path.

Once picked, create `scope.md` with:

- scope_id (slug)
- path glob(s)
- boundary contract: which symbols / APIs / files the scope exports and imports (this is the interface the rewrite must preserve)
- excluded sub-paths

Write to registry. Initialize `state.json` with `phase: "P0"`.

## Resume / rewind mechanics

`state.json` carries `phase`, `status`, `fix_loop_iteration`, `rewind_history`, and per-phase `artifact_hashes`. On rewind: copy current entry into `rewind_history`, set phase to target, mark all artifact files from later phases as stale (do not delete — they are reference for the re-run). Re-entering a phase should diff against stale artifacts and surface what changed, not start from zero.

## Visible output templates per phase gate

Each gate uses roughly this shape. Anything longer → cite the file.

```
P<N> <phase name> <status>
<≤3 lines of essential numbers / findings>
<file paths for detail>
<one question via AskUserQuestion>
```

Example for P2 passing:

```
P2 feature validation: 47 features, coverage 98%, 0 critical
file: pipeline/scopes/core/validation/features.md
proceed to P3?
```

Example for P5 batch:

```
P5 discuss batch 3/6 — storage
6 features, LOC now 1240, stack-A 380, stack-B 510
file: pipeline/scopes/core/features/ (batch_3 listed below)
<question with keep/remove/modify/merge per feature>
```

## When to stop and ask

Stop and ask the user if:

- Scope is ambiguous or boundary contract is not derivable from code.
- P3 cannot find a runnable surface (no tests, no CLI, no server). Warn explicitly that fixtures will be synthetic-only; confirm before proceeding.
- P2 or P8 has a dispute persisting past iteration 2.
- P4 research surfaces a stack that would eliminate a feature the user marked "keep" — surface the conflict.
- LOC budget in P7 is about to be exceeded by >20% — confirm continue or re-plan.

Otherwise proceed. Do not ask about trivia, taste, or naming.

## Anti-patterns (do not do)

- Do not summarize the full pipeline to the user at any gate. They know it.
- Do not emit code in chat. Write it to files.
- Do not re-explain why a feature was removed after the user decided. Move on.
- Do not let validators read the producer's reasoning. Only the artifacts.
- Do not run P3 before the user confirms the system has real config and data.
- Do not spawn sequential subagents when they can be parallel.
- Do not skip the P2 or P8 fix loop — even one iteration catches drift.
