Skip to content

Instantly share code, notes, and snippets.

@fatso83
Created July 15, 2026 08:39
Show Gist options
  • Select an option

  • Save fatso83/a9755010c1ab149bfe1df9a3bf94852b to your computer and use it in GitHub Desktop.

Select an option

Save fatso83/a9755010c1ab149bfe1df9a3bf94852b to your computer and use it in GitHub Desktop.
name refactor
description Goal-driven, multi-agent repo refactoring. Grades a codebase against an anchored 1-10 best-practice rubric using fresh, blind grader subagents per module so the orchestrator never drowns in file contents and prior grades cannot leak into new grading runs, synthesizes a phased refactor plan with binary acceptance criteria grounded in real repo baselines, then executes each theme TEST-FIRST in parallel git worktrees as one reviewable MR per theme, and re-grades with fresh blind graders to confirm the target. Includes backend, frontend, UI design-system, CSS/theme-token, visual-regression, and shared primitive audits. Use when the user wants to refactor / clean up / harden a codebase toward a quality target — e.g. "refactor this repo to 8/10", "grade and clean up the codebase", "goal: get this to best-practice", "remove duplication and over-engineering across the repo". Pairs with /torvalds (the grading lens) and the project's worktree/deploy skills (the MR mechanics).

Refactor (goal-driven, multi-agent)

A repeatable loop for taking a codebase to a stated quality bar with subagents doing the reading and editing, the orchestrator keeping only conclusions, and a human gating every merge. Invoke as /refactor <goal> where the goal is the target (e.g. "8/10", "best-practice", "kill duplication and over-engineering"). If no goal is given, default to ≥8/10 across every rubric dimension and say so.

This skill is deletion-biased: the win is almost always consolidation, inlining, and removal — single robust primitives used everywhere — not new abstraction.

Operating principles (non-negotiable)

  • Avoid context rot. The orchestrator must NOT read the whole codebase. Grader and implementer subagents read files and return only structured grades / evidence / diffs / test results. Keep the conclusions, not the file dumps.
  • Grade critically. Anchored bands; a 7+ requires cited file:line evidence the code is genuinely good. Default-7 grading is a failure.
  • Grade in fresh, blind contexts. Every grade and re-grade must use newly launched grader subagents with no prior scorecard, synthesis, acceptance plan, target-pressure, or previous run conclusions in their prompt/context. The orchestrator compares old vs new grades only after the fresh grades are returned.
  • Test-first. Every behavior change or bug fix: write the test, watch it go RED, implement, watch it go GREEN. Refactors are behavior-preserving — the existing suite is the safety net and must stay green. Never claim "tests pass" you didn't see pass.
  • Frontend/theme systems are shared primitives. When CSS, templates, components, design tokens, frontend routes, screenshots, or UI assets exist, audit them as first-class code. Route/page CSS may add layout, chart geometry, and local spacing; it must not redefine the product theme, dark/light mode, semantic surface roles, component primitives, or token contract unless the acceptance criteria explicitly approve that divergence.
  • One reviewable MR per theme. Small, coherent, understandable diffs. The agent commits, pushes, and opens the MR; the agent NEVER self-merges — a human gates the merge.
  • Parallelize only file-disjoint themes. Themes that share central files (the primitives, the server entrypoint, shared helpers) must be serialized or sequenced; running them concurrently manufactures merge hell. Map file overlap before fanning out.
  • No fake data. No unrequested API params. Never fabricate values presented as real (pricing, metrics, demo rows); get the real value or ask. Don't add temperature/max_tokens or other call params that weren't there.
  • Adapt to the project, don't impose: discover and use the project's own test runner, VCS /MR mechanics, deploy lifecycle, and worktree rules (read its AGENTS.md/CLAUDE.md and any worktree/deploy skills first).

The rubric (score each 1-10, anchored)

Bands — do NOT default to 7:

  • 1-3 pervasive problems; dangerous/painful to change.
  • 4-6 works but clearly below best-practice; multiple concrete issues.
  • 7-8 solid best-practice, minor gaps (requires cited evidence).
  • 9-10 exemplary; a reference others should copy.

Dimensions:

  1. Simplicity / anti-over-engineering — factories/managers/wrappers/abstractions with <3 real callers; speculative config; helper pyramids.
  2. Error handling & fallbacks — fail-loud vs swallow-and-continue; fake recovery; UNNECESSARY fallbacks; guards already guaranteed upstream. (Deliberate, documented degradation is fine — confirm intent before dinging.)
  3. Duplication / DRY — the same operation done several ways; one concept implemented N times.
  4. Shared-primitive reuse — is there ONE robust primitive for each concern (config/secrets, HTTP, DB, LLM calls, notifications, logging, design tokens, theme variables, component CSS, frontend data loaders) and is it used everywhere, or reinvented/bypassed?
  5. Organization & layout — sensible placement, naming, one obvious home per concept, no orphans.
  6. Conciseness & LLM-readability — file/function length, nesting depth (>3 is a smell), flat happy path. Big files and long functions score low.
  7. Correctness & robustness — reachable bugs, wrong API use, bad edge cases (adversarially verified).
  8. Consistency — same idioms for config/logging/errors/naming across modules.
  9. Testing — tests prove behavior, not implementation (no mirror/snapshot/toBeDefined churn); cover the real risks; not mock-only.
  10. Documentation — authoritative docs match the code; no stale claims; single source of truth.

Sub-characteristic taxonomy:

  • code — project-rule compliance, functional regressions, logic errors, race conditions, null/undefined handling, security issues, performance traps, compatibility problems, missing critical error handling, and missing tests for changed behavior.
  • tests — behavioral coverage, negative/error-path coverage, edge cases, boundaries, async/concurrency, retry/idempotency, persistence, integration points, and brittle tests that overfit implementation details.
  • errors — swallowed exceptions, broad/empty catches, stale-data or mock fallbacks, retries that fail silently, optional/null logic that skips required work, and messages without enough operator context.
  • comments — comments/docstrings that mismatch behavior, stale file/route references, obvious-code narration, vague TODOs, or missing rationale for non-obvious business/security/platform rules.
  • types — data models, schemas, dataclasses, interfaces, classes, structs, or enums: score encapsulation, invariant expression, invariant usefulness, and invariant enforcement.
  • simplify — unnecessary abstractions, indirection, nesting, flags, state, duplicated logic, clever dense expressions, dead code, and scoped behavior-preserving deletions.

Use the taxonomy as a sub-characteristic grid inside the 10 dimensions. Tag every material finding with one or more taxonomy labels; do not replace the dimension scores with aspect scores. When a user asks for "characteristics and sub-characteristics", report both the 10-dimension scorecard and the taxonomy-tagged findings.

Mandatory UI / Theme Audit

If the repo contains CSS, design tokens, component libraries, templates, browser-rendered pages, or dashboard/frontend assets, add an explicit UI/theme systems lane in Phase 1. This lane must compare route-local CSS/templates against the shared design-system primitives and report:

  • duplicated dark/light mode definitions, route-specific theme contracts, or local semantic variables that shadow shared tokens;
  • raw color literals, transparent structural surfaces, shadows/filters/backdrop filters, or transform/compositing tricks used where shared surfaces/components should be used;
  • page-local controls, tables, cards, popovers, or navigation styles that duplicate a component primitive instead of extending it;
  • missing visual regression coverage for representative dark/light pages, especially after CSS or template changes.

Treat a page-specific dark mode or page-specific semantic surface system as a repo-wide shared primitive failure unless the product intentionally supports that page as a separate branded experience and the acceptance criteria state that explicitly.

Process

Phase 1 — Scope + rubric (orchestrator, cheap)

Map the repo without reading it deeply: tracked-file counts by extension, top-level dirs, largest files by LOC, the key config/doc/entrypoint files, the project's AGENTS.md/CLAUDE.md. Also map frontend/theme surfaces when present: tokens.css, component CSS, route/page CSS, template files, frontend bundles, screenshots, and visual tests. Define coherent lanes (one per module/area), sized to balance LOC. Always include a UI/theme systems lane when CSS/templates/frontend assets exist, even if the main refactor request sounds backend-focused. Present the rubric and lane split to the user briefly; proceed (don't over-ask).

Phase 2 — Grade (parallel graders → synthesis)

Run a Workflow: one fresh grader subagent per lane (concurrent), each returns a structured grade ONLY (no file contents). Graders must be blind to all prior grades, scorecards, synthesis outputs, target expectations, and suspected fixes; give them only the current code, lane scope, rubric, and project instructions. Then one synthesis agent reconciles cross-lane findings into themes.

Grader contract (schema-enforced): { area, approx_loc, files_reviewed, dimensions:[{name, score,rationale,evidence:[file:line]}], aspect_breakdown:[{aspect,score,rationale, evidence:[file:line]}], area_overall, top_findings:[{severity,aspect,dimension,location,issue, critique,action}], refactor_actions:[{action,effort,raises}], cross_lane_notes }. Tell graders: read deeply, trace data flow, cite evidence for findings AND for any 7+, be blunt about code never people, prefer deletion in proposed actions, this is PLAN-ONLY (no edits). For UI/theme lanes, require direct comparison between shared tokens/components and each route/page override; do not grade route CSS in isolation.

Synthesis output: an area × dimension scorecard, repo-wide dimension grades (today → target), and a themed, phased plan organized by theme (e.g. "collapse the N duplicated primitives", "decompose the oversized files", "fix the live bugs") — NOT by area. Reconcile: a duplication that shows up in many lanes is ONE repo-wide problem, not many. Calibrate down any thin 7+.

Chat grade tables (required). Whenever reporting a grade or re-grade to the user, put the scorecard directly in chat before the prose plan. The chat output must show both axes:

  1. Summary table: Overall, strongest dimensions, weakest dimensions, and target bar.
  2. Two-dimensional grade grid: rows are the 10 rubric dimensions; columns are the taxonomy sub-characteristics code, tests, errors, comments, types, and simplify. Each cell should contain a compact score or marker, e.g. 8, 6!, - when not applicable/observed. Add a row-level Dimension score and Target column so the user can see the rollup.
  3. Findings table: material issues with Severity, Dimension, Sub-characteristic, Location, Issue, and Fix.

Do not bury the grade only in a plan file or subagent artifact; the user should be able to see the grade shape from the chat response alone.

Pattern (see the Workflow tool's own docs for the API): parallel(lanes.map(grade)) → barrier → synthesize. Graders may inherit the session model/settings, but not prior grading content or conclusions. Give synthesis higher effort.

Phase 3 — Acceptance criteria (grounded)

A second Workflow (one agent per phase) turns each theme into binary, verifiable acceptance criteria, each measured against a baseline captured NOW (the agent runs the actual grep/wc/test commands): e.g. "grep -rn 'DEFAULT_MODEL' src/ returns matches only in one file", "no module > 600 LOC except ", "new regression test fails before / passes after". Each phase gets an entry gate and an exit gate (the rubric dimensions+targets it advances). Aspirational criteria ("reduce duplication") are rejected; everything must be checkable by a named command/test.

For UI/theme themes, include acceptance criteria that prove the visual contract, not only CSS string shape. Examples: route CSS does not define dark/light theme variables outside the shared token files; structural UI backgrounds resolve to approved shared token colors in Playwright; dark and light representative pages have screenshot or pixel-diff smoke tests; controls/cards/ tables/popovers reuse shared component classes or semantic tokens; visual tests fail on known artifact colors, unintended transparent slabs, or shadow/filter/compositing artifacts.

Phase 4 — Verify the headline correctness findings

Before enshrining any "live bug" claim, the orchestrator (or a refute-first verifier) checks it against HEAD: is it reachable? what is the intended behavior (from comments/tests/callers)? what concrete input triggers it? Report only Confirmed/Likely. Correct any stale memory/doc the audit contradicts.

Phase 5 — Execute (test-first, parallel, one MR per theme)

  1. Sequence by dependency + file-disjointness. Quick wins / live bugs first; the duplicated- primitive consolidations next (highest leverage); structural decomposition after; docs/tests last. Build the file-overlap map; batch only themes with disjoint file sets concurrently.
  2. Per theme: create a fresh worktree off freshly-fetched origin/main (use the project's worktree skill/conventions; never reuse a stale branch). Launch an implementation subagent with: the exact acceptance criteria; the project's test command; "TEST-FIRST (red→green); behavior- preserving for refactors; commit in small chunks; update any code-coupled doc in the SAME change; do NOT touch the living plan (orchestrator owns it); do NOT push or open an MR; report design + files + grep proofs + exact test lines + behavior-risks + git log." For UI/theme work, require a before/after visual proof from the actual served app or browser harness in addition to unit tests; do not accept headless-only checks if the bug was observed in a different browser surface unless that surface is explicitly unavailable and reported.
  3. Orchestrator verifies each returned theme independently (run the acceptance greps + the targeted/full test suite), rebases onto latest origin/main, confirms 0 behind / N ahead and a clean tree, pushes, and opens an MR (clear title + a description carrying the change, the verification, and any deliberate scope decisions/follow-ups). Then waits for the human to merge before starting dependent themes.
  4. Subagents may make judgment calls (e.g. leave a caller out of a shared primitive because it has unique security/DI needs) — honor good ones (anti-over-engineering) and surface them in the MR; reject ones that fabricate data or change behavior silently.

Phase 6 — Re-grade to confirm

After the themes land, re-run the Phase-2 lane grading with fresh, blind grader subagents (same rubric, current code only) to objectively confirm the target grade — don't trust projections and don't show graders the before scorecard. The orchestrator compares before/after only after fresh grades return. If a dimension is still short, spin its gap into one more theme.

Tracking

Keep a living plan (the project's plan-doc convention, e.g. docs/plans/<name>_living_plan.md): rubric + scorecard + per-theme acceptance criteria + phase gates + a progress log. The orchestrator owns it (implementer agents must not edit it, to avoid cross-branch conflicts); sync it at phase checkpoints and at the end. Record open author decisions and logged follow-ups there and/or in durable memory so they survive context compaction.

Notes

  • Token cost is secondary to correctness and thoroughness here; lean on subagents/workflows.
  • This skill orchestrates; it delegates the blunt code critique to /torvalds and the MR/worktree mechanics to the project's deploy/worktree skills. Use them rather than re-deriving them.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment