Journeys
Journey: Clean Code = Lower AI Bill
Messy code costs tokens: every agent that re-reads a tangled function pays for the confusion, turn after turn. The Code Health Engine scores cognitive complexity, naming and coupling into one navigability number, surfaces the hotspots right inside reads, and gates edits that make complexity worse — so cleaner code measurably lowers your AI bill.
You arepaying to re-read tangled, complex code
ctx_qualitylean-ctx health--gatecognitive complexitynavigabilitygain navigability
You ship with an AI agent every day, and your provider bill keeps climbing. A big, quiet driver of that bill is code your agent has to re-read to understand. A tangled 400-line function with cryptic names gets loaded, parsed and reasoned about on every turn that touches it — and you pay for that confusion in tokens, again and again. This journey is the loop that makes code health a measurable token-cost lever, not a vibe.
Why messy code is an AI-bill problem
Clean code is cheaper to read for a model for the same reason it is cheaper for a human: less to hold in working memory. The SonarSource analysis that inspired this engine puts it plainly — high-complexity code forces the model to load more context, take more turns, and re-read more often. LeanCTX already compresses how code reaches the model; the Code Health Engine attacks the other half: the intrinsic cost of the code itself.
It does this with the same tree-sitter AST that powers the rest of code intelligence (26 languages), so there is no extra parser and no separate index — the health score is computed once per index build and fanned out everywhere.
The one number — navigability
The engine rolls three signals into a single navigability score (0–100):
- Cognitive complexity (Sonar’s S3776): how hard a function is to follow — nesting, breaks in linear flow, boolean tangles. Not cyclomatic count.
- Naming quality: cryptic, single-letter or meaningless identifiers that make the agent re-read surrounding code to infer intent.
- Module coupling: afferent/efferent coupling and instability — how entangled a file is with the rest of the repo.
Alongside the score it estimates a quality tax in USD: the recurring token cost of the hotspots, priced with the same model-pricing table the gain report uses. That turns “this file is messy” into “this file is costing you ~$X.”
See it where you already look — read annotations
You do not have to run anything. When the agent reads code in signatures or
map mode, over-threshold functions are annotated inline:
fn process_request(...) · cc=23 (over)
fn validate(...) · cc=8
The annotation is sparse (only hotspots), deterministic, and costs a few tokens —
so the agent sees the complexity hotspot exactly when it is about to work on
it. Prefer it off? One switch: [code_health] annotate_reads = false.
At session start, the top hotspots are surfaced once in a compact block, so a fresh agent knows where the expensive code lives before it starts.
Stop complexity from growing — the edit-gate
The cheapest hotspot is the one you never create. Both ctx_edit and ctx_patch
run the edit through a complexity delta check before writing:
⚠ code-health: process_request cognitive complexity 18 → 27 (+9, over threshold 15)
The gate has three modes ([code_health] gate):
warn(default) — annotate the regression, let the edit through.block— refuse an edit that takes a function from clean to over-threshold.off— disable entirely.
Because many agents edit with the host’s native tools too, the same notice is
emitted from the PostToolUse hook for native Edit/MultiEdit, so the signal
follows the agent regardless of which edit path it takes.
The on-demand report — ctx_quality
When you (or the agent) want the full picture, ctx_quality is the MCP tool:
ctx_quality action=report # whole-project navigability + hotspots + tax
ctx_quality action=file path=src/auth.rs # one file, function by function
ctx_quality action=delta # health change vs the last computed baseline
Add format=json for a machine-readable payload (CI, dashboards, scorecards).
It is read-only and in the standard profile, so it never costs you a write
permission prompt.
In the terminal & in CI — lean-ctx health
The same engine is a first-class CLI command:
lean-ctx health # navigability score + top hotspots + quality tax
lean-ctx health src/ # scope to a path
lean-ctx health --json # machine-readable
lean-ctx health --gate # non-zero exit if the project is over its floor
--gate makes “don’t let the codebase get less navigable” a CI check, the same
way doctor overhead --gate guards the context budget — a hard, scriptable line
in the sand.
It shows up in your savings story — gain navigability
Code health is not a side dashboard; it feeds the headline. The gain score gains a fifth component, navigability, so a cleaner codebase visibly lifts the one number you watch:
Score: 84/100 (compression 71, cost 90, quality 76, consistency 80, navigability 84)
When no health data exists yet, the score falls back to its original weighting — you are never penalised for a signal the engine has not computed.
How to read it back
- Day to day: let read-annotations and the session-start block do the work; act on a hotspot when you are already in the file.
- Before a refactor:
ctx_quality action=fileto see which functions carry the cost, andaction=deltaafterwards to prove you brought it down. - In CI:
lean-ctx health --gateto stop regressions at the door. - For the bill: watch the quality-tax USD and the gain
navigabilitycomponent trend down as you clean up.
Where to go next
- Code Health concept — the deep dive: how each signal is computed and how it fans out across the stores.
- Analytics, Insights & Reporting — where the gain score and quality tax live.
- Code Intelligence — the graph and impact tools the health engine shares its AST with.
- Customization & Governance —
the
[code_health]knobs and how to enforce them.