# End

> 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.

- **Type:** Skill
- **Install:** `agentstack add skill-bastndev-skills-end`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [bastndev](https://agentstack.voostack.com/s/bastndev)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [bastndev](https://github.com/bastndev)
- **Source:** https://github.com/bastndev/skills/tree/main/skills/end
- **Website:** https://www.skills.sh/bastndev/skills

## Install

```sh
agentstack add skill-bastndev-skills-end
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# 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; `` 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:

1. 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

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [bastndev](https://github.com/bastndev)
- **Source:** [bastndev/skills](https://github.com/bastndev/skills)
- **License:** MIT
- **Homepage:** https://www.skills.sh/bastndev/skills

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-bastndev-skills-end
- Seller: https://agentstack.voostack.com/s/bastndev
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
