3. Clones
codeknife clones is the duplication blade. It finds functions and statement blocks that have the same structure after local names and literals are normalised, data types that declare almost the same fields, and (with --changed) new functions that look like an existing helper. Use it to find copy-paste code before it drifts apart, or to catch an agent that rewrote a helper instead of reusing it.
Quick example
Section titled “Quick example”Two TypeScript files contain the same loop with different variable names, and two interfaces with the same four fields:
export interface UserPayload { id: string; email: string; name: string; role: string; }
export function processOrder(items: number[], rate: number): number { let total = 0; for (const item of items) { if (item > 0) { const taxed = item * rate; const rounded = Math.round(taxed); if (rounded > 10) { total += rounded; } else { total += item; } } } return total;}src/invoices.ts is the same file with UserDto, processInvoice, rows, mult, acc, row and scaled as the names.
codeknife clones --no-cache --format humanwarning[CK_CLONE_BLOCK]: AST clone cluster (2 copies, 100% structural similarity, ~15 lines) --> src/invoices.ts:3-17 (src/invoices/processInvoice) = note: src/orders.ts:3 — similar src/orders/processOrder (15 lines) = fix: Extract the shared logic into one reusable helper parameterized on the differing values.
warning[CK_CLONE_DTO_SHAPE]: `UserPayload` shares 100% of fields with `UserDto` (src/invoices.ts:1) --> src/orders.ts:1 (src/orders/UserPayload) = fix: Consolidate duplicate DTO/schema types `UserPayload` and `UserDto` or share an embedded core type.
codeknife clones: FAIL (2 files, 0 errors, 2 warnings, 0 info, 2ms)The exit code is 1.
| Flag | Effect |
|---|---|
--threshold <FLOAT> |
Minimum Jaccard similarity for CK_CLONE_BLOCK. Overrides clone_similarity from codeknife.toml for this run. It does not change the DTO or reinvented helper checks. |
The global flags --path, --format, --strict, --changed, --since, --no-cache and --max-items also apply. See the CLI Reference. --strict does not change any threshold used by this blade.
The help text gives the range as 0.0..=1.0, but the value is not checked. --threshold 1.5 is accepted and finds no clone blocks. A negative value must be written as --threshold=-1; it is accepted and lowers the bar to any pair that the bucketing step (below) puts together. A value that is not a number is rejected by the argument parser with exit code 2:
error: invalid value 'abc' for '--threshold <THRESHOLD>': invalid float literal
For more information, try '--help'.The [blades] clones = false switch in codeknife.toml only affects codeknife check and the other commands that run the whole static suite. codeknife clones always runs the blade.
| Rule ID | Severity | Triggers when | Config key (default) | --strict |
|---|---|---|---|---|
CK_CLONE_BLOCK |
warning | Two or more fragments have Jaccard similarity at or above the threshold | clone_similarity (0.82), clone_min_lines (10), clone_min_nodes (45); --threshold |
no change |
CK_CLONE_DTO_SHAPE |
warning | Two field-only types in different files share at least the given fraction of field names | dto_field_overlap (0.80) |
no change |
CK_CLONE_REINVENTED_HELPER |
warning | With --changed, a function in a changed file is at least 78% similar to a function in an unchanged file |
none (fixed at 0.78) | no change |
All config keys are under [thresholds] in codeknife.toml. No rule in this blade has an autofixer; the Autofix Engine does not change CK_CLONE_* findings. The full catalogue is in the Rule Catalogue.
How structural clones are detected
Section titled “How structural clones are detected”1. Fragments
Section titled “1. Fragments”CodeKnife collects fragments from every function and method that is not a test. Items in test files are marked as tests, so test code is never part of a clone. There are two kinds of fragment:
- Whole functions. A function becomes a fragment when its line count is at least
clone_min_linesand its normalised token count is at leastclone_min_nodes. The fragment’s symbol is the function’s qualified name. - Statement blocks. For a function body with at least 4 top-level statements, CodeKnife slides a window of 6 consecutive statements (or all of them, if there are fewer than 6) across the body. A window is kept when it spans at least 5 lines and 20 tokens, and becomes a fragment when it also reaches
clone_min_lineslines andclone_min_nodestokens. The symbol is the function name plus@Land the window’s first line, for exampleapp.sales.report_sales@L2.
Despite its name, clone_min_nodes counts normalised leaf tokens, not syntax tree nodes.
2. Normalisation
Section titled “2. Normalisation”Each fragment’s syntax tree is flattened into its leaf tokens:
- Comments are dropped.
- Literals (numbers, strings, template strings, characters,
true,false) become$LIT. - Parameters and locally bound names (from
let, variable declarators,forloops, short variable declarations and plain assignments) become$ID. - A name after
.in a field or member access becomes$FIELD. InMath.round(taxed),roundbecomes$FIELDandtaxedbecomes$ID. - Every other identifier, keyword and punctuation token is kept as written. In the same call,
MathstaysMath, and a call to a free function such asapplyTax(x)keeps the nameapplyTax.
This is why processOrder and processInvoice above are 100% similar: they differ only in parameter and local names.
3. Shingles and MinHash
Section titled “3. Shingles and MinHash”The token list is cut into overlapping 5-token shingles. Each shingle is hashed with xxh3 into a set. A fragment with fewer than 5 tokens has no shingles and is dropped. CodeKnife then computes a 64-value MinHash signature for each set and splits it into 16 bands of 4 values. Fragments that share any band land in the same bucket.
4. Similarity
Section titled “4. Similarity”Only fragments that share a bucket are compared. For each such pair, CodeKnife computes the exact Jaccard similarity of their shingle sets: the size of the intersection divided by the size of the union. A pair is linked when the similarity is at or above the threshold (--threshold, else clone_similarity). Two fragments in the same file whose line ranges overlap are never linked, so a function is not matched with its own statement blocks.
Because only bucketed pairs are compared, lowering the threshold does not guarantee that every pair above it is found.
5. Clusters and reporting
Section titled “5. Clusters and reporting”Linked fragments are grouped into connected clusters. A cluster becomes one CK_CLONE_BLOCK finding when:
- it has 2 or more fragments,
- if it has exactly 2, the shorter one has at least
max(clone_min_lines, 12)lines, - with
--changed, at least one fragment is in a changed file, - its first fragment is not a statement block that sits inside a whole-function fragment of the same cluster.
The finding is placed on the cluster’s first fragment. The message gives the number of copies, the lowest similarity among the links, and the shortest fragment’s line count. The other fragments, up to 5, are listed as related spans (= note: lines in human output, evidence in JSON). The metric value is the number of copies, and the impact is 55.
--threshold changes which pairs are linked. Lowering it below the 79% match of a third, slightly different function pulls that function into the cluster:
codeknife clones --threshold 0.75 --no-cache --format humanwarning[CK_CLONE_BLOCK]: AST clone cluster (3 copies, 79% structural similarity, ~15 lines) --> src/invoices.ts:3-17 (src/invoices/processInvoice) = note: src/orders.ts:3 — similar src/orders/processOrder (15 lines) = note: src/payments.ts:1 — similar src/payments/sumPayments (16 lines) = fix: Extract the shared logic into one reusable helper parameterized on the differing values....A statement-block clone, where two Python functions share a run of statements but differ elsewhere:
warning[CK_CLONE_BLOCK]: AST clone cluster (3 copies, 83% structural similarity, ~15 lines) --> app/costs.py:7-21 (app.costs.summarize_costs@L7) = note: app/costs.py:8 — similar app.costs.summarize_costs@L8 (15 lines) = note: app/sales.py:2 — similar app.sales.report_sales@L2 (15 lines) = fix: Extract the shared logic into one reusable helper parameterized on the differing values.Duplicate DTO shapes (CK_CLONE_DTO_SHAPE)
Section titled “Duplicate DTO shapes (CK_CLONE_DTO_SHAPE)”This check compares data types by the names of their fields. A struct, class or interface is a candidate when:
- it declares at least 4 fields,
- it is not test code,
- it has no methods other than trait implementations,
- its path does not start with, or contain
/followed by, any ofdocs_src/,examples/,_examples/,benchmarks/,bench/,fixtures/ortestdata/.
For each pair of candidates in different files, the overlap is the Jaccard similarity of their field name sets. A pair at or above dto_field_overlap (default 0.80) is reported once, on the second type of the pair, with the first type’s file and line in the message. The metric is the overlap percentage and the impact is 45. With --changed, a pair is checked when either file changed.
warning[CK_CLONE_DTO_SHAPE]: `UserPayload` shares 100% of fields with `UserDto` (src/invoices.ts:1) --> src/orders.ts:1 (src/orders/UserPayload) = fix: Consolidate duplicate DTO/schema types `UserPayload` and `UserDto` or share an embedded core type.Field types are not compared, only names.
Reinvented helpers (CK_CLONE_REINVENTED_HELPER)
Section titled “Reinvented helpers (CK_CLONE_REINVENTED_HELPER)”This check runs only with --changed. It compares every whole-function fragment in a changed file with every whole-function fragment in an unchanged file, using the same Jaccard similarity as above but without the bucketing step. For each changed function, the best match at or above 0.78 is reported. The threshold is fixed: --threshold and clone_similarity do not change it. The finding carries the existing function as a related span, the similarity percentage as its metric, and impact 65.
Here src/payments.ts is a new, untracked file whose function is 79% similar to a committed one. That is below the 82% clone threshold, so it is not a CK_CLONE_BLOCK, but it is above 78%:
codeknife clones --changed --no-cache --format humanwarning[CK_CLONE_REINVENTED_HELPER]: new function `src/payments/sumPayments` is 79% structurally similar to existing helper `src/invoices/processInvoice` --> src/payments.ts:1-16 (src/payments/sumPayments) = note: src/invoices.ts:3 — existing src/invoices/processInvoice (15 lines) = fix: Reuse existing helper `src/invoices/processInvoice` at src/invoices.ts:3 instead of reinventing duplicate logic.
codeknife clones: FAIL (3 files, 0 errors, 1 warnings, 0 info, 3ms)“New function” in the message means any function in a changed file, not only functions added by the change. See Paths, Excludes & Changed Scope for how the changed file set is built.
Limits
Section titled “Limits”- Test code is never compared, because fragments skip test items and items in test files.
- Generated code is only skipped when it is excluded from analysis. The default
excludelist contains**/*.generated.*and**/*.min.js; a file namedapi.generated.tswas not scanned in testing. See Paths, Excludes & Changed Scope. - Across languages, the blade does not filter by language, but tokens are the raw grammar tokens of each language. In testing, a JavaScript copy of the TypeScript
processOrderbody was not reported as a clone of it, while two JavaScript copies were. - Small functions below
clone_min_lineslines orclone_min_nodestokens are never fragments. Pairs also need 12 lines unlessclone_min_linesis higher. - Called names matter. Only parameters, locals, member names and literals are normalised. Two functions that call different helpers are less similar even if their shape matches.
Exit codes
Section titled “Exit codes”| Code | When |
|---|---|
0 |
No warning findings remain after the baseline filter. |
1 |
At least one finding remains. Every rule in this blade is a warning. |
2 |
CodeKnife could not run, for example because codeknife.toml or arch.toml does not parse, or an argument is invalid. |
See Output Formats & Exit Codes.
Also available via
Section titled “Also available via”codeknife checkruns this blade with the configuredclone_similarity(there is no--thresholdthere). Thecodeknife_checkMCP tool does the same. See MCP Tools.codeknife reusesearches for an existing helper before you write a new one.