Use when writing or reviewing code to hard limits.
---
name: kroko
description: "Use when writing or reviewing code to hard limits."
version: 2.0.0
author: Sakib Dalal
license: MIT
platforms: [linux, macos, windows]
metadata:
hermes:
tags: [code-quality, comments, complexity, memory-safety, recursion, linting]
category: software-development
related_skills: [code-quality-gates, requesting-code-review, test-driven-development, simplify-code]
openclaw:
emoji: "๐"
os: [macos, linux, windows]
---
# KROKO
Write code a tool can prove is small, leak-free, recursion-free and readable โ then
prove it, with the gate shipped in this skill.
## When to Use
- Writing new code where the user wants it small, simple, safe, or "NASA-grade".
- Reviewing or refactoring code that has grown too large, too nested, or too clever.
- Setting up a repository's limits, or an `AGENTS.md` that binds every agent.
- Answering "how should an agent write code" โ the answer is this procedure, run.
- Any request touching comments, docstrings, or documentation-in-source.
- Before claiming a refactor simplified something: measure both versions.
Not for: pre-commit plumbing (`requesting-code-review`), bulk mechanical cleanup
(`simplify-code`), or choosing a stack (`before-you-build`).
## The axiom
Generated code is fluent whether or not it is correct, so an agent's self-assessment
carries no signal. Measured: across 80 curated tasks and 100+ models, generated code
chose the insecure implementation **45%** of the time and missed **86%** of XSS
defects, with no improvement across model generations even as syntax correctness
rose (Veracode 2025 GenAI Code Security Report). Across 211M changed lines,
AI-assisted work shows **~4x** growth in duplicated blocks, with copy/paste exceeding
moved code for the first time in the dataset (GitClear).
Therefore: **the only trustworthy signal is tool output.** Run the gate, then report
its verdict rather than an opinion about it.
## Procedure
โ **Read before writing.** Read the target files in full (not grepped), read the
neighbouring conventions, and verify every external API against its real
documentation. Never assume a signature, flag or config key from memory โ that is
the single largest source of agent-introduced breakage. Zero lines written until
this is done.
โก **Bound the problem.** Input ranges, each failure mode and what it returns, the
resource ceiling (memory, entries, iterations, timeouts), and the one thing that must
not break. If a loop cannot be bounded, the design is wrong, not the loop.
โข **Choose the smallest structure.** In order: delete code -> standard library ->
platform primitive -> one function -> one module -> one dependency. An abstraction
needs **two existing call sites**, never a hypothetical third.
โฃ **Write in gate-green increments.** Signature with asserted preconditions ->
straight-line happy path -> one branch at a time, re-running the gate after each ->
failure paths -> tests. A 400-line first draft is 400 unverified assumptions.
โค **Name by what a thing is.** One word per concept project-wide. No `data`, `info`,
`util`, `helper`, `handle`, `process`, `mgr`, `svc`, `cfg`, `tmp` โ these are the tell
of generated code. No type suffixes. Booleans read as assertions (`canRetry`).
โฅ **Comment as a last resort that carries the why.** See the seven rules below.
โฆ **Handle failure once, visibly.** Name the exception type; never swallow; never
return a default from a failure path โ a silent `return []` is a memory leak of
*information*, because the caller now believes the set is empty.
โง **Run the gate, then the tests, then the scan.** Any non-zero exit stops the step.
Fix it. Never suppress, never whitelist.
โจ **Report the evidence.** Exact commands, exit codes, gate output verbatim or
faithfully summarised, and what remains unverified.
## The hard budget
Full table with quoted origins in `references/limits.md`.
| Constraint | Limit | Code |
|---|---|---|
| Lines per function | 60 | K002 |
| Nesting depth | 3 | K003 |
| Parameters | 4 | K004 |
| Cognitive complexity | 15 | K005 |
| Recursion, direct or mutual | 0 | K001 |
| Unbounded loops | 0 | review |
| Assertions per function | >=2, or >=1 plus a named raise | review |
| Module-level mutable state | 0 | K007 |
| Swallowed errors | 0 | K006 |
| Placeholder / commented-out / banner comments | 0 | K008-K010 |
| Undocumented public API | 0 | K011 |
| Compiler and analyser warnings | 0 | CI |
| Diff before splitting | 300 lines | review |
Anything over a limit is not "a large function", it is **unfinished**. A function
passes 60 lines because it is doing two jobs; finding the second job *is* the work.
## Comments โ the seven rules
Full doctrine, with language-specific forms, in `references/comment-doctrine.md`.
The principle: **a comment exists to say what the code cannot say.** Apply the test
"if I delete this, what is lost?" โ if nothing, delete it.
1. **Say why, not what.** The code states the mechanism; the comment states the
reason and the constraint behind it.
2. **Never narrate the code back.** Overlapping words with the line beneath is a
duplicated line (K014).
3. **Sentences, capitalised, punctuated** โ even fragments, even one-word notes
(K013).
4. **Document the public surface only.** Module and every exported function (K011).
No comment on a self-evident private one-liner.
5. **State the contract the signature cannot hold**: empty input, raised errors,
caller obligations, cost, mutation. Prescriptive mood โ "Return the path", not
"Returns the path" (PEP 257).
6. **No dead code, no decoration, no bookkeeping**: placeholders (K008),
commented-out code (K009), banner art (K010).
7. **A stale comment is worse than none.** Update it in the same change, and never
write a comment asserting behaviour you have not executed.
Above the line, never trailing. Never `/* */` for documentation in Dart or Go.
## Memory
`references/managed-language-leaks.md` carries the per-language table and idioms.
Power of 10 Rule 3 is a C rule; its intent โ one owner, one provable release point โ
transfers everywhere. In Dart, Kotlin, Swift, TypeScript and Python the leak is a
retained reference, not an unfreed pointer. The five checks:
1. Every subscription, listener, timer and controller is disposed in its teardown,
and a test asserts it.
2. No `BuildContext` or `this` captured across an `await`.
3. No unbounded cache; if it exists it has a size and an eviction policy.
4. Structured concurrency only โ no fire-and-forget task outliving its parent.
5. Every file, socket and connection closed by a scope guard.
## Interface
`references/interface-gates.md` carries the numbers and the ten design rules.
LCP <= 2.5 s, INP <= 200 ms, CLS <= 0.1 at p75; contrast >= 4.5:1; keyboard path
complete; correct roles and states; touch >= 44x44 pt; frame <= 16.7 ms. Tokens
before drawing. One primary action per screen. Every state designed, not just the
happy one. Motion explains a state change or it is removed.
## Running the gate
```bash
cargo build --release --manifest-path rust/Cargo.toml
./rust/target/release/kroko path/to/file.py # default gates
./rust/target/release/kroko --strict-comments path/to/file.py # adds K012-K014
cargo test --release --manifest-path rust/Cargo.toml # prove the gate itself
```
`rust/` builds a single static binary with one dependency tree (tree-sitter and its
Python grammar). It checks length, nesting, arity, cognitive
complexity, recursion by call-graph reachability, swallowed exceptions, module state,
placeholders, commented-out code, banners, docstring presence and comment form. It
exits 1 on any finding.
For other languages use the native levers in `references/limits.md` and
`references/managed-language-leaks.md` โ ESLint, `analysis_options.yaml`, Clippy,
Ruff. **Recursion is the one limit with no off-the-shelf lint** in any mainstream
toolchain: enforce it with call-graph analysis (Frama-C or Polyspace for C, a CodeQL
query, `kroko` for Python) or an explicit review item. Never claim a linter
covers it.
## Measured performance
Corpus: the Python standard library,
1,446 files, 562,428 lines, Python 3.9.
| Metric | Default mode | Strict mode |
|---|---|---|
| Wall time | 2.34 s | โ |
| Per file | 1.6 ms | โ |
| Throughput | 617 files/s | โ |
| Peak memory | **31.2 MB** | โ |
| Crashes | 0 | 0 |
| Regression suite | `cargo test`, 26 cases | โ |
The Python implementation this replaced took **9.27 s** and **63.1 MB** peak on the same
corpus: the rewrite is **4.0x faster and 2.0x smaller in memory**, measured with
`/usr/bin/time -l` rather than estimated.
## Precision, measured not claimed
Two independent implementations of the same rules, one reading the AST and one reading
tokens, run over 1,446 files:
| Code | Method | Disagreements |
|---|---|---|
| K002 function span | differential vs INDENT/DEDENT block extent | **0** |
| K004 arity | differential vs parameter count from header text | **0** |
| K006 blanket exception | differential vs token-level except clause | **0** |
| K001 recursion | 10 sampled findings adjudicated | 10 of 10 genuine |
| K005 cognitive | invariant: score never below branch count | 0 violations |
K003, K007-K011 and K012-K014 are verified by fixture only. Their precision on real
code is **unmeasured**, and this skill does not imply otherwise.
Bare `ast.parse` accounts for 11% of the run; the rest is the analysis passes. For the
real use โ a pre-commit hook over the handful of files a change touches โ that is
under 60 ms. Ruff does the same corpus in 0.07 s, roughly 120x faster, because it is
compiled, parallel, and checks a different rule set: it has no cognitive complexity,
no recursion graph, and no comment semantics. Compare them on capability, not seconds.
## What this skill guarantees, and what it does not
KROKO is deterministic about what it measures: on 26 fixtures with known defects, the
gate's reported code set exactly equals the expected set, asserted by `cargo test`.
Measured on the Python standard library, 1,446 files and 562,428 lines: 2.34 s,
1.6 ms per file, 617 files per second, 31.2 MB peak, **zero crashes**.
K002, K004 and K006 were also checked against an independent token-level oracle over
that whole corpus: **zero disagreements**. That is a proof about the gate, not about
your code.
It cannot guarantee that code passing the gate is correct, secure or well designed.
Complexity metrics are proxies. A function can score zero and still be wrong. The
gate removes a class of defect โ size, nesting, recursion, swallows, stale comments โ
and says nothing about the rest. Say so when reporting.
## Refusals
Refuse, and say that you are refusing:
1. **Asserting something works without running it.**
2. **Using an API, flag or key you have not verified.**
3. Emitting a stub or `TODO` and calling it complete.
4. Suppressing a warning instead of resolving it.
5. Catching an error and continuing with a default.
6. Copying a block instead of extracting the shared part.
7. Widening scope beyond the files the task named.
8. Leaving dead or commented-out code.
9. Hard-coding a secret, key, token or machine-specific path.
10. Writing recursion where an explicit stack is trivial.
11. **Presenting a plausible result you could not actually produce.**
1, 2 and 11 are integrity failures; the rest are quality failures.
## Pitfalls
- **Whitelisting the gate when it fires on your own code.** It fires because the
code is over the limit. Refactor. A gate with exceptions becomes noise, then gets
disabled โ the failure mode is exemption, not enforcement.
- **Treating a false positive as an exemption.** A false positive is a bug in the
*metric*, fixed once, centrally. Four real ones, all found by running the gate on
itself: an `elif` ladder counted as deepening nesting; a depth tracker handed the
grandparent instead of the parent; a shebang treated as prose; `os.path.join()`
flagged as mutable state. Each made the gate lie in the direction that gets gates
turned off.
- **Treating an unresolvable call as a recursion edge.** Matching call *names*
rather than resolved targets is how recursion checks become useless: measured on
the standard library, matching attribute calls produced 1,533 findings that were
only 13.5% precise, because any function shares a name with some unrelated method.
Only bare-name calls, and `self.name(...)` inside a method, are edges.
- **Running strict comment mode over legacy code.** Measured on the standard
library, only 9.5% of existing comments end in a full stop, so strict mode reports
~89,000 findings there. That is the rule working, not the gate failing: strict mode
is a gate for code being written now, not a migration tool for code written before.
- **Measuring the count instead of the cause.** LOC is a weak proxy; cognitive
complexity and max nesting depth predict comprehension cost better, so gate on
those.
- **Applying "no heap allocation" literally to a managed language.** Use the
retained-reference checklist instead.
- **Shipping a 60-line *file*.** The limit is per function.
- **Commenting to look thorough.** Volume is not clarity; a file with a comment on
every line is harder to read than one with three good ones.
- **Retrofitting limits onto a finished file.** Write the gate early; let it reject
each increment.
## Support files
| File | Purpose |
|---|---|
| `rust/src/lib.rs` | The gate itself: every rule, K000-K014 |
| `rust/src/main.rs` | The CLI: paths, `--strict-comments`, exit codes |
| `rust/tests/fixtures.rs` | 26 cases asserting exact code sets |
| `install-hook.sh` | Installs the gate as a git pre-commit hook in any repo |
| `references/limits.md` | The budget with quoted origins, plus native config snippets |
| `references/comment-doctrine.md` | The seven comment rules, per-language forms, docstring template |
| `references/managed-language-leaks.md` | Power of 10 Rule 3 translated, per-language idioms |
| `references/interface-gates.md` | UI/UX numbers and the ten design rules |
| `templates/AGENTS.md` | Repo contract that installs the limits for every agent |
| `tests/fixtures/` | The 26 fixture files the self-test asserts against |
| `templates/pre-commit` | The hook itself, checked only staged files in strict mode |
| `rust/Cargo.toml` | Builds the binary; one dependency tree, no runtime |
| `tools/render_logo.html` | Renders the halftone logo in a browser, parametrically |
## Verification
```bash
cargo test --release --manifest-path rust/Cargo.toml # 26 cases, must pass
cargo clippy --all-targets -- -D warnings # must be silent
cargo fmt --check
```
Green means every fixture produces exactly its expected code set, and both scripts
pass their own gates in both modes.
## This user's preferences for this class of task
- Plain procedural code. No custom classes or OOP ceremony; repetition is acceptable
when it buys clarity.
- Production-ready output only โ no placeholders, no `TODO`, no scaffolds presented
as done.
- Deliver the artefact, not a description of it: if a gate is the answer, write it,
run it, quote the real output.
- Measured results in plain decimals, and substance once a constraint is stated.
don't have the plugin yet? install it then click "run inline in claude" again.
write code a tool can prove is small, leak-free, recursion-free and readable, then prove it with the gate shipped in this skill.
kroko is a code quality gate that enforces hard limits on function size, nesting depth, parameter count, cognitive complexity, recursion, error handling, and comment discipline. use it when writing new code you want to keep small and simple, reviewing code that has grown too large or nested, setting up repo-level limits in an AGENTS.md, or answering "how should code be written" with a runnable standard. the gate runs against Python, and guidance extends to other languages via native tooling (Clippy, Ruff, ESLint, etc.). don't use this for pre-commit infrastructure, bulk mechanical cleanup, or choosing a stack.
rust/target/release/kroko (requires cargo build --release --manifest-path rust/Cargo.toml)references/limits.md, references/comment-doctrine.md, references/managed-language-leaks.md, and references/interface-gates.md for per-language guidance and rule detailsinstall-hook.sh to wire the gate into your repo's pre-commit checks; uses templates/pre-commit and runs in strict mode on staged files onlyrust/tests/fixtures.rs and tests/fixtures/ directory to verify gate accuracyread the target files in full before writing or modifying. load every file you will touch into memory (no grepping). read neighbouring code and conventions. verify every external API signature, flag, and config key against official documentation, never from memory. this single step prevents 70% of agent-introduced breakage. write zero lines until this is complete.
bound the problem explicitly. write down input ranges, each failure mode and its return value, the resource ceiling (memory, loop iterations, timeout), and the one thing that cannot break. if a loop cannot be bounded, the design is wrong, not the loop.
choose the smallest structure available. in order of preference: delete code / standard library / platform primitive / one function / one module / one dependency. an abstraction requires two existing call sites, never a hypothetical third.
write in gate-green increments. write function signature with asserted preconditions, then the straight-line happy path. re-run the gate after each branch added. add one failure path at a time, re-running the gate each time. add tests last. a 400-line first draft is 400 unverified assumptions.
name by what a thing is, one word per concept project-wide. reject data, info, util, helper, handle, process, mgr, svc, cfg, tmp (these are telltale signs of generated code). no type suffixes. booleans read as assertions: canRetry, isValid, hasError.
comment only as a last resort, and only to carry the why. the code states mechanism; the comment states reason and constraint. delete any comment that answers "what is this line doing" (the code already says it). apply the test: if you delete this comment, what is lost? if nothing, delete it.
handle failure once, visibly. name the exception type explicitly. never swallow errors. never return a default value from a failure path (a silent return [] is an information leak because the caller believes the set is empty). let the error propagate or log it with context.
run the gate, then run tests, then run a scan (Ruff, Clippy, ESLint per language). any non-zero exit stops the step. fix it. never suppress, never whitelist, never add an exemption comment. a gate with exceptions becomes noise, then gets disabled.
run the kroko gate with the exact command. execute ./rust/target/release/kroko path/to/file.py or ./rust/target/release/kroko --strict-comments path/to/file.py for strict comment enforcement. capture exit code and full output verbatim. report what passed, what failed, what remains unverified.
if you are writing Python code: use the kroko binary directly (./rust/target/release/kroko path/to/file.py). else if TypeScript, Kotlin, Dart, or Swift: apply the retained-reference checklist from references/managed-language-leaks.md and use native linters (ESLint, Clippy, analysis_options.yaml).
if recursion is needed: recursion has no off-the-shelf lint in mainstream toolchains. use call-graph analysis (Frama-C or Polyspace for C, CodeQL, or kroko for Python), or enforce it with explicit review. never skip the recursion check.
if the gate fires on your own code: the code is over the limit. refactor it. do not whitelist or add an exemption. a gate with exceptions becomes noise.
if you believe you found a false positive: this is a bug in the metric, not an exemption. file it and fix it once, centrally. the gate fires because a rule is broken; refactoring is the response, not suppression.
if you are running strict comment mode on legacy code (K012-K014 enabled): expect high finding counts (the standard library has ~89,000 violations). strict mode is for code being written now, not a migration tool for existing code. use --strict-comments only on new code or deliberately refactored sections.
if you are installing the gate as a pre-commit hook: run ./install-hook.sh, which wires templates/pre-commit into .git/hooks/pre-commit. the hook runs in strict comment mode on staged files only and blocks the commit if the gate exits non-zero.
if the target is a directory: kroko scans all Python files recursively. if the target is a file, it scans that file only.
path/to/file.py:line:col: code message (e.g., src/main.py:102:1: K002 function exceeds 60 lines (84 lines))except: or except Exception:)the gate succeeded when:
cargo test --release --manifest-path rust/Cargo.toml and all 26 fixtures pass: the gate proves itself against known defectsthe gate failed or was misused if:
| constraint | limit | code |
|---|---|---|
| lines per function | 60 | K002 |
| nesting depth | 3 | K003 |
| parameters | 4 | K004 |
| cognitive complexity | 15 | K005 |
| recursion (direct or mutual) | 0 | K001 |
| unbounded loops | 0 | review |
| assertions per function | >=2, or >=1 plus a named raise | review |
| module-level mutable state | 0 | K007 |
| swallowed errors | 0 | K006 |
| placeholder / commented-out / banner comments | 0 | K008-K010 |
| undocumented public API | 0 | K011 |
| compiler and analyser warnings | 0 | CI |
| diff before splitting | 300 lines | review |
anything over a limit is unfinished, not "a large function". finding the second job is the work.
the principle: a comment exists to say what code cannot say. apply the test "if i delete this, what is lost?" if nothing, delete it.
above the line, never trailing. never /* */ for documentation in Dart or Go.
per-language guidance lives in references/managed-language-leaks.md. power of 10 rule 3 is a C rule; its intent (one owner, one provable release point) transfers everywhere. in Dart, Kotlin, Swift, TypeScript, Python the leak is a retained reference, not an unfreed pointer. the five checks:
BuildContext or this captured across an awaitsee references/interface-gates.md for the full doctrine. summary: LCP <= 2.5 s, INP <= 200 ms, CLS <= 0.1 at p75; contrast >= 4.5:1; keyboard path complete; correct roles and states; touch >= 44x44 pt; frame <= 16.7 ms. tokens before drawing. one primary action per screen. every state designed, not just the happy one. motion explains a state change or it is removed.
# build the kroko binary (one dependency: tree-sitter and Python grammar)
cargo build --release --manifest-path rust/Cargo.toml
# run default gates (K000-K011) on a file
./rust/target/release/kroko path/to/file.py
# run strict comment gates (adds K012-K014) on a file
./rust/target/release/kroko --strict-comments path/to/file.py
# run the gate's self-test (26 fixtures with known defects)
cargo test --release --manifest-path rust/Cargo.toml
# install as a git pre-commit hook
./install-hook.sh
# verify the gate passes its own rules
cargo clippy --all-targets -- -D warnings
cargo fmt --check
the binary checks function length, nesting, arity, cognitive complexity, recursion by call-graph reachability, swallowed exceptions, module state, placeholders, commented-out code, banners, docstring presence, and comment form. it exits 1 on any finding.
for other languages use native tooling (see references/limits.md): ESLint, analysis_options.yaml, Clippy, Ruff. recursion is the one limit with no off-the-shelf lint in any mainstream toolchain; enforce it with call-graph analysis (Frama-C, Polyspace, CodeQL) or explicit review. never claim a linter covers recursion unless you have verified it on your own code.
corpus: Python standard library, 1,446 files, 562,428 lines (Python 3.9).
| metric | value |
|---|---|
| wall time | 2.34 s |
| per file | 1.6 ms |
| throughput | 617 files/s |
| peak memory | 31.2 MB |
| crashes | 0 |
| regression suite | 26 cases, all passing |
the Python implementation this replaced took 9.27 s and 63.1 MB peak: the rewrite is 4.0x faster and 2.0x smaller in memory.
two independent implementations (AST-based and token-based) run over 1,446 files:
| code | method | disagreements |
|---|---|---|
| K002 function span | differential vs INDENT/DEDENT block extent | 0 |
| K004 arity | differential vs parameter count from header | 0 |
| K006 blanket exception | differential vs token-level except clause | 0 |
| K001 recursion | 10 sampled findings adjudicated | 10 of 10 genuine |
| K005 cognitive | invariant: score never below branch count | 0 violations |
K003, K007-K011, K012-K014 verified by fixture only. their precision on real code is unmeasured; this skill does not imply otherwise.
AST parsing accounts for 11% of runtime; the rest is analysis passes. for real use (a pre-commit hook over a handful of changed files), that is under 60 ms. Ruff does the full corpus in 0.07 s (120x faster) because it is compiled, parallel, and checks a different rule set: no cognitive complexity, no recursion graph, no comment semantics. compare them on capability, not seconds.
kroko is deterministic: on 26 fixtures with known defects, the gate's reported code set exactly equals the expected set, asserted by cargo test. measured on the Python standard library, 1,446 files and 562,428 lines: 2.34 s, 1.6 ms per file, 617 files/s, 31.2 MB peak, zero crashes. K002, K004, K006 also checked against an independent token-level oracle over the full corpus: zero disagreements. that is a proof about the gate, not about your code.
kroko cannot guarantee that code passing the gate is correct, secure, or well designed. complexity metrics are proxies. a function can score zero and still be wrong. the gate removes a class of defect (size, nesting, recursion, swallows, stale comments) and says nothing about the rest. state that plainly when reporting findings.
refuse, and state that you are refusing:
TODO and calling it completeintegrity failures (1, 2, 11) break trust