Skip to content

5. Slop

The slop blade looks for code patterns that compile and often pass tests but hide failures or cause trouble in production: empty catch blocks, as any casts, unwrap(), blocking calls inside async functions, queries inside loops, HTTP calls without timeouts, todo!() stubs, debug leftovers and similar. It reads the tree-sitter syntax tree of each file, plus a few model-wide facts such as call graphs and .env.example.

Use it as a quick review pass over AI-written or hurried code. It has no flags of its own and no config table.

This demo repository triggers every rule the blade has:

use std::sync::Mutex;
pub async fn load_users(m: &Mutex<i32>, ids: &[i32]) {
std::thread::sleep(std::time::Duration::from_millis(5));
let guard = m.lock().unwrap();
refresh().await;
for id in ids {
sqlx::query("SELECT * FROM users WHERE id = ?").bind(id);
tokio::spawn(async move { work(*id).await });
}
let _ = reqwest::get("https://example.com").await;
}
pub fn parse(raw: &str) -> i32 {
match raw.parse::<i32>() {
Ok(v) => v,
Err(_) => {}
}
let n = raw.parse::<i32>().expect("number");
dbg!(n);
n
}
pub fn raw_read(p: *const i32) -> i32 {
unsafe { *p }
}
pub fn later() -> i32 {
todo!()
}
async fn refresh() {}
async fn work(_id: i32) {}
Terminal window
codeknife slop --format human
warning[CK_SLOP_BROAD_SWALLOW]: broad exception catch returns fallback default without propagating or handling error
--> py/svc.py:30-31
= fix: Narrow the caught exception type and propagate unexpected failures loudly.
warning[CK_SLOP_DEBUG_LEFTOVER]: leftover debug macro/breakpoint in production code
--> py/svc.py:16
= fix: Remove debugging calls before committing.
warning[CK_SLOP_NO_TIMEOUT]: outbound HTTP request made without an explicit timeout
--> py/svc.py:15
= fix: Use a client configured with explicit connect/request timeouts or `AbortSignal.timeout(...)`.
error[CK_SLOP_BLOCKING_IN_ASYNC]: blocking call inside async function `py.svc.poll` stalls the async executor
--> py/svc.py:9 (py.svc.poll)
= fix: Replace with async I/O / async sleep or offload via `spawn_blocking`.
warning[CK_SLOP_PLACEHOLDER]: placeholder string literal left in production code
--> py/svc.py:5
= fix: Replace placeholder text with real configuration or fixture data.
warning[CK_SLOP_N_PLUS_ONE]: potential N+1 I/O `cursor.execute` executed inside loop
--> py/svc.py:14
= fix: Batch the query or prefetch records once before entering the loop.
info[CK_SLOP_ERROR_CONTEXT_LOSS]: `raise` inside `except` block omits `from err` / `from None` chaining
--> py/svc.py:24
= fix: Use `raise NewError(...) from err` to preserve the original traceback context.
error[CK_SLOP_STUB_HANDLER]: unfinished `todo!()` / `unimplemented!()` stub in production code
--> src/lib.rs:29
= fix: Implement the branch or return an explicit typed error.
error[CK_SLOP_TYPE_ESCAPE]: `unsafe` block missing `// SAFETY:` invariant justification
--> src/lib.rs:25
= fix: Document why invariants hold in a `// SAFETY: ...` comment above the `unsafe` block.
warning[CK_SLOP_DEBUG_LEFTOVER]: leftover debug macro/breakpoint in production code
--> src/lib.rs:20
= fix: Remove debugging calls before committing.
warning[CK_SLOP_TYPE_ESCAPE]: panic-prone `expect` in production code
--> src/lib.rs:19
= fix: Propagate `Result`/`Option` cleanly with `?` or `.ok_or(...)` instead of panicking.
warning[CK_SLOP_EMPTY_CATCH]: empty `Err(_) => {}` match arm silently swallows errors
--> src/lib.rs:17
= fix: Handle or propagate errors instead of discarding `Err(_)`.
warning[CK_SLOP_NO_TIMEOUT]: outbound HTTP request made without an explicit timeout
--> src/lib.rs:11
= fix: Use a client configured with explicit connect/request timeouts or `AbortSignal.timeout(...)`.
warning[CK_SLOP_UNBOUNDED_SPAWN]: unbounded concurrent task spawn inside loop
--> src/lib.rs:9
= fix: Bound concurrency with a semaphore, worker pool, or `JoinSet`.
warning[CK_SLOP_TYPE_ESCAPE]: panic-prone `unwrap` in production code
--> src/lib.rs:5
= fix: Propagate `Result`/`Option` cleanly with `?` or `.ok_or(...)` instead of panicking.
error[CK_SLOP_BLOCKING_IN_ASYNC]: blocking call inside async function `slopdemo::load_users` stalls the async executor
--> src/lib.rs:4 (slopdemo::load_users)
= fix: Replace with async I/O / async sleep or offload via `spawn_blocking`.
warning[CK_SLOP_LOCK_ACROSS_AWAIT]: synchronous lock guard `guard` held across `.await` point
--> src/lib.rs:5-6
= fix: Drop the lock guard before `.await`, narrow its scope, or use an async-aware lock.
warning[CK_SLOP_N_PLUS_ONE]: potential N+1 I/O `sqlx::query("SELECT * FROM users WHERE id = ?").bind` executed inside loop
--> src/lib.rs:8
= fix: Batch the query or prefetch records once before entering the loop.
warning[CK_SLOP_N_PLUS_ONE]: potential N+1 I/O `sqlx::query` executed inside loop
--> src/lib.rs:8
= fix: Batch the query or prefetch records once before entering the loop.
warning[CK_SLOP_NO_TIMEOUT]: outbound HTTP request made without an explicit timeout
--> svc/main.go:14
= fix: Use a client configured with explicit connect/request timeouts or `AbortSignal.timeout(...)`.
warning[CK_SLOP_GO_DEFER_IN_LOOP]: `defer` executed inside Go `for` loop leaks resources until function returns
--> svc/main.go:11
= fix: Extract the loop body into a helper function or close resources before the next iteration.
warning[CK_SLOP_IGNORED_ERROR]: Go error return explicitly discarded with `_ = ...` on fallible call
--> svc/main.go:12
= fix: Handle or explicitly propagate the returned error value.
warning[CK_SLOP_BROAD_SWALLOW]: broad exception catch returns fallback default without propagating or handling error
--> web/api.ts:17-19
= fix: Narrow the caught exception type and propagate unexpected failures loudly.
error[CK_SLOP_EMPTY_CATCH]: empty catch/except block silently swallows errors
--> web/api.ts:14
= fix: Propagate the error, log with context, or explicitly handle known recoverable variants.
warning[CK_SLOP_TYPE_ESCAPE]: non-null assertion `!` bypasses TypeScript null checks
--> web/api.ts:11
= fix: Narrow the type explicitly or fail with a clear domain error.
warning[CK_SLOP_TYPE_ESCAPE]: TypeScript type-safety escape (`body as unknown as { name: string }`)
--> web/api.ts:10
= fix: Parse/validate external data at the boundary instead of casting through `any` or `unknown`.
warning[CK_SLOP_TYPE_ESCAPE]: TypeScript type-safety escape (`body as any`)
--> web/api.ts:9
= fix: Parse/validate external data at the boundary instead of casting through `any` or `unknown`.
warning[CK_SLOP_UNBOUNDED_SPAWN]: unbounded concurrent task spawn inside loop
--> web/api.ts:7
= fix: Bound concurrency with a semaphore, worker pool, or `JoinSet`.
warning[CK_SLOP_NO_TIMEOUT]: outbound HTTP request made without an explicit timeout
--> web/api.ts:7
= fix: Use a client configured with explicit connect/request timeouts or `AbortSignal.timeout(...)`.
warning[CK_SLOP_NO_TIMEOUT]: outbound HTTP request made without an explicit timeout
--> web/api.ts:5
= fix: Use a client configured with explicit connect/request timeouts or `AbortSignal.timeout(...)`.
error[CK_SLOP_BLOCKING_IN_ASYNC]: blocking call inside async function `web/api/sync` stalls the async executor
--> web/api.ts:4 (web/api/sync)
= fix: Replace with async I/O / async sleep or offload via `spawn_blocking`.
warning[CK_SLOP_FLOATING_PROMISE]: unawaited promise `fetch(...)` inside async function
--> web/api.ts:5
= fix: `await` the returned promise, return it, or attach `.catch(...)`.
warning[CK_SLOP_N_PLUS_ONE]: potential N+1 I/O `fetch` executed inside loop
--> web/api.ts:7
= fix: Batch the query or prefetch records once before entering the loop.
warning[CK_SLOP_RESOURCE_LEAK]: `useEffect` registers listener/interval without cleanup return
--> web/widget.tsx:4-6
= fix: Return a cleanup closure calling `removeEventListener` or `clearInterval`.
info[CK_SLOP_GUARD_SCATTER]: `normalize` re-validates parameter(s) [name] already guarded by 2 callers
--> py/svc.py:45-48 (py.svc.normalize)
= fix: Parse and validate once at the system boundary (`boundary-discipline`), then trust internal types.
info[CK_SLOP_UNWIRED_ENV]: env var `DATABASE_URL` read in code is missing from `.env.example`
--> py/svc.py:42 (DATABASE_URL)
= fix: Document the required/optional env variable in `.env.example`.
codeknife slop: FAIL (5 files, 6 errors, 27 warnings, 3 info, 4ms)

Note what is missing: the Python quiet function (except ValueError: pass) produced no finding. See the CK_SLOP_EMPTY_CATCH limits below.

  • Every source file that is not a test file. Test files are skipped entirely. See Language Support for how each language detects test files.
  • Inside other files, the line ranges of test functions (items the model marks as tests) are skipped.
  • With --changed, only files in the changed set are scanned. See Paths, Excludes & Changed Scope.

Most checks match on the syntax node kind plus the start of the node’s source text. They do not resolve imports or types. A call written through an alias (for example use std::fs; fs::read(...)) does not match a pattern written as std::fs::.

Rule ID Severity Languages Fixer
CK_SLOP_EMPTY_CATCH error (catch/except), warning (Rust Err(_) arm) TS, JS, Python, Rust no
CK_SLOP_BROAD_SWALLOW warning TS, JS, Python no
CK_SLOP_TYPE_ESCAPE warning, or error for undocumented unsafe TS, JS, Rust no
CK_SLOP_NO_TIMEOUT warning any (text match) yes, aggressive
CK_SLOP_BLOCKING_IN_ASYNC error Rust, TS, JS, Python no
CK_SLOP_UNBOUNDED_SPAWN warning any (text match) no
CK_SLOP_RESOURCE_LEAK warning TS, JS no
CK_SLOP_STUB_HANDLER error Rust no
CK_SLOP_DEBUG_LEFTOVER warning Rust, and any language for breakpoint( / pdb.set_trace( yes, safe
CK_SLOP_PLACEHOLDER warning any no
CK_SLOP_GUARD_SCATTER info any no
CK_SLOP_UNWIRED_ENV info Rust, TS, JS, Python, Go no
CK_SLOP_N_PLUS_ONE warning any (text match) no
CK_SLOP_FLOATING_PROMISE warning TS, JS no
CK_SLOP_GO_DEFER_IN_LOOP warning Go no
CK_SLOP_IGNORED_ERROR warning Go no
CK_SLOP_ERROR_CONTEXT_LOSS info Python no
CK_SLOP_LOCK_ACROSS_AWAIT warning Rust no

--strict changes only CK_SLOP_PLACEHOLDER (two extra trigger words). No rule has a numeric threshold or config key. The full catalogue across blades is in the Rule Catalogue.

  • Error, impact 75. A catch_clause (TypeScript, JavaScript) or except_clause (Python) whose body, after trimming {, } and : from both ends and whitespace, is empty, pass or ....
  • Warning, impact 60. A Rust match arm whose text starts with Err(_) and ends with {}.

Limits:

  • For Python, the blade looks for a body field on the except_clause node and falls back to the whole clause text. The whole text starts with except, so it is never empty or pass. In testing, except ValueError: pass and except Exception: pass were not reported.
  • Rust arms such as Err(e) => {} or Err(_) => () do not match.

Warning, impact 60. A non-empty catch or except clause where:

  • the first line contains Exception or starts with catch, and
  • the body contains none of throw, raise, return Err, and
  • the body contains one of return null, return None, return [], return {}, return false.

Every TypeScript or JavaScript catch starts with catch, so any catch that returns one of those fallbacks matches. In Python only clauses that name Exception on their first line match; except ValueError: return None does not.

One rule ID for four patterns:

Pattern Language Severity Impact
as_expression whose text ends with as any or contains as unknown as TS, JS warning 55
non_null_expression (postfix !) TS, JS warning 45
Call whose function text ends with .unwrap or .expect Rust warning 55
unsafe block without a SAFETY: marker Rust error 75

The unsafe check passes if any line of the block contains SAFETY: (any case), or if any line in the run of comment lines directly above it does. A comment line here is one whose trimmed text starts with //, /* or *. A multi-line // SAFETY: comment followed by more comment lines counts.

unwrap_or, unwrap_or_default and similar do not match, because the function text must end exactly in .unwrap or .expect.

Warning, impact 60. A call node whose text starts with:

  • reqwest::get(, reqwest::blocking::get(, http.Get( or http.Post( (always flagged), or
  • requests.get( or requests.post( and does not contain timeout=, or
  • fetch( and contains neither signal nor AbortSignal.

Calls made through a client object (for example client.get(...) or axios.get(...)) are not checked.

Error, impact 75. A call inside the line range of an async function (not a test) whose text starts with std::fs::, std::thread::sleep(, fs.readFileSync(, fs.writeFileSync( or time.sleep(. The finding names the async function.

The function is found by line range, so a synchronous closure nested inside an async function still counts. Go has no async functions, so this rule never fires for Go.

Warning, impact 55. A call inside a loop whose text starts with tokio::spawn( or Promise.all(. Loops are nodes of kind for_expression, for_statement, for_in_statement, while_expression, while_statement or loop_expression.

Warning, impact 60. TypeScript or JavaScript only. A call whose text starts with useEffect(, contains addEventListener( or setInterval(, and contains neither removeEventListener( nor clearInterval(. This is a text check over the whole useEffect(...) call; cleanup done in a separate helper function is not seen.

Error, impact 75. A Rust macro call whose text starts with todo! or unimplemented!. Stubs in other languages (for example raise NotImplementedError) are not checked.

Warning, impact 45. A Rust dbg! macro call, or any call node whose text starts with breakpoint( or pdb.set_trace(. JavaScript debugger statements and console.log calls are not reported by this blade.

Warning, impact 50. A string literal node (string_literal, string, interpreted_string_literal or raw_string_literal) whose text, with quotes stripped, trimmed and lowercased:

  • equals changeme, lorem ipsum or replace_me, or
  • starts with your-api-key, or
  • with --strict (or strictness = "strict"), equals placeholder or todo.

The literal is skipped when the source text of its parent, grandparent or great-grandparent node contains ==, .contains( or .starts_with(. This keeps detector code such as v == "changeme" quiet.

Info, impact 35. A non-test function that guards one of its parameters, and is called by at least 2 functions that also guard a parameter. The finding sits on the callee and suggests validating once at the boundary.

A function guards a parameter when a top-level if statement in its body contains return, throw or raise , and the first line of that if names the parameter as a whole word together with one of None, null, undefined, nil, empty, == 0, <= 0, !<, or ! directly before the parameter name. Callers are taken from the call graph. See Import Resolution for how calls are resolved.

Info, impact 25. Runs only when .env.example exists in the repository root. CodeKnife reads every line that is not empty and does not start with #, and takes the trimmed text before the first = as a declared name.

It then compares that list with environment variable reads found in non-test source files:

  • process.env.NAME, where NAME is at least 2 characters of uppercase letters, digits and _
  • env::var("NAME") and std::env::var("NAME")
  • os.Getenv("NAME")
  • os.getenv("NAME") and os.environ.get("NAME")

Each missing name is reported once, at its first read. os.environ["NAME"] is not recognised. A line such as export NAME=1 declares the name export NAME, which never matches.

Warning, impact 65. A call inside a loop (the loop kinds above plus do_statement) whose callee, the text of the call’s function part, looks like database or HTTP I/O.

Database callees:

  • starts with sqlx::query, ends with .findOne or .findUnique, or is exactly cursor.execute, or
  • ends with .query or .execute, and either the receiver’s last segment is one of db conn connection pool tx trx txn transaction sql stmt statement cursor cur session knex prisma drizzle sqlite pg postgres mysql client repo repository store query_builder sqlx database engine, or the call text contains SELECT , INSERT , UPDATE or DELETE (any case).

HTTP callees (exact match): fetch, axios.get, axios.post, axios.put, axios.delete, axios.request, reqwest::get, requests.get, requests.post, http.Get, http.Do.

So cmd.execute(item) inside a loop is not flagged, but db.execute(item) is.

Warning, impact 60. TypeScript or JavaScript. Inside an async function, an expression statement that is a bare call (not awaited, not returned) whose callee is fetch or starts with axios., prisma. or fs.promises., and whose text contains neither .then( nor .catch(.

A function counts as async when it is a function declaration, method, arrow function or function expression whose source starts with async . A non-async function nested inside an async one resets the scope.

Warning, impact 70. Go. A defer statement anywhere inside a for loop.

Warning, impact 65. Go. An = assignment whose left side is _ or ends with , _, and whose right side contains .Write(, .Close(, .Flush(, .Exec(, .Commit(, .Sync(, .Remove(, .Encode(, .Marshal(, .Unmarshal( or .Copy(, or starts with one of those names followed by (.

Only assignment_statement nodes are checked. In testing, n, _ := f.Write(b) was not reported while _, _ = f.Write(b) and _ = f.Close() were.

Info, impact 40. Python. A raise statement with an argument, inside an except clause (not inside a nested function or class), whose text does not contain from. A bare raise is fine.

Warning, impact 75. Rust. Inside an async fn or async block (closures reset the scope), CodeKnife walks the statements of each block in order:

  • A let statement whose value contains .lock(), .read() or .write() and does not end in .await starts a guard, named after the let pattern.
  • A later statement containing drop(name) ends that guard.
  • A later statement that contains an .await (not inside a closure or async block) while any guard is live produces one finding per live guard, spanning from the let line to the .await line.

Only statements in the same block are compared. The check is textual, so any method called read() or write() with no arguments starts a guard.

codeknife slop has no flags of its own. The global flags --path, --format, --strict, --changed, --since, --no-cache and --max-items apply; see the CLI Reference.

There is no [slop] table in codeknife.toml. The only settings that affect this blade are:

Setting Effect
--strict or strictness = "strict" Adds placeholder and todo to CK_SLOP_PLACEHOLDER.
[blades] slop = false Skips this blade in codeknife check. codeknife slop still runs.

With --strict:

warning[CK_SLOP_PLACEHOLDER]: placeholder string literal left in production code
--> py/mod.py:2
= fix: Replace placeholder text with real configuration or fixture data.
warning[CK_SLOP_PLACEHOLDER]: placeholder string literal left in production code
--> py/mod.py:1
= fix: Replace placeholder text with real configuration or fixture data.
codeknife slop: FAIL (2 files, 0 errors, 2 warnings, 0 info, 2ms)

Line 1 of that file is LABEL = "todo" and line 2 is TOKEN = "your-api-key-here". Without --strict, only line 2 is reported.

codeknife fix has fixers for two slop rules:

  • CK_SLOP_DEBUG_LEFTOVER (safe, always on). Removes a Rust dbg!(...) that is a statement on its own line, or replaces an inline dbg!(x) with x. Removes a breakpoint() or pdb.set_trace() call that is alone on its line. It also removes JavaScript and TypeScript debugger statements, which this blade does not report.
  • CK_SLOP_NO_TIMEOUT (aggressive, needs --aggressive). Appends , timeout=30 to a single-line Python requests.get(...) or requests.post(...) with at least one argument, and , { signal: AbortSignal.timeout(30000) } to a single-line fetch(...) with exactly one argument. Calls that span lines or already mention timeout, signal or AbortSignal are skipped. The Rust and Go forms have no fixer.

On the demo repository:

Terminal window
codeknife fix --aggressive --format human
codeknife fix (dry-run): planned 5 patch(es) across 3 file(s), 0 reverted (1 pass(es))
[FIX] CK_SLOP_DEBUG_LEFTOVER | Remove debug leftover at py/svc.py:16
[FIX] CK_SLOP_NO_TIMEOUT | Inject explicit HTTP timeout at py/svc.py:15
[FIX] CK_SLOP_DEBUG_LEFTOVER | Remove debug leftover at src/lib.rs:20
[FIX] CK_SLOP_NO_TIMEOUT | Inject explicit HTTP timeout at web/api.ts:7
[FIX] CK_SLOP_NO_TIMEOUT | Inject explicit HTTP timeout at web/api.ts:5

No other slop rule has a fixer.

Code Meaning
0 No error or warning findings remain after the baseline is applied.
1 At least one error or warning finding. The demo above exits 1.
2 CodeKnife failed, for example an invalid codeknife.toml.

Findings in codeknife.baseline are filtered out before the exit code is decided. See Ratchet Baseline and Output Formats & Exit Codes.

  • codeknife check runs this blade as part of the static suite.
  • The MCP tool codeknife_check runs the same suite, and codeknife_fix runs the two slop fixers. See MCP Tools.