dry-refactoring
kucherenko/jscpd
Guided workflow to eliminate copy-paste duplication detected by jscpd using targeted refactoring strategies.
What is dry-refactoring?
A structured workflow for refactoring code duplication after running jscpd clone detection. It guides you through triaging exact, renamed, and near-miss clones, then applying extract-function, parameterize, module, constant, or base-class strategies to eliminate them, starting from high-impact hotspots.
- Identifies and ranks duplicated code segments by impact using jscpd detection output
- Guides triage of exact, renamed (Type-2), and near-miss (Type-3) clones with clear skip criteria
- Provides refactoring strategies: extract function, extract module, parameterize, template/base class, and unify near-miss copies
- Handles cross-format clones (JavaScript/TypeScript) and mixed-language codebases
- Confirms refactoring success by re-running jscpd with matching flags to verify clone elimination
How to install dry-refactoring
npx skills add https://github.com/kucherenko/jscpd --skill dry-refactoring- jscpd installed and run with `--reporters ai` flag to generate clone detection output
- Source code access to read both sides of each reported clone
- Understanding of the codebase structure and module boundaries
How to use dry-refactoring
- 1.Run jscpd with `--reporters ai` (add `--summary` on larger codebases to identify high-impact files)
- 2.Parse each clone line to extract file paths, line ranges, and clone kind (exact, renamed, gap, ast)
- 3.Read both code fragments and understand what they do; for renamed/similar clones, list exact differences
- 4.Triage each pair: skip if semantics differ despite shape, code is generated, or abstraction would be vague
- 5.Design a refactoring strategy (extract function, parameterize, extract module, base class, or unify)
- 6.Apply the refactoring to both locations and all other call sites; ensure tests pass
- 7.Re-run jscpd with identical flags to confirm the clone is eliminated and dup% decreased
- 8.Report refactored and skipped clones separately with reasons to track real vs. intentional duplication
Use cases
- Reduce technical debt in large codebases with high duplication percentages identified by jscpd summary reports
- Consolidate copy-pasted logic across unrelated modules into shared utilities or base classes
- Refactor test files with repeated setup patterns into reusable test helpers
- Unify renamed clones where the same algorithm is duplicated with different variable names or configuration values
- Merge near-miss function pairs that differ only in a few guard conditions or logging calls
- Backend and frontend developers refactoring legacy or rapidly-grown codebases
- Teams conducting code-quality initiatives to reduce duplication metrics
- Developers maintaining large monorepos with cross-module duplication
- QA and test engineers consolidating repeated test fixtures and setup logic
dry-refactoring FAQ
Only after exact clones are refactored. Type-2 and Type-3 are noisier and surface blocks that merely look alike (models, DTOs, test setup, generated code). Run them one family at a time with tight settings (`--min-tokens 70` for Type-2, `--max-gap-lines 1 --similarity 0.85` for Type-3) and treat results as leads to review, not defects to fix.
Skip if: the two sides do different things despite the same shape; sameness is intentional boilerplate (models, DTOs, config, test fixtures); code is generated; a shared abstraction would need a vague name like `processData`; or the pair is under ~10 lines. Only refactor pairs where you can delete code and give the extraction a precise, descriptive name.
The `dup%` column shows what percentage of each file is duplicated. Prioritize files with high `dup%` and high token counts first—they pay back the most effort. Start with exact clones in high-impact files, then move to renamed and similar clones.
Use `--cross-formats "js-ts"` to detect them. Rather than extracting a third shared copy, consolidate into one implementation (usually TypeScript) and update imports. This avoids maintaining parallel versions.
Re-run with the same flags you used to find the clone to confirm it is eliminated and the `dup%` of touched files decreased. For renamed clones, re-run with `--ignore-identifiers` to verify they no longer appear, since the default run ignores identifier differences.
Full instructions (SKILL.md)
Source of truth, from kucherenko/jscpd.
name: dry-refactoring description: Guided workflow to eliminate copy-paste duplication detected by jscpd. Refactor exact, renamed and near-miss clones using extract function, parameterize, module, constant, or base class strategies, starting from the hotspots the summary ranks.
dry-refactoring
Guided workflow to eliminate copy-paste duplication in source code. Use after running jscpd to detect clones.
Prerequisites
First, run jscpd to identify duplications:
npx jscpd --reporters ai <path>
In codebases that mix related formats (e.g. JavaScript and TypeScript), add --cross-formats so clones spanning both are detected too:
npx jscpd --reporters ai --cross-formats "js-ts" <path>
On larger codebases, add --summary to get a refactoring-hotspot overview alongside the clone list — top files and folders with a dup% column showing how much of each file is duplicated:
npx jscpd --reporters ai --summary <path>
The default scan reports only exact copies, and those are the ones to refactor first: an exact clone is almost always a real copy-paste. Two more passes find copies that were edited after pasting. They are noisier: they ignore names, values or a few statements on purpose, so they also surface blocks that merely look alike (models and DTOs, config tables, test setup, generated code, shared idioms). Run them only after the exact clones are dealt with, one family at a time, with tight settings, and treat what they report as leads to read rather than defects to fix:
# Type-2: renamed copies (other variable names, other constants), reported as "(renamed)".
# Raise --min-tokens: with identifiers ignored, a short block is mostly placeholders.
npx jscpd --reporters ai --ignore-identifiers --min-tokens 70 <path>
# Type-3: near-miss copies (one or two edited lines, or JS/TS functions with the same structure),
# reported as "[~0.91 gap]" and "[~0.85 ast]". Widen only if the tight run finds nothing.
npx jscpd --reporters ai --max-gap-lines 1 --similarity 0.85 <path>
See the jscpd skill for full option reference, including cross-format group syntax, the clone-kind suffixes and how to read the summary.
Workflow
- Run jscpd with
--reporters aion the target path (add--summaryon larger codebases to pick a starting point: files with highdup%and high token counts pay off most) - Parse each clone line to identify the two duplicated locations (file + line range) and its kind: no suffix is an exact copy,
(renamed)differs only in names or values,[~N gap]has a few edited lines in the middle,[~N ast]is a function pair with the same structure - Read both code fragments from the source files
- Understand what the duplicated code does, and for renamed and similar clones list exactly what differs between the two sides
- Triage renamed and similar clones before touching them. Skip the pair, and say so, when any of these holds: the two sides do different things despite the same shape (a
switchover different enums, two reducers with unrelated semantics); the sameness is intentional boilerplate (models, DTOs, config, route tables, test fixtures); the code is generated; a shared abstraction would need a vague name likeprocessData; or the pair is under about 10 lines. Only a pair that would let you delete code and give the extraction a precise name goes on to the next step - Design a refactoring: extract a shared function, class, module, or constant; the kind decides the strategy (below)
- Apply the refactoring — update both locations and all other usages
- Re-run jscpd with the same flags to confirm the clone is eliminated and the
dup%of the touched files went down; a clone that was(renamed)will not show in a default run, so check with--ignore-identifiersagain - Repeat for remaining clones, highest-impact first: exact clones, then renamed, then similar. Report the skipped candidates separately from the refactored ones, with the reason, so nobody mistakes a normalized run's count for real duplication
Refactoring Strategies
Extract function — when the duplicate is a block of logic:
// Before: same block in two places
// After: shared function called from both places
Extract module/utility — when the duplicate spans multiple files in different domains:
// Move shared logic to a shared utility file and import it
Extract constant or config — when the duplicate is repeated data or configuration.
Template/base class — when the duplicate is structural (e.g., repeated class shape).
Parameterize — for (renamed) clones. The two sides are the same algorithm over different names or values, so the things that differ become parameters:
// Before: computeCartTotal(items) and computeBasketTotal(entries), same body, other names;
// limits-dev.js and limits-prod.js, same shape, other numbers
// After: one function whose parameters are the identifiers that differed,
// or one function reading the values that differed from a config object
A renamed clone whose only difference is a literal is a missing constant or config entry, not a missing function.
Unify near-miss copies — for [~N gap] clones. Read the unmatched lines: the gap is the one place the copies diverged, typically a guard, a log call or an extra field. Extract the common body and pass the divergence in:
// Before: saveUser and saveAccount, identical except one inserted validation line
// After: one saveRecord(record, { validate }) with the inserted line behind the option,
// or the inserted line moved to the caller before the shared call
If the gap changes the meaning rather than adding a step, keep two functions but extract the shared halves.
Merge similar functions — for [~N ast] clones. The structure matches but names, literals and some statements do not. Diff the two functions first; the ast score tells how much is shared (0.9 is a copy with one edit, 0.75 a copy with a couple of added statements plus renames). Extract the shared skeleton and inject what differs, as arguments, a strategy object, or a callback:
// Before: buildInvoice(order, customer, taxRate) and buildCreditNote(refund, account, vatRate):
// same loop, same rounding, one extra guard and one extra log call in the second
// After: buildDocument(source, party, rate, { filter, onBuilt }) used by both
Below about 0.8 the pair usually shares an idiom, not an implementation; leave those alone unless the summary shows the file is a hotspot anyway.
Always ensure:
- All call sites are updated, not just the two reported by jscpd
- Tests still pass after refactoring
- The extracted abstraction has a clear, descriptive name
- The re-run uses the same detection flags as the run that found the clone
Tips
- Start with clones that have the highest line count — they have the most impact
- Use the summary's
dup%column to order the work: a large file with a high share of duplicated lines pays back first - A clone between test files may indicate a missing test helper
- Clones across unrelated modules may signal a missing shared utility
- A cross-format clone (same logic in a
.jsand a.tsfile, found with--cross-formats) often means code was ported without deleting the original — consolidate into one implementation (usually the TypeScript one) and update imports, rather than extracting a third shared copy - Many
(renamed)clones in one file usually mean one abstraction is missing, not many: look for the shared shape before extracting pair by pair. Many(renamed)clones across test files usually mean nothing: test cases are supposed to look alike - Do not gate CI (
--threshold,--fail-on-new-clones) on the Type-2/Type-3 passes until the team has reviewed what they report on this codebase; gate on the exact run --similarityonly covers JavaScript and TypeScript today; for other languages rely on the exact and--max-gap-linespasses- Use
--min-lines 10to filter noise and focus on meaningful duplications - Keep a separate
--baselineper set of detection flags when gating CI: renamed and similar runs fingerprint clones differently from exact runs
Related skills
More from kucherenko/jscpd and the wider catalog.

jscpd
Copy-paste detector for 220+ languages—find exact, renamed, and similar code duplicates to guide refactoring.

trading-strategist
Provides trading strategies for cryptocurrencies based on Binance market data, calculated technical analysis indicators, and aggregated market sentiment from crypto RSS news feeds. Use when users ask for trading advice, strategy recommendations, or analysis combining price data, TA, and sentiment for crypto assets like ETH, BTC, or altcoins.
axi
Ergonomic standards for building CLI tools that agents interact with via shell execution.

chrome-devtools-axi
Control Chrome browser sessions for automation, testing, and web debugging via CLI.

gh-axi
GitHub CLI wrapper for issues, PRs, workflows, releases, Projects, and gists.

lavish
Turn complex responses into interactive HTML artifacts for user review and annotation.