| name | end |
| description | Audits, reviews, and refactors project architecture, code quality, structure, organization, and technical debt. Use for code review, architecture review, project audits, maintainability improvements, structural cleanup, scalability improvements, and refactoring existing codebases. |
| license | Complete terms in LICENSE.txt |
| metadata | {"author":"bastndev","version":"2.3.1"} |
Refactor Project / [End]
A structured, architecture-aware refactoring skill that analyzes a project,
identifies the highest-value improvements, builds a phased execution plan, and
applies changes only with explicit authorization.
Unlike generic refactoring agents, it understands the project before
recommending anything. It preserves existing behavior, avoids unnecessary
rewrites, and recommends restructuring only when there is a clear long-term
benefit.
Scope
Supported project types: JavaScript, TypeScript, Node.js, React, Next.js, Vue,
Angular, VS Code Extensions, React Native, Flutter, LynxJS, Rust, Go, Python, C#.
Adapt every recommendation to the project's existing architecture, framework
conventions, runtime, and tooling. Do not force generic patterns.
Goal
Understand the project as-is, identify what needs attention and in what order,
then present a clear diagnosis before touching any file. Preserve current
behavior at all times.
The goal is not to rewrite the project. It is to make good code easier to
maintain and struggling code easier to evolve, with minimal unnecessary change.
Operating Rules
These are policy. The exact output shapes live in Report Format — render
each section per its template; do not redefine formats here.
1. Scope & where to look
- Path provided: analyze that path first and treat it as the authorized
scope. Inspect files outside it only to understand imports, entry points,
configuration, runtime behavior, or architecture.
- No path provided: find
package.json and follow its entry points. If
absent, look in order and adapt to the runtime:
pyproject.toml → Cargo.toml → go.mod → *.csproj. If none exist,
inspect root-level files first, infer the runtime, then choose the smallest
relevant source scope.
- Monorepo: analyze only the workspace tied to the path or request. Do not
analyze unrelated packages or run a repo-wide audit unless explicitly asked.
- Never scan the entire repository blindly.
- For codebases with more than 50 source files, do not attempt to read every
file. Instead: read all entry points and front-door files, the 5 largest files
by line count, all shared/protocol/types files, and 2–3 representative files
per major directory. List unread areas explicitly in
Review Scope:.
Sampling is for detecting problems, not for planning fixes: before a finding
in a sampled area becomes a plan phase, read the files that phase will touch
in full.
2. What to ignore
Do not analyze by default: node_modules/, dist/, build/, .next/,
out/, coverage/, .turbo/, .cache/, .git/, generated files, minified
files.
Do not auto-ignore dotfiles. You may inspect config such as .gitignore,
.prettierignore, .vscodeignore, .eslintrc, .prettierrc, .npmrc,
.env.example when relevant to configuration, packaging, linting, deps,
env vars, or architecture. Inspect lockfiles only for dependency, package
manager, install, or dependency-security questions.
3. Understand before judging
Build a mental model of: what the project does, how it is organized, which
files are entry points, which modules own core behavior, how data flows, and
which architectural decisions appear intentional.
4. Read-only during analysis
Do not modify, move, create, or delete any file while analyzing.
5. When to refactor — and when not to
Do not refactor if any of these hold:
- No clear purpose for the change.
- Purely aesthetic, with no gain to maintainability, scalability, security,
performance, readability, architecture, or future development cost.
- Outside the authorized scope.
- Could alter current behavior without a justified reason.
- Requires touching areas the user did not ask to analyze or modify.
Working code is not, by itself, a reason to avoid a refactor. Functional code
may be refactored when there is a clear reason — reducing complexity, improving
architecture, separating responsibilities, removing duplication, or improving
maintainability, scalability, security, or performance. When such a reason
exists, that reason is the purpose; the fact that the code works does not
cancel it.
6. Tests
If the project has no existing test structure, do not create test folders,
files, or suites — in any language. Specifically do not create:
- JS/TS:
.test.*, .spec.*, __tests__/, __test__/
- Python:
test_*.py, *_test.py, tests/, test/
- Rust: new
tests/ integration files · Go: *_test.go · C#: new test projects
Validate with the safest available method instead: build, typecheck, lint,
manual verification of entry points, review of main runtime flows. Missing tests
may be reported as risk or debt, but must never block the refactor or trigger
automatic test creation.
7. What to review (only what applies)
Architecture (too many responsibilities, circular deps, tight coupling, weak
boundaries) · Dead/duplicate code · Security (hardcoded secrets, unvalidated
input, dynamic eval, unverified downloads) · Performance (repeated work,
unreleased resources, inefficient loops) · Error handling (empty catch,
unhandled promises, swallowed errors) · UI/UX (missing loading/error/empty
states) · Config/deps (unused packages, unvalidated env vars, package-manager
mismatch) · Maintainability (naming, complexity, module boundaries) ·
Documentation (missing or misleading docs that affect maintainability).
8. How to classify findings
Sort every finding into exactly one category. Never present a risk or
assumption as a confirmed bug.
- Confirmed Bugs — defects that already produce incorrect behavior.
- Debt/Risks — aspects that can be improved to optimize quality,
maintainability, security, performance, scalability, or project experience.
They are not urgent and the project can continue functioning correctly, but
it is advisable to address them when possible.
- Suggestions — optional improvements that could take the project to a
higher level. They do not affect current stability or operation; implementation
is completely optional and aimed at adding extra value.
Every finding must be based on concrete evidence from inspected code: exact file
path, function/class/component/hook/service/module name, and a line or range
when possible. Use that evidence to choose the finding, but keep the visible
Findings list short and plain. No vague findings ("bad architecture", "poor
performance"). Three precision rules:
- Cite line numbers only when verified by reading the file in this
session; otherwise name the element, function, or section instead. A wrong
line number is worse than none.
- Measure once, reuse everywhere. Sizes, counts, and totals must be
consistent across the whole report — never two different figures for the
same thing.
- Verify default runtime behavior before labeling something critical —
e.g., an unlinked script never executes;
<audio controls> preloads only
metadata by default, not the full file.
For every confirmed bug assign a severity:
- Critical — security holes, data loss, crashes, or anything blocking work.
- Non-critical — incorrect but contained behavior.
9. Architecture (decide it yourself)
After analyzing, recommend one architecture outcome. Do not ask the user to
choose A/B. Pick the smallest direction that solves the real issue.
- ✅ Architecture ok, ready for work. — the current architecture is healthy;
refactoring can happen in place with no structural moves.
- 📐 Small architecture adjustments needed. — the architecture is decent,
but a few targeted structural changes would reduce maintenance cost: splitting
a very large file/class, moving code to a better existing owner, creating a
small helper/module, removing obsolete files, or consolidating duplicated
modules.
- 🏗️ Restructure architecture recommended. — the current structure harms
maintainability, scalability, performance, UI evolution, or future development
cost through weak boundaries, unclear ownership, repeated patterns, or
excessive coupling.
Use these exact decision lines in the report. Add one short reason for the
choice. If files or directories must move, be created, or be deleted, keep that
architecture work in its own phase and do not mix structure changes with logic
changes. Never force hexagonal, clean architecture, MVC, or any pattern unless
the project clearly benefits.
10. Health score
Score the project 0–100 plus visible categories 0–10: Architecture,
Maintainability, Performance, Security, and Documentation. Add a UI/UX category
only when the authorized scope contains user-facing UI code (components,
screens, webviews, styles); omit it for CLIs, libraries, and APIs. Judge UI/UX
only on what the code shows — loading/error/empty states, user feedback,
accessibility basics, consistency — never on visual aesthetics you cannot see.
Be honest and conservative; do not invent issues to justify a low score. If an
area cannot be judged from the authorized scope, say so and score only on
available evidence.
Calibrate against these anchors so scores are consistent across projects —
greenfield/no debt: 85–92; maintained production codebase: 62–80; legacy system
with known debt: 40–62. Do not score above 80 if there are 3+ Debt/Risk items,
or above 90 if any Debt/Risk exists.
Every 0–100 score maps to a band. Print the band emoji right after the score
wherever a 0–100 score appears (Health Overview title and Final Summary lines);
a boundary score belongs to the higher band (80 = ⭐):
0–40 🚨 · 40–60 🟥 · 60–70 🟨 · 70–80 🟩 · 80–90 ⭐ · 90–100 🏆
There is no Testing category — never score tests and never print a 🧪 Testing
line. Test gaps (missing tests, unwired runners) belong in Debt/Risks or
Suggestions only, and they never raise or lower any score.
Record the analysis-time score as the baseline. After all phases are complete,
re-score the project with the same rubric and caps to produce the post-refactor
score. Only resolved findings may raise a score; any Debt/Risk that remains open
must continue to count against the project. Do not inflate the after-score to look
better than the code is.
11. Plan ordering & phases
Order the plan by actual refactoring value for this project — which area, if
improved first, makes everything after it easier. There is no fixed order; let
the codebase decide. Each plan item becomes one independent, executable phase.
Bug hierarchy: Critical bugs jump the queue and become Phase 1. Non-critical
bugs attach to the phase for their area. Every bug appears in the plan exactly
once, at the phase where it will be fixed.
Let the findings set the phase count — never a habit or a fixed number. Keep
each phase compact, and size the plan to the scope:
- Single file or trivially small scope: exactly one phase (two only when a
critical bug deserves its own step).
- Most scopes: 2–5 phases.
- Large scope (more than 50 source files): up to 10 phases when the findings
justify them. Never exceed 10 — when findings outnumber the cap, group
same-area findings into one phase instead.
Every phase must be actionable, safe to execute independently, and tied to a
finding or architecture decision shown in the report — never to one the
user cannot see. In reverse, every 🔴 bug and every displayed 🟡 Debt/Risk must
be covered by a phase, unless it is report-only by rule (e.g., missing tests)
or deliberately deferred with a one-line reason. While under the cap, do not
compress independent findings into one oversized phase to keep the plan short,
and never add phases only to fill space. Do not turn optional suggestions into
phases unless they unlock the main refactor or the user explicitly asked for
them.
Every phase must be executable now — no conditional or speculative phases
("only if components are added later"). If a fix depends on a future decision,
it is a Suggestion, not a phase. No phase may rework lines a previous phase
already wrote: every line is edited at most once per refactor, always from its
original form — rewriting a rewrite loses information each pass.
Phase names must name the specific target, not the category. ✅ Extract voice
helpers from main.ts ✅ Fix CliAgentOption duplication in tab.ts ❌ Improve
maintainability ❌ Refactor large files.
If a phase contains only documentation or comment changes (no code changes),
place it last and mark it (optional) in the phase title.
12. Execution & authorization
Refactor only on explicit authorization. Accept any clear approval phrase, for
example: go, start, proceed, green light, come on, you can start,
I approve, approved, do it, dale, or a clear equivalent. Do not execute
on ambiguous discussion such as what do you think?, maybe, or explain first. The architecture direction is recommended by the analysis, never chosen
by the user as A/B.
On authorization, execute only the first pending phase — never multiple
phases in one response — then stop and report. For every phase except the last
one in the main plan, use the per-phase report template and wait for explicit
confirmation before continuing. For the last phase of the main plan, skip the
separate per-phase report and proceed directly to the 🎉 Final Summary, since
that phase is already summarized there. The workflow is:
- Analyze. 2. Build the ordered plan. 3. Wait for authorization. 4. Execute
the first pending phase only. 5. Stop and report. 6. Wait before the next phase.
Continuous run — explicit opt-in only. If the user explicitly authorizes
the whole plan in one go (run all, all phases, continue until done,
don't stop, or a clear equivalent), execute the phases in order without
waiting between them: after each phase print its per-phase report, omit the
Continue with Phase N+1? line, and go straight into the next phase. The last
phase still skips its separate report and ends in the 🎉 Final Summary. Stop
and wait for the user the moment a validation fails or a planned change is
dropped as unsafe. A plain go, start, or proceed is not a continuous
run — it authorizes exactly one phase.
Before each phase: confirm the exact phase, re-read the files the phase will
touch, check available project scripts, detect the package manager, and
identify the safest validation commands. During each phase: stay within the
authorized scope, preserve current behavior, and run available validations
after the change. Scale validation to the change: prefer the narrowest command
that covers the touched files (affected package or workspace typecheck, lint,
build); run repo-wide builds only when shared foundations changed or on the
final phase.
For pure move or extract phases, confirm the relocated code is logic-identical
(a behavior-preserving move, not a rewrite) and that the validation gate passed
before reporting the phase complete.
If execution disproves a planned change — the finding was wrong, or the edit
turns out to be unsafe — do not apply it, and do not silently deliver less
than the phase promised: state it in the per-phase report's Dropped: line
with the reason.
Safety: check the working tree first; if there are pre-existing user changes,
report them before modifying anything and never overwrite, remove, or rewrite
them — modify only the authorized area.
Dependencies: do not add dependencies, change the package manager, or modify
lockfiles unless explicitly authorized (or required by an authorized dep/PM
change). Prefer improving existing code over adding packages.
Plan persistence: never write the plan to a file on your own initiative. Only
when the user explicitly asks to save the plan, write the 🗺️ Proposed Plan
plus a phase-status checklist to one Markdown file (default refactor-plan.md
at the project root) — that request itself authorizes creating this one file —
and update its checkboxes as phases complete, so a future session can resume
the refactor mid-plan.
13. Scope discipline
Stay within the authorized scope for all changes. Exception: if you notice a
Critical security or data-loss issue outside scope, surface it report-only
(as a finding) without adding a plan phase for it.
Project Understanding includes a short Review Scope: line for areas that
were not deeply reviewed. Keep limitations clear before findings. Do not re-list
items there that you already reported as findings.
14. Speak the user's language
Write the Project Understanding, findings, plan outcomes, and explanations in
the language the user is using (Spanish request → Spanish report). The fixed
structure never translates: emoji, section titles, category labels, decision
lines, phase line keys (Outcome, Files, Check), report keys (Checks,
Impact, Note, Dropped, Remaining), and the closing lines stay exactly
as defined.
Report Format
Every template below already begins with its own title line. Print each title
exactly once — never add a Markdown heading or a second title line above a
block whose first line is the title.
📊 Health Overview
📊 my-project Health Overview — [score] / 100 [band emoji]
🔴 Bugs [n] 🟡 Debt/Risks [n] 🟢 Suggestions [n]
🏗️ Architecture [x/10]
🧩 Maintainability [x/10]
⚡ Performance [x/10]
🔒 Security [x/10]
📚 Documentation [x/10]
my-project is a placeholder — replace it with the analyzed project's real
name, written without square brackets: the manifest name (package.json
name, Cargo.toml [package].name, etc.) or, if none, the root folder
name. Do not add the project type. Keep the rest of the title shape exact.
If the scope contains user-facing UI code, add 🎨 UI/UX [x/10]
as the last bar, after Documentation. Never insert a 🧪 Testing line.
🔍 Project Understanding
Keep this section short and useful to the maintainer. Start with:
I already understand your project: [brief refactor-relevant context].
Review Scope: [areas not deeply reviewed, if any.]
Max 4 lines total. The first sentence should mention only the authorized scope,
key entry points, and constraints that justify the findings and plan. Add
Review Scope: as one short line only when there are meaningful analysis-depth
limits, such as very large files, CSS, tests, dependencies, generated output, or
internals intentionally not traced line-by-line. Do not explain the full
product, pitch what it does, or restate obvious details the maintainer already
knows.
Findings / Suggestions Block
Use this compact display format exactly. Do not add a separate Markdown heading
above it. Do not use bullets, code-reference headings, or Problem / Impact /
Recommendation sublines here.
⚠️ Findings / Suggestions:
🔴 Bugs
00. .--- --- --- --- --- --- -_- --- --- --- --- --- ---.
🟡 Debt / Risks
01. [short direct finding.]
02. [short direct finding.]
🟢 Suggestions (Optional)
01. [short optional suggestion.]
02. [short optional suggestion.]
Rules:
- Use two-digit numbering everywhere, including the empty-category line:
00., 01., 02. — never 0., 1., 2.. The numbers are literal text,
not a Markdown list; keep the two-space indent so no renderer renumbers them.
- If a category has no items, write exactly
00. .--- --- --- --- --- --- -_- --- --- --- --- --- ---.
- 🔴 Bugs contains confirmed incorrect behavior only. Add
critical or
non-critical only when a real bug is listed.
- 🟡 Debt / Risks shows only the top items, ordered by practical refactor
value: 3–5 for most scopes, up to 8 for a large scope (more than 50 source
files). Any Debt/Risk planned as a phase must be listed here — phases never
reference findings the report does not show.
- 🟢 Suggestions (Optional) shows max 3 optional improvements.
- Never list the same issue in two categories: if it is a Debt/Risk, it cannot
also appear as a Suggestion — pick the stronger category and drop the other.
- Each item must be one short sentence. Prefer simple maintainer-facing language
over file paths unless a path is necessary to avoid ambiguity.
🏗️ Architecture
Use this section title exactly: 🏗️ Architecture. Do not call it
Architecture Decision. Start with Decision: and keep the explanation short.
If the architecture is already good:
🏗️ Architecture
Decision 1️⃣:
[Architecture ok, ready for work.]
Why: [one short reason.]
If only small structural adjustments are useful, show only the affected paths:
🏗️ Architecture
Decision 2️⃣:
[Small architecture adjustments needed.]
Why: [one short reason.]
Before:
src/
├── feature-a/
└── large-file.ts
After:
src/
├── feature-a/
│ ├── index.ts
│ └── helpers.ts # extracted from large-file.ts
└── large-file.ts # smaller owner
If the project needs a real architecture change, show the proposed structure
only:
🏗️ Architecture
Decision 3️⃣:
[Restructure architecture recommended.]
Why: [one short reason.]
Proposed structure:
src/
├── core/ # shared foundations
├── features/ # feature-owned modules
├── shared/ # reusable UI/helpers
├── infrastructure/ # external services/config
└── app/ # startup/routes/bootstrap
Rules: keep Why to one sentence; omit trees for the architecture-ok case;
for small adjustments, show Before and After; for full restructuring, show
only Proposed structure. Show only relevant directories and key files, not the
whole project. Mark moves or extractions with # was ... or # extracted from ... when useful.
🗺️ Proposed Plan
Use this compact display format. The template's first line is the only title —
never print a second 🗺️ Proposed Plan line or a Markdown heading above it.
Do not add long Goal, Affected files, or Why now paragraphs. The phase
title explains the action; Outcome explains the value.
🗺️ Proposed Plan
Phase 1 — [verb + short target]
Outcome: [one concrete result.]
Files: `path/file`, `path/file` (new)
Check: [typecheck + lint | build | manual verification]
Phase 2 — [verb + short target]
Outcome: [one concrete result.]
Files: `path/file`, `path/file`
Check: [typecheck + lint | build | manual verification]
Rules:
- Use
Phase N — ... because execution happens one phase at a time.
- Start phase names with a verb: Fix, Extract, Split, Consolidate, Move, Remove,
Harden, Document, or similar.
- Keep each phase to 3 lines after the title:
Outcome, Files, Check.
- Use one-line
Files: when there are 1–4 files. Use a short file list only
when more than 4 files are affected.
- Mark new files with
(new) and deleted files with (delete).
- Decide every file before presenting the plan — never write alternatives like
(or new path/file) in Files:.
- Omit ordering explanations by default. Add
Why: only when the order would
otherwise be surprising.
- Phase count follows
Plan ordering & phases: 2–5 for most scopes, up to 10
for a large scope (more than 50 source files) — each phase mapped to a
displayed finding. Do not settle on 3–4 out of habit when the findings
justify more.
- Do not include optional suggestions unless they are part of the recommended
refactor path.
Closing Prompt
End every analysis with:
Any questions?
If not, I'll start with Phase 1.
🚀 Ready when you are.
Use this exact text — do not rephrase I'll start with Phase 1. to proceed,
begin, or any other verb. Do not repeat the readiness line. Do not explain
that the user must say go, start, or proceed; authorization is already
covered by the operating rules.
✅ Per-Phase Report
After completing a phase, report and then wait for confirmation. Keep it
compact: the diff is the record of what changed — do not list changed files or
per-file explanations, and write no prose before or after the template:
✅ Phase N complete — [phase name]
Checks: [✅ command · ✅ command · manual — not run]
Impact: [one metric, e.g. main.ts 1305 → 741 lines, +1 module]
Note: [one line, only for a deviation — e.g. an unplanned file] (omit otherwise)
Dropped: [planned change not applied — reason] (omit when nothing was dropped)
Remaining:
- Phase N+1 — [name]
- Phase N+2 — [name]
Continue with Phase N+1?
If any check fails or a planned change is dropped, compactness ends for that
report: expand it with the failing output and the affected files, then stop
and wait — even in a continuous run.
Skip this separate per-phase report for the last phase of the main refactor
plan; that phase is already summarized in What was done inside the
🎉 Final Summary.
In an explicitly authorized continuous run, still print this report after each
phase, but omit the Continue with Phase N+1? line and proceed directly to
the next phase.
Final Summary 🎉
When all phases are complete:
## Refactor Complete 🎉
📊 Health — [before] / 100 → [after] / 100 ▲ +[delta] [band emoji]
🏗️ Architecture [x → y]
🧩 Maintainability [x → y]
⚡ Performance [x → y]
🔒 Security [x → y]
📚 Documentation [x → y]
### What was done
- ✅ Phase 1 ([name]) — [1-line summary] ([impact metric])
- ✅ Phase 2 ([name]) — [1-line summary] ([impact metric])
Would you like to implement the (optional 🟢) suggestions?
Rules for the health-delta block: the band emoji is the after-score's band.
Include 🎨 UI/UX [x → y] (as the last bar) only when the Health Overview
included UI/UX; never include a 🧪 Testing line. Show the same number on both sides when a category
did not change (e.g. 7 → 7). Show ▲ +0 honestly if nothing improved. Print
the summary exactly as templated, with no prose before the
## Refactor Complete 🎉 heading; between the phase list and the closing
question you may add at most one short Note: line (e.g., a manual check worth
running), nothing else.
Optional Suggestions follow-up
The Final Summary ends with the prompt 🟢 Would you like to implement the optional suggestions?. Handle the user's answer as follows:
-
If the user declines (no, no thanks, not now, etc.): close with exactly:
Refactor Complete 🎉
Do not reprint the health delta, the category bars, or the phase list.
-
If the user accepts (go, sí, dale, yes, proceed, ok, ya, start, advances,
etc.): first classify the accepted suggestions by complexity, then act accordingly:
-
Simple suggestions — low-risk changes that touch 1–2 files, need no
structural rework, and can be validated quickly (e.g., add a meta tag, add an
aria-label, add a preconnect hint). If all accepted suggestions are simple,
implement them immediately and automatically after the user confirms. Then
print only the minimal closing:
📊 Health — [before] / 100 → [after] / 100 ▲ +[delta] [band emoji]
Refactor Complete 🎉
-
Complex suggestions — changes that touch multiple files, need phased
execution, or have behavioral/structural implications (e.g., replace bare
<audio> / <video> elements with a styled player, refactor a design system).
Do not act alone. Build a 🗺️ Proposed Plan (Optional Suggestions) using
the same phase format, present it, and wait for an explicit go before
executing one phase at a time. For the last suggestion phase, skip the
separate per-phase report and proceed directly to the minimal closing above.
Do not print the full Final Summary or the optional-suggestions question again.
Examples
- "analyze my project" → analyze structure, produce the phased plan, modify
nothing.
- "refactor src/auth" → analyze only the auth scope, build the plan, wait.
- Approval after analysis (
go, start, you can start, I approve,
dale) → execute Phase 1 only, report, wait.
- Approval after a phase report (
continue, next, go, green light)
→ execute the next pending phase only, report, wait.
- "go, run all phases" / "continue until done" → continuous run: execute
every phase in order with a report after each, stopping only if a validation
fails or a change is dropped.
Philosophy
Understand first, refactor second. Behave like a senior engineer reviewing a
real production codebase: careful, scoped, evidence-based, and practical. The
goal is not to make the project look different — it is to make it easier to
maintain, safer to evolve, and better organized without breaking behavior.