4. Dead Code
codeknife dead is the dead code blade. It walks the call graph from the repository’s entry points and reports private functions, methods and constants that nothing reaches, files that nothing imports, production helpers that only tests call, private wrappers with a single caller, and internal traits or interfaces with at most one implementation. With --fix --write it deletes unreachable private functions. Use it to clean up after refactors, or to check that an agent did not leave unused code behind.
Quick example
Section titled “Quick example”deaddemo/ Cargo.toml src/main.rs main, thin_wrap, real_work, unused_dead_fn, unused_crate_fn, UNUSED_LIMIT, test_only_helper, exported_cb (#[no_mangle]), a #[test] src/shapes.rs trait Shape, struct Square, impl Shape for Square src/orphan.rs pub fn forgotten() (no `mod orphan;` anywhere)// src/main.rs (excerpt)mod shapes;
fn main() { let total = thin_wrap(2); println!("{total}");}
fn thin_wrap(x: i32) -> i32 { real_work(x)}
/// Old pricing rule, no longer called.#[inline]fn unused_dead_fn() -> i32 { 42}
pub(crate) fn unused_crate_fn() -> i32 { 7}
const UNUSED_LIMIT: usize = 10;
#[no_mangle]extern "C" fn exported_cb() -> i32 { 7}codeknife dead --no-cache --format humanwarning[CK_DEAD_SYMBOL]: unreachable internal symbol `unused_dead_fn` --> src/main.rs:18-20 (deaddemo::unused_dead_fn) = fix: Delete this unused function (or run `codeknife dead --fix --write`).
warning[CK_DEAD_SYMBOL]: unreachable internal symbol `unused_crate_fn` --> src/main.rs:22-24 (deaddemo::unused_crate_fn) = fix: Delete this unused symbol or wire it into an active execution path.
warning[CK_DEAD_SYMBOL]: unreachable internal symbol `UNUSED_LIMIT` --> src/main.rs:26 (deaddemo::UNUSED_LIMIT) = fix: Delete this unused symbol or wire it into an active execution path.
warning[CK_DEAD_TEST_ONLY_PROD]: production symbol `test_only_helper` is only called by tests --> src/main.rs:28-30 (deaddemo::test_only_helper) = fix: Move this helper into test code or delete it if the production feature was removed.
warning[CK_DEAD_FILE]: orphan file `src/orphan.rs` has no inbound imports or reachable symbols --> src/orphan.rs:1-3 (src/orphan.rs) = fix: Delete this unreferenced file or wire its module into an entrypoint.
info[CK_DEAD_ONE_CALLER_WRAPPER]: one-caller pass-through wrapper `thin_wrap` adds indirection with zero depth --> src/main.rs:8-10 (deaddemo::thin_wrap) = fix: Inline this single-caller wrapper directly at its call site to minimize reader load.
info[CK_DEAD_SINGLE_IMPL_TRAIT]: internal trait/interface `Shape` has 1 implementation(s) --> src/shapes.rs:1-3 (deaddemo::shapes::Shape) = fix: Collapse single-implementation abstractions into concrete types until a second implementation exists.
codeknife dead: FAIL (3 files, 0 errors, 5 warnings, 2 info, 2ms)The exit code is 1. exported_cb is not reported because of its #[no_mangle] attribute.
| Flag | Effect |
|---|---|
--fix |
Plan the removal of every reported dead symbol that is a strictly private function, and add a note with the count. Nothing is written. |
--write |
Together with --fix, apply the removals to disk. On its own, --write does nothing. |
The global flags --path, --format, --strict, --changed, --since, --no-cache and --max-items also apply. See the CLI Reference. --strict does not change this blade.
The [blades] dead = false switch in codeknife.toml only affects codeknife check and the other commands that run the whole static suite. codeknife dead always runs the blade.
| Rule ID | Severity | Triggers when | Config key | --strict |
Fixer |
|---|---|---|---|---|---|
CK_DEAD_SYMBOL |
warning | A non-public function, method or constant is unreachable and its name is not used elsewhere | none | no change | dead --fix, codeknife fix (private functions only) |
CK_DEAD_TEST_ONLY_PROD |
warning | A non-public production symbol is reachable only from tests | none | no change | none |
CK_DEAD_FILE |
warning | A non-entry file is never imported and none of its items are reachable | none | no change | none |
CK_DEAD_ONE_CALLER_WRAPPER |
info | A non-public thin wrapper has exactly one non-test caller | none | no change | codeknife fix --aggressive (some cases) |
CK_DEAD_SINGLE_IMPL_TRAIT |
info | A non-public trait or interface has at most one implementation (rules differ by language) | none | no change | none |
None of these checks has a threshold in codeknife.toml. Info findings are shown but do not fail the run. The full catalogue is in the Rule Catalogue.
How reachability works
Section titled “How reachability works”The blade uses the references that the language adapters resolve: calls, field reads and writes, type references and trait implementations. Each resolved reference from one item to another is an edge. See Import Resolution for how references are resolved.
CodeKnife runs two breadth-first walks over these edges. The production walk ignores references that sit in test code. The test walk includes them and also starts from every test item.
An item is a root of both walks when any of these holds:
- it is an entry point, as marked by its language adapter (below),
- it is a trait implementation method,
- it is preceded by an entry attribute or decorator (below),
- it is public and its file is an entry file,
- it is public and its module, or an ancestor module, is a library root.
The target of any reference made from top-level code (outside any function) is also a root.
Entry points, entry files and library roots by language, as the adapters set them:
| Language | Entry point items | Entry files | Library root |
|---|---|---|---|
| Rust | main, or an attribute containing command, get( or post( |
src/lib.rs, src/main.rs, src/bin/, benches/, examples/ |
the crate has src/lib.rs |
| Python | a function named main |
__init__.py, __main__.py, or a file containing if __name__ == "__main__" or if __name__ == '__main__' |
packages found by pyproject.toml |
| TypeScript / JavaScript | none | module named index, main, app, server, page, layout, route, loading or error; paths containing routes/ or pages/; .config files |
package.json has exports, main or module |
| Go | main without a receiver |
main.go, files in the go.mod directory, and every file whose package is not main |
packages with no main.go |
Language Support covers these adapters in full.
Entry attributes and decorators
Section titled “Entry attributes and decorators”CodeKnife looks at the lines directly above an item, up to the first blank line, while they are attributes, decorators or doc comments. If any of them contains one of these strings, the item is a root:
#[no_mangle] #[unsafe(no_mangle)] #[export_name #[unsafe(export_name#[cfg( #[pyfunction] #[pymethods] #[wasm_bindgen]#[tokio::main] #[tauri::command] @app. @router.@pytest.fixtureAny #[cfg(...)] attribute counts, so a function behind a feature flag is never reported.
Visibility
Section titled “Visibility”Public items are walk roots in the cases above, but a public item is never reported as CK_DEAD_SYMBOL in any case. Only non-public items are checked. The adapters assign visibility like this:
| Language | Public | Not public |
|---|---|---|
| Rust | pub |
private, and pub(crate) / pub(super) (module visibility) |
| Python | names without a leading _; function and method names that start with __ |
other names starting with _ (private) |
| TypeScript / JavaScript | exported declarations; class members without private or protected |
non-exported declarations, private and protected members, #name members (private) |
| Go | names starting with an upper-case letter | other names (module visibility) |
The difference between private and module visibility matters for --fix, which only removes private functions.
What each rule checks
Section titled “What each rule checks”Dead symbols (CK_DEAD_SYMBOL) and test-only code (CK_DEAD_TEST_ONLY_PROD)
Section titled “Dead symbols (CK_DEAD_SYMBOL) and test-only code (CK_DEAD_TEST_ONLY_PROD)”An item is checked when it is a function, method or constant, is not a test, is not in a test file, is not public, and is not a trait implementation. With --changed, only items in changed files are checked. Reachability is still computed over the whole repository.
If the item is not reached by the production walk, CodeKnife scans for its name as a whole word (letters, digits and _ delimit words) in:
- its own file, outside the item itself, comments and test items,
- other non-test files of the same language that are in the same module, import the item’s module, or are a parent or child module of it.
String literals are not skipped. If the name appears anywhere in that text, the item is treated as used. Names shorter than 2 characters skip this scan.
If the item is still unused:
- it is
CK_DEAD_TEST_ONLY_PROD(impact 50) when the test walk reaches it, - otherwise it is
CK_DEAD_SYMBOL(impact 55). The fix hint saysDelete this unused function (or run codeknife dead --fix --write).for a private function, andDelete this unused symbol or wire it into an active execution path.for anything else.
Dead files (CK_DEAD_FILE)
Section titled “Dead files (CK_DEAD_FILE)”A file is reported, on its full line range with impact 60, when all of these hold:
- it is not a test file and not an entry file,
- it has at least one non-test item,
- no import targets its module, and no non-test reference from another module targets it,
- none of its non-test items is reached by the production walk.
With --changed, only changed files are checked. A dead file’s public items are not also reported as dead symbols, because public items never are.
One-caller wrappers (CK_DEAD_ONE_CALLER_WRAPPER)
Section titled “One-caller wrappers (CK_DEAD_ONE_CALLER_WRAPPER)”A wrapper is a function or method whose body is a single statement that either returns a field of the receiver (a field accessor) or is a single-line call to another function that CodeKnife can resolve (a forwarder). The finding is an info (impact 35) when the wrapper is not a test, not a trait implementation, not public, and exactly one non-test reference targets it. With --changed, only wrappers in changed files are checked.
Single-implementation traits (CK_DEAD_SINGLE_IMPL_TRAIT)
Section titled “Single-implementation traits (CK_DEAD_SINGLE_IMPL_TRAIT)”For every non-public trait or interface that is not a test, CodeKnife counts the trait-implementation references whose target name equals the trait’s name, across the whole repository. The result is an info (impact 30) when:
| Language | Reported when the count is |
|---|---|
| Rust, Python | 0 or 1 |
| TypeScript, JavaScript | exactly 1 |
| Go | never reported |
An unimplemented TypeScript interface such as a props type is not reported. In Rust, a trait with no implementation is:
CODEKNIFE dead status=pass files=1 errors=0 warnings=0 infos=1 elapsed_ms=2[1] INFO CK_DEAD_SINGLE_IMPL_TRAIT src/lib.rs:1-3 sym=infoonly::Foo impact=30 | internal trait/interface `Foo` has 0 implementation(s) | fix: Collapse single-implementation abstractions into concrete types until a second implementation exists.The status is pass and the exit code is 0 because the only finding is an info.
Implementations are matched by name only. Two traits with the same name in different modules share one count.
Removing dead code
Section titled “Removing dead code”Dry run: --fix
Section titled “Dry run: --fix”codeknife dead --fix --no-cache --format agentCODEKNIFE dead status=fail files=3 errors=0 warnings=5 infos=2 elapsed_ms=2[1] WARNING CK_DEAD_FILE src/orphan.rs:1-3 sym=src/orphan.rs impact=60 | orphan file `src/orphan.rs` has no inbound imports or reachable symbols | fix: Delete this unreferenced file or wire its module into an entrypoint.[2] WARNING CK_DEAD_SYMBOL src/main.rs:18-20 sym=deaddemo::unused_dead_fn impact=55 | unreachable internal symbol `unused_dead_fn` | fix: Delete this unused function (or run `codeknife dead --fix --write`)....NOTE dry-run: 1 strictly private dead symbol(s) can be removed with `--fix --write`Of the three CK_DEAD_SYMBOL findings, only unused_dead_fn is removable:
- Strictly private means private visibility, not module visibility.
unused_crate_fnispub(crate), which is module visibility, so it is reported but not removed. For the same reason,--fixnever removes Go functions. - Functions only. Methods and constants (
UNUSED_LIMIT) are reported but not removed. CK_DEAD_TEST_ONLY_PROD,CK_DEAD_FILEand the info rules are never removed. The orphan file stays.
When nothing is removable, the dry run adds no note.
Write: --fix --write
Section titled “Write: --fix --write”codeknife dead --fix --write --no-cache --format agentCODEKNIFE dead status=fail files=3 errors=0 warnings=5 infos=2 elapsed_ms=2...[2] WARNING CK_DEAD_SYMBOL src/main.rs:18-20 sym=deaddemo::unused_dead_fn impact=55 | unreachable internal symbol `unused_dead_fn` | fix: Delete this unused function (or run `codeknife dead --fix --write`)....NOTE removed unreachable private symbols across 1 file(s)git diff@@ -13,12 +13,6 @@ fn real_work(x: i32) -> i32 { x + 1 }
-/// Old pricing rule, no longer called.-#[inline]-fn unused_dead_fn() -> i32 {- 42-}- pub(crate) fn unused_crate_fn() -> i32 { 7 }The report lists the findings as they were before the write, and the exit code is still 1. Run the command again to see the updated state. With --write, the note is always added, and reads across 0 file(s) when nothing was removed.
What is deleted
Section titled “What is deleted”For each removable function, the deleted range is:
- Start: the beginning of the function’s first line, extended upward over directly attached lines until a blank line or another kind of line. Attached lines are doc comments (
///,/**, lines starting with*or equal to*, and the lines of a block comment that ends with*/) and, by language: Rust attributes#[...]; Python decorators@...and comments starting with#; TypeScript and JavaScript decorators@...; Go//comments. - End: the end of the function, plus trailing spaces and tabs and up to two line breaks.
Edits in a file are applied from the bottom up. The new text is parsed again with tree-sitter; if the parse has errors, the file is left unchanged and is not counted in the note. There is no other check and no backup, so commit or stash your work first.
Decorators are removed together with the function. In Python, a function marked @staticmethod above def _dead_helper(): lost both lines. A function whose decorator is not in the entry list is removed with it, even when a framework calls it:
@app.get("/health")def _health(): return {"ok": True}
@shared_taskdef _nightly_job(): return 1CODEKNIFE dead status=fail files=1 errors=0 warnings=1 infos=0 elapsed_ms=2[1] WARNING CK_DEAD_SYMBOL svc/routes.py:13-14 sym=svc.routes._nightly_job impact=55 | unreachable internal symbol `_nightly_job` | fix: Delete this unused function (or run `codeknife dead --fix --write`)._health is kept because @app. is on the list. _nightly_job is reported and would be deleted.
Removal happens in one pass
Section titled “Removal happens in one pass”The name scan means a dead function that calls another dead function keeps its callee alive for this run. In this example, dead_a calls dead_b, and log_names prints the string "named_in_string":
fn dead_a() -> i32 { dead_b() + 1}
fn dead_b() -> i32 { 2}
fn named_in_string() -> i32 { 3}
fn log_names() { println!("named_in_string");}The first codeknife dead --fix --write removed dead_a and log_names. Only the second run reported and removed dead_b and named_in_string. Repeat the command until the note reports 0 file(s), or use codeknife fix --write, which runs up to --max-passes passes (see Autofix Engine).
Fixers
Section titled “Fixers”| Rule | codeknife dead --fix |
codeknife fix |
|---|---|---|
CK_DEAD_SYMBOL |
removes strictly private dead functions | same removal, as a safe patch |
CK_DEAD_ONE_CALLER_WRAPPER |
no | with --aggressive, inlines private forwarding functions whose one caller and target are in the same file |
CK_DEAD_TEST_ONLY_PROD |
no | no |
CK_DEAD_FILE |
no | no |
CK_DEAD_SINGLE_IMPL_TRAIT |
no | no |
codeknife fix also plans CK_DEAD_UNUSED_IMPORT patches, which remove single-symbol import lines whose name is not used elsewhere in the file. This blade never reports unused imports; the rule ID exists only as a fix patch. For a Python file that starts with import os and never uses os:
codeknife fix --path impdemo --no-cache --format agentcodeknife dead --path impdemo --no-cache --format agentCODEKNIFE fix mode=dry-run passes=1 applied=1 reverted=0 conflicts=0 files=1 [FIX] CK_DEAD_UNUSED_IMPORT | Remove unused import `os` in cli.py:1CODEKNIFE dead status=pass files=1 errors=0 warnings=0 infos=0 elapsed_ms=1On the Rust demo above:
codeknife fix --aggressive --no-cache --format agentCODEKNIFE fix mode=dry-run passes=1 applied=2 reverted=0 conflicts=0 files=1 [FIX] CK_DEAD_SYMBOL | Remove unreachable private function in src/main.rs [FIX] CK_DEAD_ONE_CALLER_WRAPPER | Inline 1-caller wrapper `thin_wrap` -> `real_work`The Autofix Engine page describes the exact conditions for each patch.
Known sources of false results
Section titled “Known sources of false results”Reachability only follows references that the adapters resolve to an item. Anything else can cause a wrong result:
- Dynamic calls. Calls through reflection,
getattr, string lookups, dynamic dispatch the adapter cannot resolve, or registration by a framework do not create edges. The name scan saves an item whose name appears as a word in its own file or a related file, including inside strings and macro invocations, because the scan works on raw text. - Framework entry points. Only the attribute and decorator strings listed above, plus the per-language entry points, are recognised. Other decorators, such as
@shared_taskabove, do not protect a function. - Missed dead code. Public items are never reported as dead symbols. A non-public item whose name appears as a word in a related file (for example in a string, or in another dead function) is not reported. Structs, enums and classes are not checked.
- Name collisions. The name scan and the trait implementation count both match by bare name, so an unrelated item with the same name can hide a dead one.
- Import resolution gaps.
CK_DEAD_FILEdepends on resolved imports. A Rust file that imports any external crate is never reported as an orphan file, and a JavaScript file that is only loaded throughconst x = require(...)or a dynamicimport()is reported as one. See Import Resolution.
Exit codes
Section titled “Exit codes”| Code | When |
|---|---|
0 |
No warning findings remain after the baseline filter (info findings do not count). |
1 |
At least one warning remains. This is unchanged by --fix --write, because the report shows the state before the write. |
2 |
CodeKnife could not run, for example because codeknife.toml or arch.toml does not parse. |
See Output Formats & Exit Codes.
Also available via
Section titled “Also available via”codeknife checkruns this blade without--fix. Thecodeknife_checkMCP tool does the same.codeknife fixand thecodeknife_fixMCP tool apply the dead code patches listed under Fixers. See MCP Tools.