Skip to content

How Metrics Are Computed

Every function and method in the code model carries a set of metrics that the language adapters compute while parsing. The Architecture, Tests & CRAP, Mutation Testing and Churn blades compare these numbers against thresholds. Read this page when a finding’s number surprises you, or when you want to predict how a refactor will change it.

This Rust function is in src/lib.rs of a crate named m1:

pub fn classify(x: i32, a: bool, b: bool) -> i32 {
if x > 10 {
for i in 0..x {
if i % 2 == 0 && a || b {
return i;
}
}
} else if x < 0 {
return -1;
} else {
return 0;
}
match x {
1 => 10,
_ => 20,
}
}

Computed by hand with the rules below:

Construct Depth when reached Cyclomatic Cognitive Nesting after
start 0 1 0 0
if x > 10 0 +1 +1 1
for i in 0..x 1 +1 +2 2
if i % 2 == 0 && a || b 2 +1 +3 3
|| (new operator sequence) +1 +1
&& (different operator from its parent) +1 +1
else if x < 0 +1 +1 stays 1
else +1
match x 0 +1 1
two match arms +2
total 9 11 max 3

The line count is 17 (lines 3 to 19) and there are 3 parameters, 2 of them bool. Confirm with dossier:

Terminal window
codeknife dossier --no-cache --target classify --format json
{
"mode": "target",
...
"target": {
"query": "classify",
"resolved_kind": "symbol",
"file": "src/lib.rs",
"symbol": "m1::classify",
"start_line": 3,
"end_line": 19,
"metrics_summary": "lines=17 cc=9 cog=11 nesting=3 params=3",
...
"rules": [
"CK_ARCH_BOOL_TRAP"
],
...

dossier prints lines, cc (cyclomatic), cog (cognitive), nesting and params. The boolean parameter count is not printed, but the CK_ARCH_BOOL_TRAP finding shows it reached the limit of 2.

Metrics are computed on the function’s body node, not the whole declaration:

Language Item Node measured
Rust fn the body block
TypeScript and JavaScript function, method, arrow or function expression bound to a variable the body (a block, or the single expression of an expression-bodied arrow)
TypeScript and JavaScript it(...) / test(...) test the whole callback function
Python def the body block
Go func, method the body block

Items without a body (structs, classes, enums, traits, interfaces, fields, constants) keep the defaults: cyclomatic 1, cognitive 0, nesting 0, no parameters.

Because only the body is measured, a multi-line arrow function bound to a variable does not count as nesting for itself, but a multi-line arrow inside it does.

lines is end_line - start_line + 1 of the declaration node. It counts blank lines and comments inside the function. It does not include Rust attributes, Python decorators or doc comments above the declaration, because those are separate syntax nodes. For a variable-bound arrow function the node is the arrow function itself, starting at the line where the arrow’s parameters begin.

cc starts at 1 and adds 1 for each of these syntax nodes inside the body:

Node Languages
if (if_expression, if_statement), including if let all
Python elif (elif_clause) Python
for (for_expression, for_statement) all; for TypeScript and JavaScript this is only the C-style for (;;)
while (while_expression, while_statement), including while let all
loop (loop_expression) Rust
catch / except (catch_clause, except_clause) TypeScript, JavaScript, Python
ternary / conditional expression (ternary_expression, conditional_expression) TypeScript, JavaScript, Python
each match arm or case (match_arm, case_clause, switch_case) Rust match arms (including _), Python case clauses (including case _), TypeScript and JavaScript case labels (not default)
each &&, ||, and or or binary operator all

Not counted: for...in / for...of and do...while in TypeScript and JavaScript, Go switch and select cases, try, else, ?, ??, ?., ! and not, early return, break and continue.

cog follows the general shape of Sonar’s cognitive complexity: structures add 1 plus the current nesting depth, else branches add a flat 1, and each run of the same boolean operator adds 1. The exact rules in crates/codeknife-lang/src/complexity.rs are:

Construct Adds Nesting for its children
if that is not an else if head 1 + depth depth + 1
for, while, loop (same node kinds as cyclomatic) 1 + depth depth + 1
catch / except clause 1 + depth depth + 1
ternary / conditional expression 1 + depth unchanged
Python elif 1 + depth - 1 (see below) unchanged
switch: Rust match, TypeScript and JavaScript switch, Go select 1 + depth depth + 1
else if head (Rust, TypeScript, JavaScript) 1 unchanged
else without an if (Rust, TypeScript, JavaScript, and Python else on if, for, while and try) 1 unchanged
boolean operator &&, ||, and, or whose direct parent is not a binary expression with the same operator 1 unchanged
multi-line closure: Rust closure, TypeScript and JavaScript arrow function, Python lambda spanning more than one line 0 depth + 1

So a && b && c adds 1, a && b || c adds 2, and a && (b && c) adds 2 because the parenthesised expression sits between the two operators.

Nothing else adds to cognitive complexity. In particular recursion, labelled break or continue, goto, try blocks, do...while, TypeScript for...of / for...in, Go function literals, TypeScript function expressions, nested function declarations and Rust ? add nothing and do not increase nesting.

These come straight from the grammar node kinds the scorer recognises. Each was confirmed with dossier on a small function (results in the table after the list).

  • Go else and else if. The Go grammar has no else clause node. A plain else adds nothing. An else if is scored as an ordinary if nested one level deeper, so it adds 1 + depth + 1 and raises the nesting depth.
  • Go switch. switch and type switches add nothing to cognitive complexity and nothing to cyclomatic complexity, however many cases they have. Only select counts, as a switch.
  • Python match. The match statement itself adds nothing to cognitive complexity and does not raise nesting. Each case adds 1 to cyclomatic complexity.
  • Python elif. In the Python grammar, elif is a child of its if, which has already raised the depth by 1. The scorer subtracts that 1 back, so elif adds 1 + the depth of its if. At the top level that is 1. Inside a nested if it is more than 1, unlike Rust or TypeScript else if, which always adds 1.
  • TypeScript and JavaScript loops. Only the C-style for (;;) and while count. for...of, for...in and do...while add nothing.
  • Closures. A closure on one line adds no nesting. The same closure split across lines raises the nesting depth for everything inside it.
Function (language) Source summary Observed
ElseIf (Go) if / else if / else, each returning cc=3 cog=3 nesting=2
Switchy (Go) switch x with case 1, case 2, default cc=1 cog=0 nesting=0
Loops (Go) for range containing if x > 0 && ok, then a func literal containing an if cc=5 cog=5 nesting=2
elifs (Python) if / elif / else at top level cc=3 cog=3 nesting=1
nested_elif (Python) if y: containing if / elif cc=4 cog=5 nesting=2
matcher (Python) match x: with case 1: and case _: cc=3 cog=0 nesting=0
lam (Python) a lambda split over two lines containing x if x > 0 else -x cc=2 cog=2 nesting=1
loops (TypeScript) for...of, for (;;), do...while, while (t > 50 || flag), return t ?? 0 cc=4 cog=3 nesting=1
sw (TypeScript) switch with two case and a default cc=3 cog=1 nesting=1
chain (TypeScript) if / else if / else returning a && b && c cc=5 cog=4 nesting=1
drain (Rust) while let containing loop containing if; then a multi-line closure with if / else; then ? cc=5 cog=9 nesting=3
inline (Rust) a one-line closure containing if / else cc=2 cog=2 nesting=1

Each row is the metrics_summary from codeknife dossier --no-cache --target <name> --format json on the demo file.

nesting (max_nesting in the model) is the deepest nesting level reached anywhere in the body. The level starts at 0 and rises by 1 inside each construct marked “depth + 1” in the cognitive table: if (except else if heads and Python elif), for, while, loop, catch / except, the switch kinds, and multi-line closures. A function with one if has nesting 1. Plain blocks, else, try, do...while, for...of and Go function literals do not raise it.

params is the number of parameters extracted from the declaration. bool_param_count is how many of them have a boolean type annotation. The rules differ per language:

Language What is counted Boolean when the type is
Rust each parameter node. self, &self and &mut self are not counted. exactly bool
TypeScript and JavaScript each child of the parameter list, including destructured and rest parameters exactly boolean (so boolean | undefined is not)
Python each child of the parameter list except one written exactly self or cls exactly bool (so Optional[bool] is not)
Go each name in each parameter group (a, b, c int counts 3); an unnamed parameter counts once exactly bool

Untyped parameters are never boolean, even with a boolean default (flag = false). Go receivers are not parameters.

Each function also stores ast_node_count: the number of tree-sitter nodes in the body, named and anonymous. No blade reads it.

Each file has total_lines (the number of lines, at least 1) and code_lines: non-empty lines that, after trimming, do not start with # in Python or // in every other language. Lines inside /* ... */ blocks and Python docstrings count as code. dossier --target <file> prints both, as lines= and code=.

held_in_mind (default 7) is not a per-function metric. It is an architecture threshold on how many of a module’s working functions are used from other modules. The adapters do not compute it; see Architecture.

The adapters also store data that other blades read. None of it is a threshold metric.

Data Definition Read by
Accessed fields names reached through the receiver: self.x (Rust, Python), this.x (TypeScript, JavaScript), r.x for receiver r (Go), excluding method calls LCOM4 cohesion in Architecture
Mutating method Rust: takes mut self. TypeScript and JavaScript: assigns to or increments this.. Python: assigns to or augments self.. Go: pointer receiver that assigns to or increments through the receiver. field-leak checks in Architecture
Guarded parameters parameters checked by a top-level if in the body whose text contains return, throw or raise , and whose first line contains the parameter name plus one of None, null, undefined, nil, empty, == 0, <= 0, !<, or !name CK_SLOP_GUARD_SCATTER in Slop
Wrapper a body with exactly one statement that returns a receiver field (field accessor, mutable when it starts with &mut ) or a single call (forwarder) Dead Code and the call graph
Normalized tokens the body’s leaf tokens with literals replaced by $LIT, parameter and local variable names by $ID, and member names by $FIELD; comments dropped Clones, Reuse Oracle
Statement blocks for a body with n statements (comments excluded) and n at least 4: every run of min(n, 6) consecutive statements that spans at least 5 lines and at least 20 normalized tokens Clones
Body hash SHA-256 of the body text with whitespace collapsed the mutation result cache in Mutation Testing

This layer emits no findings and no rule IDs of its own. These are the blades that compare its numbers against configuration. The Rule Catalogue lists every rule.

Metric Config key ([thresholds]) Default --strict Rule Fires when
lines max_fn_lines 60 capped at 40 CK_ARCH_LONG_FN lines is greater than the limit
nesting max_nesting 4 capped at 3 CK_ARCH_DEEP_NESTING nesting is greater than the limit
cog max_cognitive_complexity 15 capped at 10 CK_ARCH_COGNITIVE_COMPLEXITY cog is greater than the limit
params max_params 5 capped at 4 CK_ARCH_TOO_MANY_PARAMS params is greater than the limit
boolean params max_bool_params 2 unchanged CK_ARCH_BOOL_TRAP the count is at least the limit

Architecture skips test items for these checks. Cyclomatic complexity feeds the CRAP score in Tests & CRAP and mutation ranking in Mutation Testing. Churn hotspots use the larger of cognitive and cyclomatic complexity (Churn). See codeknife.toml for the configuration file.

Which functions are tests is decided per language. Language Support lists the exact rules: Rust test attributes, TypeScript and JavaScript it / test calls, Python test_ functions in test files or Test classes, and Go Test functions in _test.go files.

For each recognised test CodeKnife walks every node of the test body and fills these counters, which Tests & CRAP turns into CK_TEST_* findings.

Assertions. For each call-like node (a call, a Rust macro invocation or a Python assert statement), CodeKnife takes the first line of its text and checks it against the language’s patterns:

Language Counts as an assertion when the trimmed first line
Rust starts with assert!, assert_, debug_assert, panic!(, unreachable!(, matches!(, check!( or assert_matches!, or contains .assert(), .assert_, .success() or .failure()
TypeScript and JavaScript starts with assert(, or contains expect(, expect.assertions, t.is(, t.deepEqual(, t.throws(, t.true(, t.false(, fail(, expectTypeOf(, expectType<, assert., assertEquals(, assertStrictEquals(, assertThrows(, .assertEqual or assertType
Python starts with assert , or contains self.assert, self.fail, assertRaises, assertWarns, assertLogs, .assert_, pytest.raises, pytest.warns, pytest.deprecated_call, pytest.fail, warnings.catch_warnings or with raises(
Go contains t.Error, t.Fatal, t.Fail, assert. or require., or calls a function whose name starts with assert, check, verify or expect (case-insensitive) with t as its first argument

Additional assertions: a Rust #[should_panic] attribute adds 1; a Rust macro_rules! inside the test whose text contains assert or panic! adds 1; a TypeScript or JavaScript comment containing @ts-expect-error adds 1; a TypeScript type alias containing Expect<, AssertTrue< or AssertEqual< adds 1.

Weak assertions. An assertion line containing .is_ok(), .is_some(), .toBeDefined(), .toBeTruthy(), is not None, NotNil( or NoError(.

Mock assertions. An assertion line containing toHaveBeenCalled or assert_called.

Implementation-coupled assertions. An assertion line containing toHaveBeenCalledTimes, assert_called_once, toThrow(" or .to_string(),.

Mock setups. Any call line containing vi.mock(, jest.mock(, vi.spyOn(, jest.spyOn(, MagicMock(, @patch(, monkeypatch., mocker.patch or gomock..

Control-flow branches. Each if, for, while or try node in the test. A Go if without an else whose text contains t.Error, t.Fatal, t.Fail, b.Error, b.Fatal, assert. or require. is a guard assertion and is not counted.

Flake smells, recorded once per line and message:

Message Triggered by a call line containing
wall-clock sleep inside unit test thread::sleep, setTimeout(, time.sleep(, time.Sleep(
uninjected wall-clock time dependency in test SystemTime::now, Date.now(, time.time(, time.Now(
unseeded randomness in test Math.random(, rand::random

Example. These tests produced the findings below with codeknife tests --no-cache --format json (rule, file, line and message shown):

tests/test_a.py
def test_weak():
x = 1
assert x is not None
def test_none():
x = 1
# helpers.py
def test_looks_like_a_test():
x = 1
class TestThing:
def test_in_class(self):
y = 2
CK_TEST_ZERO_ASSERT helpers.py 7 test `test_in_class` executes with zero assertions
CK_TEST_WEAK_ASSERT tests/test_a.py 2 test `test_weak` has only weak existence/truthiness assertions (1 weak / 1 total)
CK_TEST_ZERO_ASSERT tests/test_a.py 7 test `test_none` executes with zero assertions

test_looks_like_a_test is not a test because helpers.py is not a test file and the function is not in a Test class.

codeknife mutate asks the adapter for candidate mutation sites. Every adapter uses the same collector. It visits every syntax node whose start line falls inside a non-test Function or Method item of the file and applies these operators:

Operator Applies to Replacement
BoundaryFlip binary operators <, <=, >, >= < to <=, <= to <, > to >=, >= to >
BoolFlip binary operators ==, !=, ===, !==, &&, ||, and, or == and != swap, === and !== swap, && and || swap, and and or swap
BoolFlip boolean literals true, false, True, False the opposite literal
ArithmeticFlip binary operators +, -, *, / in Rust, TypeScript, JavaScript and Go + and - swap, * and / swap. A + whose expression text contains a quote or backtick is skipped (string concatenation).
ReturnDefault return statements and expressions, except Go see below
DeleteGuard an if whose text has at most 4 lines, contains return or return;, and does not contain else Python: pass. Others: /* mutant: guard removed */ {}

Binary operators are matched on the first anonymous child of binary_expression, Python boolean_operator and Python comparison_operator nodes. Python arithmetic such as score * 2 is a binary_operator node, so Python never gets ArithmeticFlip sites. %, bitwise operators, unary ! / not, is / is not, in, ?? and compound assignments are never mutated.

ReturnDefault replacements:

Language Return text contains true, false, True or False Otherwise
Rust return false; return Default::default();
TypeScript return false; return null as any;
JavaScript return false; return null;
Python return False return None
Go no mutation no mutation

A return is skipped when its trimmed text is exactly return, return;, return (), return () ;, return None, return None;, return false, return false; or return False, or when it contains Default::default(). The true / false check is a plain substring test on the whole return text, so a return of a variable such as is_true_value also gets the boolean replacement. Rust tail expressions without return are not return sites.

Example: the same grade(score, bonus) function written in each language, with an early-return guard if score < 0 { return false }, an arithmetic line (score + 10 in Rust and Go, score - 1 in TypeScript, score * 2 in Python) and a final total >= 50 && bonus == true (Python: and bonus is not None; TypeScript: && bonus === true, returned explicitly). In the Go demo:

Terminal window
codeknife mutate --scan --no-cache --format human
...
note: scan: 8 covered candidate mutation sites (0 uncovered skipped)
codeknife mutate: PASS (1 files, 0 errors, 0 warnings, 8 info, 2ms)

The sites found inside grade per language, in line order (from --format json in each demo):

Go TypeScript Python Rust
delete guard delete guard delete guard delete guard
< to <= < to <= < to <= < to <=
false to true false to true False to True false to true (twice)
+ to - - to + replace return value + to -
&& to || replace return value and to or && to ||
== to != && to || >= to > == to !=
true to false === to !== true to false (twice)
>= to > true to false >= to >
>= to >

Mutation Testing covers how sites are selected, run and reported.

Metric computation has no flags, no configuration and no exit codes. Functions in files that cannot be read or parsed are simply absent from the model. Thresholds and their exit codes belong to the blades listed above.

dossier --target (MCP tool codeknife_dossier) prints the metrics for one function or file. mutate --scan lists mutation sites. See Dossier and MCP Tools.