Works with the AI Agents you already use

    ReFactory: Project-Wide Code Refactorer

    by yuvalB

    1

    Audit entire repositories for DRY violations, bloated logic, tight coupling, and O(N²) bottlenecks—then execute behavior-preserving, approval-gated refactorings with surgical diffs and zero wasted tokens.

    Free

    Security scanned
    ReFactory: Project-Wide Code Refactorer

    ReFactory: Project-Wide Code Refactorer

    Example session with this skill installed

    Audit src/orders/ and src/billing/ for duplicated logic, high complexity, and performance bottlenecks. Give me the Phase 1 prioritized refactoring blueprint first, and preview the surgical Before/After diff for the P1 item before modifying any files.

    • Read your context and instructions
    • Compiled the refactory

    1. Executive Summary & Architectural Diagnosis

    • Scanned Scope: package.json, src/orders/processOrder.ts, src/orders/discountMatcher.ts, src/billing/invoiceController.ts, src/orders/orderController.ts, tests/orders.test.ts
    • Architectural Health Overview: Core order and billing endpoints have solid Vitest coverage for happy paths, but business rules are tightly intertwined with HTTP transport handling and deeply nested conditionals. Validation and tax/currency guard logic are copy-pasted across two controllers, and coupon matching performs a quadratic array scan inside the checkout hot path.
    • Primary Refactoring Objectives:
      • Flatten deeply nested checkout orchestration into guard clauses and pure validation helpers.
      • Consolidate duplicated request validation and error-mapping logic shared by orders and billing.
      • Eliminate an $O(N \times M)$ nested lookup during bulk coupon resolution.

    2. Prioritized Smells Matrix

    PriorityIDLocation (File Paths & Symbols)Smell CategoryImpactEffort/RiskIssue & Proposed Solution
    P1 (Critical)REF-01src/orders/processOrder.ts (processOrder)High Complexity / Bloated LogicHighLow5-level nested conditional monolith mixing inventory checks, discount rules, and persistence; flatten with early-return guard clauses and extract pure calculateOrderTotals.
    P2 (High)REF-02src/orders/orderController.ts, src/billing/invoiceController.tsDRY ViolationHighMediumDuplicated tenant auth, payload validation, and HTTP error mapping; extract into shared src/shared/httpGuards.ts.
    P3 (Medium)REF-03src/orders/discountMatcher.ts (matchApplicableCoupons)Algorithmic / Performance BottleneckMediumLowNested .find() loop ($O(N \times M)$) across line items and active coupons; pre-index coupons by sku in a Map for $O(N + M)$ resolution.

    Approval Gate (Phase 1):
    Would you like me to proceed with applying these refactorings in priority order (including all cross-file call-site updates), or focus on specific IDs first?


    3. Before / After Code Diffs & Architectural Rationale (P1 Preview)

    REF-01 — Flatten processOrder with Guard Clauses & Pure Total Calculation

    • Affected Files: src/orders/processOrder.ts, src/orders/orderTotals.ts (new pure helper)
    • Architectural Rationale: The original 5-level nesting obscures error semantics and mixes pure price math with async repository mutations, raising cognitive load and making edge-case testing brittle. Guard clauses preserve identical error codes and early exits while isolating pricing math in a deterministic pure function.
    Before (Original Code)
    // File: src/orders/processOrder.ts
    export async function processOrder(order: OrderInput, repo: OrderRepo): Promise<OrderResult> {
      if (order && order.items.length > 0) {
        const stockOk = await repo.checkStock(order.items);
        if (stockOk) {
          if (order.customerId) {
            let subtotal = 0;
            for (const item of order.items) {
              if (item.qty > 0) subtotal += item.price * item.qty;
            }
            const total = order.coupon ? subtotal * (1 - order.coupon.rate) : subtotal;
            return await repo.save({ ...order, total });
          } else {
            throw new DomainError('MISSING_CUSTOMER');
          }
        } else {
          throw new DomainError('OUT_OF_STOCK');
        }
      } else {
        throw new DomainError('EMPTY_ORDER');
      }
    }
    
    After (Refactored Code)
    // File: src/orders/orderTotals.ts
    export function calculateOrderTotal(items: OrderItem[], coupon?: Coupon): number {
      const subtotal = items.reduce(
        (sum, item) => (item.qty > 0 ? sum + item.price * item.qty : sum),
        0
      );
      return coupon ? subtotal * (1 - coupon.rate) : subtotal;
    }
    
    // File: src/orders/processOrder.ts
    import { calculateOrderTotal } from './orderTotals';
    
    export async function processOrder(order: OrderInput, repo: OrderRepo): Promise<OrderResult> {
      if (!order || order.items.length === 0) throw new DomainError('EMPTY_ORDER');
      if (!(await repo.checkStock(order.items))) throw new DomainError('OUT_OF_STOCK');
      if (!order.customerId) throw new DomainError('MISSING_CUSTOMER');
    
      const total = calculateOrderTotal(order.items, order.coupon);
      return repo.save({ ...order, total });
    }
    
    • Cross-File Call-Site Updates:
      • src/orders/orderController.ts: No signature change; processOrder(order, repo) remains 100% backward-compatible.
      • tests/orders.test.ts: Existing integration tests require zero changes; add direct unit tests for calculateOrderTotal.

    4. Regression Verification Checklist

    • [ ]

    Behavioral Equivalence: All inputs, outputs, return types, and error/edge-case semantics (try/catch, null/undefined, async edge cases) match the original behavior 100%.

    • [ ]

    Cross-File Compilation & Imports: All imports, exports, and function signatures are updated across every dependent file in the project.

    • [ ]

    Automated Test Verification: Test command: npm test -- tests/orders.test.ts (will run before and after applying approved edits; recommend adding edge-case unit tests for zero-quantity items and missing coupons).

    Connects securely to your tools. The creator never sees your data.

    About this skill

    Asking an AI agent to "clean up my codebase" usually ends in one of two disasters: sweeping, unapproved rewrites that silently break edge cases, or bloated full-file reprints that burn through your token budget. Project-Wide Code Refactorer turns your coding agent into a disciplined Principal Refactoring Architect that audits multi-file repositories, delivers a prioritized blueprint first, and executes surgical, behavior-preserving refactorings only after you approve the plan.

    What it does

    • Four-dimension codebase audit: Systematically detects DRY Violations, High Complexity / Bloated Logic (God functions, >3-level nesting), Tight Coupling / SOLID leaks, and Algorithmic / Performance Bottlenecks (such as $O(N^2)$ lookups).
    • Two-phase approval gate (Plan Before Mutate): Outputs a deterministic, prioritized Refactoring Blueprint ranked by Impact vs. Effort/Risk (P1–P3) and pauses for your confirmation before editing multiple files in place.
    • Strict behavioral equivalence: Preserves 100% of external behavior, public API signatures, error semantics, null/undefined handling, and async edge cases while mapping every cross-file call-site update.
    • Quality-first token efficiency: Avoids reading unrelated files and emits minimal surgical Before/After hunks instead of full-file reprints—cutting token waste without ever dropping edge cases or verification steps.
    • Built-in regression verification: Detects project test runners (package.json, pyproject.toml, Cargo.toml) and runs existing test suites before and after structural changes, concluding with a Regression Verification Checklist.
    • International, language-adaptive output: Explains architectural trade-offs and reports in whatever language you write in (defaulting to English) while keeping code blocks, file paths, and symbols strictly in English.

    How it works

    1. Scope & Test Discovery: Inspects project manifests, directory structure, entry points, and test runners. If a large monorepo scope is ambiguous, it asks which module to prioritize before scanning.
    2. Targeted Dependency Mapping: Maps shared utilities, data flow, and high-complexity slices without reading unrelated files.
    3. Prioritized Refactoring Blueprint (Phase 1): Delivers a structured audit using the included references/refactoring-report-template.md, ranking every finding (REF-01, REF-02, ...) by impact and risk, then waits at the Approval Gate.
    4. Incremental Execution & Surgical Diffs (Phase 2): Applies approved changes in atomic steps with concrete Before/After hunks, complete cross-file call-site updates, and concise architectural rationales.
    5. Silent Verification & Test Run: Validates behavioral equivalence, cross-file integrity, and zero premature abstractions via a pre-output rubric, then verifies against your test suite.

    Frameworks & tools

    • Compatible AI Agents & IDEs: Claude Code, Cursor, Windsurf, Cline, Antigravity, GitHub Copilot Workspace, and any agent supporting SKILL.md / system prompt workflows.
    • Languages & Stacks: Language-agnostic—works across TypeScript/JavaScript, Python, Rust, Go, Java, C/C++, and multi-module repositories.
    • Agent Tool Types: File read/write tools for workspace scanning and surgical edits, plus optional shell/terminal execution for running project test suites.

    Why this beats prompting it yourself

    A generic prompt like "refactor this repo to be cleaner" gives the model no guardrails against cosmetic churn, premature abstractions, broken cross-file imports, or uncontrolled multi-file rewrites. This skill embeds a complete architectural constitution (SYSTEM_PROMPT.md), an operational workflow (SKILL.md), a deterministic reporting template (references/refactoring-report-template.md), and a structured blueprint.xml specification—enforcing a plan-before-mutate workflow, measurable smell criteria, surgical diffs, and a five-point silent verification rubric on every run.

    Use cases

    • Auditing legacy multi-file services before a major feature sprint or team handoff.
    • Eliminating duplicated validation, auth, and data-fetching logic across API routes and controllers.
    • Flattening deeply nested business logic (>3 levels) into readable, testable pure functions.
    • Decoupling domain logic from database, UI, or transport layers without altering public contracts.
    • Replacing hidden $O(N^2)$ loops and redundant allocations with linear-time data structures.

    This is a pure prompt-and-template architectural skill with no bundled AST parser or compiler plugin, so cross-file call-site tracking and behavioral equivalence depend on your host model's reasoning quality and context window—very large monorepos should be scoped module-by-module to prevent context drift. Automated regression checks rely on the repository already having an executable test suite; on untested legacy code, the agent provides a manual verification checklist and recommended tests rather than programmatic proof of zero regressions. The skill is intentionally scoped to behavior-preserving refactoring and is not designed for greenfield feature development, changing business requirements, or purely cosmetic formatting passes.

    How to use

    1. 1

      Connect your agent to the Agensi MCP

      Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup

    2. 2

      Sign in to Agensi

      Your agent shows a sign-in link. Sign in and click Allow.

    3. 3

      Ask for what you need

      Your agent loads this skill and uses it on your task. It always asks before buying a skill.

    Reviews

    No reviews yet

    Be one of the first to try it. Every listed skill goes through the trust checks below.

    Security scanned

    Checked by our 8-point scan before listing

    Fresh listing

    Recently published to Agensi

    Free to use

    No account required to browse

    Trust & safety

    Security scan

    Security scan passed 16 days ago

    • Free with an Agensi account

    Nothing to install. It runs in your AI agent.

    Pure Markdown & XML skill—nothing to install. Works across any language or repository (JS/TS, Python, Rust, Go, etc.) inside agentic IDEs and CLI tools. Always presents an approval-gated blueprint before editing multiple files. Existing project test runner (e.g., Jest, Vitest, Pytest, Cargo test)……

    Permissions

    Read Files
    Write Files
    Terminal / Shell

    Read Files is used for targeted scans of project manifests, entry points, and dependency slices; Write Files is used only after your Phase 1 approval to apply surgical refactorings and update cross-file call sites. Terminal / Shell is used strictly to run your existing local test suite before and after changes to verify zero regressions.

    Listed16 days ago

    What's inside

    Creator

    yuvalB

    yuvalB

    2 skills on Agensi

    Frequently Asked Questions

    No. It is a pure Markdown and XML skill package with zero external dependencies. Drop it into your agent's skills directory or load the instructions into your IDE/CLI agent and start auditing repositories immediately.

    It works in any agent or IDE that supports skills or custom system instructions—including Claude Code, Cursor, Windsurf, Cline, and Antigravity. It is programming-language agnostic (TypeScript/JavaScript, Python, Rust, Go, Java, C/C++, etc.) and responds in whatever spoken language you write in (defaulting to English) while keeping code, file paths, and symbols strictly in English.

    Generic prompts often trigger unapproved multi-file rewrites, premature abstractions, or bloated full-file outputs that waste tokens and introduce silent regressions. This skill enforces a strict Two-Phase Approval Gate (Plan Before Mutate), audits across four concrete smell dimensions, outputs a deterministic Prioritized Smells Matrix, emits surgical Before/After diffs, and runs a five-point Silent Verification Rubric before every response.

    Behavioral equivalence is a hard guardrail: the agent never changes public interfaces without mapping every internal consumer and flagging breaking changes, preserves exact null/error/async edge cases, executes approved edits in atomic steps, and runs your existing test suite before and after structural transformations whenever tests are present.

    Task correctness always comes first—the agent will never skip edge cases, call-site updates, or verification steps to save tokens. Instead, it cuts waste by inspecting only relevant manifests and dependency slices, outputting minimal surgical Before/After hunks rather than reprinting untouched files, and keeping explanations crisp and filler-free.

    New in Code Quality & Review

    Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for Code Quality & Review.

    Free