Autofix Engine
codeknife fix plans text edits for a fixed set of rules and, with --write, applies them to disk. It does not call a language model: every edit comes from the code model, tree-sitter parse trees and the blade analyzers. Use it to clean up the mechanical findings (dead private functions, debug leftovers, expired suppressions, broken doc links) before you or an agent deal with the rest.
Without --write the command is a dry run and changes nothing.
Dry run
Section titled “Dry run”This demo repository is a small Rust binary with a banner comment, an expired suppression, a dbg! call, an unused private function and a Markdown file that links to a file that moved from src/old/ to src/util/.
mod util;use util::helper::active;
// ======== Helpers ========pub fn run(x: i32) -> i32 { // eslint-disable-next-line until: 2020-01-01 -- old workaround dbg!(x); active() + x}
fn never_called() -> i32 { 99}
fn main() { let _ = run(2);}codeknife fix --format human --no-cacheecho $?codeknife fix (dry-run): planned 5 patch(es) across 2 file(s), 0 reverted (1 pass(es)) [FIX] CK_CMT_STRIP | Remove 1 strippable comment(s) in src/main.rs [FIX] CK_DEAD_SYMBOL | Remove unreachable private function in src/main.rs [FIX] CK_GUARD_SUPPRESSION_EXPIRED | Remove expired suppression (`until: 2020-01-01`) at src/main.rs:6 [FIX] CK_SLOP_DEBUG_LEFTOVER | Remove debug leftover at src/main.rs:7 [FIX] CK_DOC_DEAD_PATH | Rewrite broken link `../src/old/helper.rs` -> `../src/util/helper.rs` in docs/guide.md0A dry run always runs exactly one pass, so it does not show fixes that only become possible after an earlier fix is written (see Cascading passes).
codeknife fix --write --format human --no-cachegit diffcodeknife fix (write): applied 5 patch(es) across 2 file(s), 0 reverted (1 pass(es)) [FIX] CK_CMT_STRIP | Remove 1 strippable comment(s) in src/main.rs [FIX] CK_DEAD_SYMBOL | Remove unreachable private function in src/main.rs [FIX] CK_GUARD_SUPPRESSION_EXPIRED | Remove expired suppression (`until: 2020-01-01`) at src/main.rs:6 [FIX] CK_SLOP_DEBUG_LEFTOVER | Remove debug leftover at src/main.rs:7 [FIX] CK_DOC_DEAD_PATH | Rewrite broken link `../src/old/helper.rs` -> `../src/util/helper.rs` in docs/guide.md--- a/docs/guide.md+++ b/docs/guide.md@@ -1,3 +1,3 @@ # Guide
-See [the helper](../src/old/helper.rs) for details.+See [the helper](../src/util/helper.rs) for details.--- a/src/main.rs+++ b/src/main.rs@@ -1,17 +1,10 @@ mod util; use util::helper::active;
-// ======== Helpers ======== pub fn run(x: i32) -> i32 {- // eslint-disable-next-line until: 2020-01-01 -- old workaround- dbg!(x); active() + x }
-fn never_called() -> i32 {- 99-}- fn main() { let _ = run(2); }Running the same command again finds nothing left to do and reports applied 0 patch(es) across 0 file(s), 0 reverted (0 pass(es)).
fix does not use git. It writes files in place, so commit or stash your work first if you want an easy way back.
Verify and roll back
Section titled “Verify and roll back”With --write --verify, CodeKnife runs a verification command after writing and removes any patch that breaks it. Here the demo repository also contains src/math.rs, which calls a trait method through method syntax:
use std::ops::Add;
pub fn bump(x: i32) -> i32 { x.add(1)}The unused-import fixer matches whole words only, so it sees no use of Add and, with --aggressive, plans to delete the import. Removing it breaks the build.
codeknife fix --write --verify --aggressive --format agent --no-cacheecho $?git diff --statCODEKNIFE fix mode=write passes=2 applied=4 reverted=2 conflicts=0 files=2 [FIX] CK_CMT_STRIP | Remove 1 strippable comment(s) in src/main.rs [FIX] CK_DEAD_SYMBOL | Remove unreachable private function in src/main.rs [FIX] CK_SLOP_DEBUG_LEFTOVER | Remove debug leftover at src/main.rs:7 [FIX] CK_DOC_DEAD_PATH | Rewrite broken link `../src/old/helper.rs` -> `../src/util/helper.rs` in docs/guide.md [REVERT] CK_DEAD_UNUSED_IMPORT | Remove unused import `Add` in src/math.rs:1 | verify `cargo check --workspace --all-targets` failed: error: could not compile `fixdemo` (bin "fixdemo") due to 1 previous error | warning: build failed, waiting for other jobs to finish... | error: could not compile `fixdemo` (bin "fixdemo" test) due to [REVERT] CK_DEAD_UNUSED_IMPORT | Remove unused import `Add` in src/math.rs:1 | verify `cargo check --workspace --all-targets` failed: error: could not compile `fixdemo` (bin "fixdemo" test) due to 1 previous error | warning: build failed, waiting for other jobs to finish... | error: could not compile `fixdemo` (bin "fixdemo") due to0 docs/guide.md | 2 +- src/main.rs | 6 ------ 2 files changed, 1 insertion(+), 7 deletions(-)The four good patches stay on disk, src/math.rs is back to its original text, and the build passes. The import patch appears twice because pass 1 applied some patches, so a second pass ran, planned the same import removal again and rolled it back again.
When every patch in the run is rolled back, the command exits 1:
codeknife fix --write --verify --aggressive --format human --no-cacheecho $?codeknife fix (write): applied 0 patch(es) across 0 file(s), 1 reverted (1 pass(es)) [REVERT] CK_DEAD_UNUSED_IMPORT | Remove unused import `Add` in src/math.rs:1 | verify `cargo check --workspace --all-targets` failed: error: could not compile `fixdemo` (bin "fixdemo") due to 1 previous error | warning: build failed, waiting for other jobs to finish... | error: could not compile `fixdemo` (bin "fixdemo" test) due to1Fixers
Section titled “Fixers”fix gathers patches from four planners in this order: comments, dead code, slop, then docs and dependencies. Each patch carries a rule ID, a description, a safety label (safe or aggressive) and a list of text edits.
Safe fixers always run. Aggressive fixers run only with --aggressive.
| Rule ID | Mode | What is matched | Edit made |
|---|---|---|---|
CK_CMT_STRIP |
safe | Comments the comment blade classifies as narration, banner, corpse or AI residue, with its --strip-pub-docs option off. One patch per file. |
Deletes each comment. A comment alone on its line is removed with its whole line; a trailing comment is removed with the spaces and tabs before it. |
CK_DEAD_SYMBOL |
safe | Private functions (not methods, not constants) in non-test files that are not reachable from any entry point, not reachable only from tests, not trait implementations and not referenced as a value. | Deletes the function plus the attached lines directly above it (doc comments, Rust attributes, decorators, and for Python also # comments, for Go also // comments), and up to two trailing newlines. |
CK_DEAD_UNUSED_IMPORT |
safe for Python, TypeScript, JavaScript; aggressive for Rust | A single-symbol import line whose symbol name does not appear as a whole word anywhere else in the file. | Deletes the whole import line. |
CK_DEAD_ONE_CALLER_WRAPPER |
aggressive | A private function whose body is only target(params) with the same parameters in the same order, with exactly one non-test call site, in the same file as both the call site and the target. |
Renames the call site to the target and deletes the wrapper. |
CK_SLOP_DEBUG_LEFTOVER |
safe | Rust dbg!(...); breakpoint(...) and pdb.set_trace(...) calls; TypeScript and JavaScript debugger statements. Test files are skipped. |
Deletes the whole line when the statement is alone on it. An inline Rust dbg!(expr) is replaced by expr. |
CK_GUARD_SUPPRESSION_EXPIRED |
safe | A suppression whose line contains until, optionally followed by : or =, then a YYYY-MM-DD date earlier than today (local time). Test files are skipped. |
Deletes the line, but only when the trimmed line starts with // or #, or starts with /* and ends with */. |
CK_SLOP_NO_TIMEOUT |
aggressive | A single-line Python requests.get(...) or requests.post(...) call with at least one argument, or a single-line TypeScript or JavaScript fetch(url) call with exactly one argument, whose text does not contain timeout, signal or AbortSignal. Test files are skipped. |
Python: appends , timeout=30 before the closing parenthesis. TS/JS: appends , { signal: AbortSignal.timeout(30000) }. |
CK_DOC_DEAD_PATH |
safe | A CK_DOC_DEAD_PATH finding from the docs blade whose target appears as (target) on the reported line, and whose file name matches exactly one file in the code model. |
Rewrites the link target to the relative path from the Markdown file to that file. |
CK_DEP_UNUSED |
aggressive | A CK_DEP_UNUSED finding from the deps blade in Cargo.toml or package.json. |
Cargo.toml: deletes the entry line, only inside a [dependencies] table, only when the key equals the package name and braces on the line balance. package.json: deletes the reported line if it starts with the quoted package name and, when that line had no trailing comma, removes the trailing comma from the line above. |
What each rule means as a finding is documented on the blade pages: Comments, Dead Code, Slop, Docs Drift and Dependencies. Expired suppressions are reported by the loosening guard (see Loosening Guard). The full rule list is in the Rule Catalogue.
| Rule ID | Severity of the matching blade finding | Changed by --strict |
|---|---|---|
CK_CMT_STRIP |
none: fix-only ID; the comment blade reports these comments under its own CK_CMT_* IDs |
no |
CK_DEAD_SYMBOL |
warning | no |
CK_DEAD_UNUSED_IMPORT |
none: fix-only ID, no blade emits it |
no |
CK_DEAD_ONE_CALLER_WRAPPER |
info | no |
CK_SLOP_DEBUG_LEFTOVER |
warning | no |
CK_GUARD_SUPPRESSION_EXPIRED |
error | no |
CK_SLOP_NO_TIMEOUT |
warning | no |
CK_DOC_DEAD_PATH |
warning | no |
CK_DEP_UNUSED |
warning | no |
--strict only tightens size and complexity thresholds, and no fixer reads those thresholds. The [comments] settings in codeknife.toml do change which comments the comment fixer classifies as strippable, and exclude patterns remove files from the model, so they are never fixed.
Fixer details and limits
Section titled “Fixer details and limits”- Unused imports. Only one-symbol imports on a single line are considered: Rust
use a::b::Name;(a line starting withpub useis never matched), Pythonimport name(no dots) andfrom mod import Name, TS/JSimport Name from "...",import { Name } from "..."andimport type .... Lines with{(Rust),*,,,((Python) orasare skipped. Go imports are never touched. The symbol check counts whole-word occurrences in the rest of the file, including comments and strings. - Imports that are always kept.
from __future__ import ...; any import in a test file; any import in a re-export barrel (__init__.py,index.ts,index.js); any import whose nearest non-blank line above starts with#[,@,# noqa,# type: ignore,// @ts-or/* eslint; Rustself,superandcrate; Rust names that end inExtor are one ofRead,Write,BufRead,Seek,Display,Debug,From,Into,TryFrom,TryInto,FromStr,Iterator,IntoIterator,ExactSizeIterator,Ord,PartialOrd,Eq,PartialEq,Hash,Serialize,Deserialize,Future,Stream,AsRef,AsMut,Deref,DerefMut,Borrow,Parser,Subcommand. Other trait imports, such asstd::ops::Addin the demo above, are not recognised, which is why Rust import removal is aggressive. - Dead functions. The function must also pass the dead-code blade’s entry-point check, which keeps functions marked with attributes such as
#[no_mangle],#[cfg(,#[wasm_bindgen],#[tokio::main]or decorators such as@app.and@pytest.fixture. See Dead Code. - Wrapper inlining. The wrapper must be a private function that is neither a test nor a trait implementation. The call site line must contain the wrapper name exactly once. The patch is dropped if the call site lies inside the wrapper.
- Debug leftovers. A
breakpoint(),pdb.set_trace()ordebuggerthat shares its line with other code (anything other than a trailing;) is left alone. An inlinedbg!()with no argument is left alone. - Expired suppressions next to strippable comments. The comment fixer runs first. If it classifies the
// until: ...comment itself as strippable, it removes that comment, the expired-suppression patch on the same line is skipped as a conflict, and the suppression stays in place without its expiry date. This happened with#[allow(clippy::too_many_lines)] // until: 2020-01-01 legacy: after--writethe line was#[allow(clippy::too_many_lines)]. - Markdown links. Only targets written as Markdown links,
[text](target), are rewritten. The replacement file is found by file name among the files in the code model, so if two files share the name, nothing is rewritten.
How patches are applied
Section titled “How patches are applied”Every pass builds the code model, gathers all patches and hands them to a transactional patch engine.
- Conflict selection. Patches are taken in planner order. A patch whose edits overlap any edit of an already selected patch in the same file is skipped and counted as a conflict. Two ranges overlap when each starts before the other ends; two zero-width insertions overlap only at the same position. Ranges that only touch end to start do not overlap. A skipped patch is planned again in the next pass.
- Original snapshot. CodeKnife reads every file that a selected patch touches and keeps its text in memory.
- Syntax guard. Each patch is checked in order, applied on top of the patches already accepted. For
.jsonfiles, the result must still parse as JSON if the original did. For source files in a supported language, the result is parsed with tree-sitter and rejected if the original had no parse errors and the new text has some. Rejected patches are reported as reverted with the reasonsyntax error detected in <file> after edit. Files in other formats are not checked. This guard runs in dry-run mode too. - Write. Edits for each file are sorted by start byte and applied from the end of the file backwards, so earlier offsets stay valid. An edit whose range falls outside the file is skipped silently.
- Verify (only with
--write --verify), described below.
The conflicts count appears only in --format agent output (as conflicts=) and in JSON (as skipped_conflicts).
Cascading passes
Section titled “Cascading passes”With --write, fix repeats the plan-and-apply cycle so that fixes unlocked by earlier fixes are picked up. Each pass rebuilds the code model from disk.
The loop stops when:
- a pass plans no patches (this pass is not counted in
passes), or - a pass applies no patches (all were conflicts, syntax rejections or rollbacks), or
- the pass limit is reached.
The limit is --max-passes, default 3, clamped to the range 1 to 5. A dry run always uses one pass.
In this demo, a banner comment sits inside an unused function. The comment patch and the dead-function patch overlap, so pass 1 applies only the comment patch:
fn old_path() -> i32 { // ======== Legacy ======== 41}
fn main() { println!("hi");}codeknife fix --format agent --no-cachecodeknife fix --write --format agent --no-cacheCODEKNIFE fix mode=dry-run passes=1 applied=1 reverted=0 conflicts=1 files=1 [FIX] CK_CMT_STRIP | Remove 1 strippable comment(s) in src/main.rsCODEKNIFE fix mode=write passes=2 applied=2 reverted=0 conflicts=1 files=1 [FIX] CK_CMT_STRIP | Remove 1 strippable comment(s) in src/main.rs [FIX] CK_DEAD_SYMBOL | Remove unreachable private function in src/main.rsWith --max-passes 1 the second pass does not run and the dead function stays. --max-passes 0 is treated as 1, and --max-passes 99 as 5.
Verification and rollback
Section titled “Verification and rollback”--verify takes effect only together with --write. In a dry run it is ignored. --verify-cmd takes effect only together with --verify; on its own it is ignored.
The verification command
Section titled “The verification command”With --verify-cmd "<command>", that command is used. Otherwise CodeKnife looks at the repository root and takes the first match:
| File at the root | Command |
|---|---|
Cargo.toml |
cargo check --workspace --all-targets |
tsconfig.json |
npx tsc --noEmit |
package.json |
npm test |
go.mod |
go test ./... |
pyproject.toml or pytest.ini |
pytest -q |
If none of these files exists and you gave no --verify-cmd, no verification runs and --verify has no effect.
The command runs as sh -c "<command>" with the repository root as the working directory. Exit status 0 is success. Anything else, or a failure to start the shell, is a failure. The failure reason stored on a reverted patch has this shape:
verify `<command>` failed: <detail><detail> is the last three lines of stderr (or of stdout when stderr is empty), joined with | and cut to 200 characters.
Bisect and rollback
Section titled “Bisect and rollback”The verification runs once per pass, after all syntax-valid patches of that pass are written:
- If the command passes, every patch is kept.
- If it fails, CodeKnife searches for the breaking patches by splitting the list in half recursively. A single patch is tested by writing it together with all patches kept so far and running the command; it is kept on success and reverted on failure. A group of patches is tested as a whole together with the kept patches, but only once at least one patch has been kept; if that passes, the whole group is kept, otherwise it is split again.
- Finally, every touched file is rewritten from its in-memory original plus the kept patches.
Rollback does not use git or backup files. Each test step rewrites every file touched in this pass from the snapshot taken in step 2 of How patches are applied. Files that no patch touched are never written.
A patch that fails verification in one pass is planned again in the next pass whenever the previous pass applied anything, so the same patch can appear more than once under [REVERT], as in the demo above. Each repeat costs extra runs of the verification command.
Native toolchains
Section titled “Native toolchains”--toolchains runs native formatters and fixers once, after all fix passes. It does nothing without --write. Each tool runs only when its trigger file exists and a probe command succeeds:
| Trigger | Probe | Commands run in the repository root |
|---|---|---|
Cargo.toml at the root |
cargo --version |
cargo fmt --all; with --aggressive also cargo clippy --fix --allow-dirty --allow-staged |
pyproject.toml at the root, or any .py file directly in the root (not in subdirectories) |
ruff --version |
ruff check --fix . then ruff format . |
package.json at the root |
npx biome --version |
npx biome check --write . |
go.mod at the root |
gofmt -h |
gofmt -w . |
A tool whose probe fails (including a tool that is not installed) is skipped without a note. For each command that runs, the report gets one note in one of these forms:
toolchain ok: `<command>`toolchain exited <code>: `<command>`toolchain error `<command>`: <error>codeknife fix --write --toolchains --aggressive --format agent --no-cacheCODEKNIFE fix mode=write passes=0 applied=0 reverted=0 conflicts=0 files=0 NOTE: toolchain ok: `cargo fmt --all` NOTE: toolchain ok: `cargo clippy --fix --allow-dirty --allow-staged`Toolchain changes are not verified, not rolled back, and not listed in files_modified (here cargo fmt rewrote src/main.rs, but files=0).
Scope: what fix touches and what it never touches
Section titled “Scope: what fix touches and what it never touches”fixalways works on the whole repository. The global--changedand--sinceflags are accepted but have no effect on it.- Files excluded by your configuration are not in the code model and are never edited.
- Test files are skipped by the dead-function, unused-import, debug-leftover, timeout and expired-suppression fixers. The comment fixer does process test files.
- Go imports, multi-symbol imports, aliased imports and wildcard imports are never removed.
- Public functions, methods, constants and trait implementations are never deleted.
- Which doc comments survive is decided by the comment classifier, the same way as
codeknife comments --stripwithout--strip-pub-docs. See Comments. - Dependencies are only removed from
Cargo.toml[dependencies]and frompackage.json, and only with--aggressive. - Without
--write, nothing on disk changes. Without--no-cache, the model build may still update the.codeknife/cache (see The .codeknife Directory).
| Flag | Default | Effect |
|---|---|---|
--write |
off | Apply patches. Without it the run is a one-pass dry run. |
--verify |
off | After writing, run the verification command and bisect-rollback breaking patches. Needs --write. |
--verify-cmd <CMD> |
auto-detected | Shell command used by --verify. Ignored without --verify. |
--aggressive |
off | Add wrapper inlining, timeout injection, unused dependency removal and Rust unused-import removal. With --toolchains, also runs cargo clippy --fix. |
--toolchains |
off | Run native formatters after the passes. Needs --write. |
--max-passes <N> |
3 |
Maximum passes with --write, clamped to 1 to 5. |
--format |
auto |
human and markdown print the human summary; agent prints the CODEKNIFE fix line; json and sarif both print the JSON report below. |
--no-cache |
off | Do not read or write the .codeknife/ cache when building the model. |
--path |
. |
Repository root. |
--strict |
off | Accepted; no effect on any fixer. |
--changed, --since |
off | Accepted; no effect on fix. |
--max-items |
none | Accepted; not used by fix output. |
Output
Section titled “Output”Human (--format human or markdown):
codeknife fix (<dry-run|write>): <planned|applied> N patch(es) across F file(s), R reverted (P pass(es)) [FIX] <rule> | <description> [REVERT] <rule> | <description> | <reason> NOTE: <note>Agent (--format agent):
CODEKNIFE fix mode=<dry-run|write> passes=P applied=N reverted=R conflicts=C files=Ffollowed by the same [FIX], [REVERT] and NOTE: lines.
JSON (--format json; --format sarif prints the same JSON, not SARIF) has the fields dry_run, passes, applied, reverted, skipped_conflicts, files_modified and notes. Each entry in applied has id, rule, description, safety ("safe" or "aggressive") and edits; each edit has file, start_byte, end_byte and replacement. Each entry in reverted has id, rule, description and reason. Trimmed from the rollback demo above (with --max-passes 1):
{ "dry_run": false, "passes": 1, "applied": [ { "id": "cmt:src/main.rs", "rule": "CK_CMT_STRIP", "description": "Remove 1 strippable comment(s) in src/main.rs", "safety": "safe", "edits": [... ], "reverted": [ { "id": "dead_imp:src/math.rs:1", "rule": "CK_DEAD_UNUSED_IMPORT", "description": "Remove unused import `Add` in src/math.rs:1", "reason": "verify `cargo check --workspace --all-targets` failed: error: could not compile `fixdemo` (bin \"fixdemo\" test) due to 1 previous error | warning: build failed, waiting for other jobs to finish... | error: could not compile `fixdemo` (bin \"fixdemo\") due to" } ], "skipped_conflicts": 0, "files_modified": [ "docs/guide.md", "src/main.rs" ], "notes": []}In dry-run mode, applied lists the planned patches and files_modified lists the files they would touch.
Exit codes
Section titled “Exit codes”| Code | When |
|---|---|
0 |
The run finished. This includes dry runs, runs with conflicts, and --verify runs where at least one patch was kept. |
1 |
--write and --verify were both set, no patch was kept, and at least one patch was reverted (by verification or by the syntax guard). |
2 |
An error, for example an unparseable codeknife.toml or a file that cannot be read or written. The message is printed to stderr as codeknife error: .... |
fix never exits 1 without --verify, even when the syntax guard reverts patches.
Also available via
Section titled “Also available via”- MCP tool
codeknife_fixwith the argumentspath,no_cache,write,verify,verify_cmd,aggressive,toolchainsandmax_passes(default3). It returns the JSON report. See MCP Tools. codeknife verify --fixruns the same engine with--writeand three passes before its quality check. See Verify Pipeline.codeknife comments --strip --writeandcodeknife dead --fix --writeapply single-blade fixes. See Comments and Dead Code.