Reuse Oracle
codeknife reuse searches the functions and types that already exist in your repository for ones that match a short description of what you are about to write. Use it before adding a helper, so that you (or an agent) import the existing one instead of writing a second copy.
The search is lexical. It splits names, doc comments, file paths and code into words, adds a small fixed synonym list, and ranks with a TF-IDF style score. It does not use embeddings or any model, so it only finds code that shares words with your query.
Quick start
Section titled “Quick start”codeknife --no-cache --format agent reuse "validate positive amount"CODEKNIFE reuse query="validate positive amount" scanned=14 matches=3[1] score=81.0 fn `src.helper.verify_positive_amount` (src/helper.py:1, vis=public, callers=0) sig: def verify_positive_amount(amount): """Check that an order amount is positive.""" use: from src.helper import verify_positive_amount[2] score=55.5 fn `src.engine.validate_order` (src/engine.py:4, vis=public, callers=1) sig: def validate_order(total, cmd, region, currency, coupon, rush): try: use: from src.engine import validate_order[3] score=27.0 fn `src.engine.submit_order` (src/engine.py:19, vis=public, callers=0) sig: def submit_order(total): return validate_order(total, "echo ok", "eu", "EUR", None, False) use: from src.engine import submit_orderEach result shows the score, the kind, the qualified name, location, visibility, the number of callers, the signature (sig:) and an import line (use:).
A query that shares no words with the code returns nothing:
codeknife --no-cache --format agent reuse "zebra quantum"CODEKNIFE reuse query="zebra quantum" scanned=14 matches=0Arguments and flags
Section titled “Arguments and flags”| Argument or flag | Default | Effect |
|---|---|---|
QUERY (positional, required) |
Words describing what you need. An empty string is accepted. | |
--lang LANG |
all languages | Only search files of one language. |
--snippet CODE |
none | Add a code-overlap score (see below). |
--top N |
8 |
Maximum results. 0 is treated as 1. |
Accepted --lang values (case-insensitive, surrounding spaces ignored):
| Language | Values |
|---|---|
| Rust | rust, rs |
| TypeScript | ts, typescript |
| JavaScript | js, javascript |
| Python | py, python |
| Go | go, golang |
Anything else fails with exit code 2:
codeknife --no-cache --format agent reuse "anything" --lang javacodeknife error: unsupported language `java` (use rust, ts, js, python, go)Global flags: --format json and --format sarif print the JSON report (not SARIF); every other format prints the text layout above. --no-cache stops the parse cache from being written. --changed, --since, --strict and --max-items have no effect on the result.
What is searched
Section titled “What is searched”Every item in the code model that is a function, method, struct, class, enum, trait or interface, except:
- test items,
- items in test files,
- items in other languages when
--langis set.
scanned (scanned_items in JSON) is the number of items left after these filters.
For each item CodeKnife builds four word sets:
| Set | Built from |
|---|---|
| Name | The short name and the qualified name |
| Doc | Up to 3 comment lines directly above the item: lines starting with ///, //!, //, #, * or /**. Lines starting with @ (decorators) are skipped over. |
| Path | The file path |
| Body | The signature, parameter names and types, field names, and the item’s normalized AST tokens |
The signature is the item’s first two source lines joined with a space, cut at the first { or at 160 bytes.
How text is split into words
Section titled “How text is split into words”The same tokenizer is used for the query, the snippet and every item:
-
Every character that is not an ASCII letter or digit is a separator. Non-ASCII letters are separators too.
-
A lowercase letter followed by an uppercase letter starts a new word (
parseCoverageReportbecomesparse,coverage,report). -
Everything is lowercased.
-
Light stemming: the first of the suffixes
ing,ed,es,sthat the word ends with is removed, but only when the word is longer than the suffix plus 3 characters.decodingbecomesdecod,invoicesbecomesinvoic,rowsstaysrows. -
Words shorter than 2 characters and these stop words are dropped:
a,an,and,are,as,at,by,do,for,from,get,in,into,is,it,of,on,or,set,that,the,to,use,with,fn,def,func,let,var,const,return,pub,export
Synonyms
Section titled “Synonyms”If a query word starts with any entry of a group below, every entry of that group is added to the query with weight 0.55. Your own words have weight 1.0.
| Group |
|---|
parse, decode, load, deserial, read |
format, render, serial, stringif, print |
validat, check, verif, audit, assert |
http, fetch, request, client, endpoint |
hash, digest, checksum, sha, xxh |
path, file, dir, fs, walk |
date, time, clock, durat, timeout |
auth, token, jwt, session, secret |
cache, store, memo, index |
diff, patch, delta, edit, chang |
graph, cycle, bfs, dfs, scc, tangle |
The added words are the group entries themselves, and they must equal an item’s word exactly. A stem such as verif only matches the word verif, not verify. In the quick-start example, validate brought in check, which matched the docstring in the signature; it did not match verify in the function name. Querying verify positive amount instead matches verify directly.
Stemming can also cause misses:
codeknife --no-cache --format json reuse "decoding invoices" --top 1{ "query": "decoding invoices", "scanned_items": 2, "candidates": []}The same repository has parse_invoice_total. decoding and invoices became decod and invoic, which match nothing. decode invoice finds it:
codeknife --no-cache --format agent reuse "decode invoice"CODEKNIFE reuse query="decode invoice" scanned=2 matches=1[1] score=60.7 fn `rdoc::parse_invoice_total` (src/lib.rs:3, vis=public, callers=0) sig: pub fn parse_invoice_total(raw: &str) -> usize use: use rdoc::parse_invoice_total;Scoring
Section titled “Scoring”For each item:
- Word weight. For each query word (including synonyms) that appears in the item, add up:
3.5if in the name set,2.0if in the doc set,1.5if in the path set,1.5if in the body set. - IDF.
idf = ln((N + 1) / (df + 1)) + 1, whereNis the number of scanned items anddfis how many of them contain the word in any set. BecauseNdepends on--lang, the same query scores differently with and without it. - Lexical score. Sum over matched words of
word weight × query weight × idf × 6. - Coverage multiplier.
0.35 + 0.65 × (matched original words / original word count). Synonyms do not count as matched original words. - Snippet score. With
--snippet:40 × |snippet words ∩ body words| / |snippet words ∪ body words|. Otherwise 0. - Items with
lexical + snippetof0.01or less are dropped. - Adjusted.
(lexical + snippet) × coverage × visibility + min(callers, 10) × 0.6, where visibility is1.25for public,1.05for module,0.85for private, and callers is the number of inbound call edges. - Score.
100 × adjusted / (adjusted + 45), clamped to 0 to 99.9.
The score is a relative rank, not a probability. It can never reach 100. Results are sorted by score, then callers, then file path, then start line, and cut to --top.
matched_terms in JSON lists every query word (original or synonym) the item matched.
Snippet matching
Section titled “Snippet matching”--snippet takes a piece of code. It is not parsed: it goes through the word tokenizer above, and the resulting word set is compared with each item’s body set. The overlap adds up to 40 points before scaling. Use it when the code you are about to write shares parameter and type names with existing code.
codeknife --no-cache --format agent reuse "sum rows" --snippet 'function total(rows: number[], mult: number) { let acc = 0; for (const row of rows) { acc += Math.round(row * mult); } return acc; }' --lang ts --top 3CODEKNIFE reuse query="sum rows" scanned=3 matches=3[1] score=34.8 fn `src/b/scoreInvoice` (src/b.ts:1, vis=public, callers=1) sig: export function scoreInvoice(rows: number[], mult: number): number use: import { scoreInvoice } from './src/b'[2] score=7.2 fn `src/a/scoreOrder` (src/a.ts:1, vis=public, callers=1) sig: export function scoreOrder(items: number[], rate: number): number use: import { scoreOrder } from './src/a'[3] score=5.3 fn `src/index/main` (src/index.ts:4, vis=public, callers=0) sig: export function main(): number use: import { main } from './src/index'Without the snippet the same query returns only scoreInvoice, with score 23.0. scoreOrder is a structural clone of scoreInvoice but uses different names (items, rate), so it gains little from the snippet. For structural clone detection use Clones.
Import hints
Section titled “Import hints”reuse_hint (use: in text output) depends on the language of the file:
| Language | Hint |
|---|---|
| Rust | use CRATE::REST; built from the qualified name (- in the crate name becomes _); use crate::NAME; when the qualified name has no :: |
| TypeScript, JavaScript | import { NAME } from './PATH' with .ts or .js removed from the file path |
| Python | from MODULE import NAME, the file path with .py removed and / replaced by . |
| Go | import "DIR" -> NAME, the file’s directory |
The hint is built from the file path relative to the repository root. It is not adjusted to the location of the file you are editing.
JSON output
Section titled “JSON output”codeknife --no-cache --format json reuse "validate positive amount" --top 1{ "query": "validate positive amount", "scanned_items": 14, "candidates": [ { "symbol": "src.helper.verify_positive_amount", "name": "verify_positive_amount", "kind": "fn", "visibility": "public", "file": "src/helper.py", "start_line": 1, "end_line": 3, "language": "python", "score": 80.99168, "signature": "def verify_positive_amount(amount): \"\"\"Check that an order amount is positive.\"\"\"", "doc_summary": null, "matched_terms": [ "amount", "check", "positive" ], "inbound_callers": 0, "reuse_hint": "from src.helper import verify_positive_amount" } ]}| Field | Type | Meaning |
|---|---|---|
query |
string | The query as given |
scanned_items |
number | Items searched after filters |
candidates |
array | Results, best first |
symbol |
string | Qualified name |
name |
string | Short name |
kind |
string | fn, method, struct, class, enum, trait or interface |
visibility |
string | public, module or private |
file, start_line, end_line |
Location | |
language |
string | Language of the file |
score |
number | 0 to 99.9, formula above |
signature |
string | First two lines, cut at { or 160 bytes |
doc_summary |
string or null | Comment lines above the item, joined with spaces |
matched_terms |
string array | Query words that matched, sorted |
inbound_callers |
number | Inbound call edges in the call graph |
reuse_hint |
string | Import line |
Rule IDs
Section titled “Rule IDs”reuse emits no findings and no rule IDs. For duplicate code that already exists, see the CK_CLONE_* rules on Clones and the Rule Catalogue.
Exit codes
Section titled “Exit codes”| Code | When |
|---|---|
0 |
Search ran, with or without matches |
2 |
Unsupported --lang, or another CodeKnife error |
101 |
Panic on a multi-byte character at byte 160 of a signature (see above) |