๐Ÿค Code standards: what is binary, what is judgement, and the ratchet

Status: reference.

The two size rules below are enforced by tests/test_code_standards_scan.py; everything under The rest of the checklist is a review standard with no detector, and Build order lists the detectors that run today.

This is the code counterpart of WRITING-STANDARDS.md: that one is the standard the genre skills write prose against, this one is the standard an agent changes this repository's own code against.

Written for someone changing code in chitragupta/, scripts/ or assets/webapp/, or deciding whether a proposed rule is worth enforcing. It assumes DEVELOPER-AGENTS.md for the process around a change (test policy, the local check suite, commit/PR/release conventions) and states only what the code itself must look like.

Not covered here: prose standards for drafts (WRITING-STANDARDS.md), module boundaries and which layer owns what (ARCHITECTURE.md, and DEVELOPER-AGENTS.md's "Module boundaries"), and the drafting loop this document borrows its shape from (AUTO-IMPROVEMENT.md).

๐Ÿงญ Table of contents

๐Ÿ’ก Where these rules come from

The source standard is the widely-circulated clean-code summary of Robert C. Martin's Clean Code (Prentice Hall, 2008); INSPIRATION.md records the provenance. Its nine sections are the checklist this document is written against, and The rest of the checklist maps every rule in it to one of four fates: enforced, already here under another name, review standard, or not applicable with the reason.

Two things follow from adopting a checklist rather than writing one.

Nothing is restated. Where a rule already existed in this project under a different name, the table points at it instead of repeating it. A rule stated twice is a rule that will eventually be stated two different ways.

Nothing is adopted unread. Two of the nine sections, the comment rules and the Boy Scout Rule, land differently here than a quick reading suggests, and both get their own section below rather than a row in a table. A checklist applied without noticing where it collides with the codebase is how a standard produces worse code than none.

๐Ÿ”‘ The rule that decides everything

R3: "An unattended item's check is binary. No continuous score is ever the thing being optimised."

(AUTO-IMPROVEMENT.md owns the wording.)

That rule was written for drafts. It applies here unchanged, and it is why this document is split the way it is. "No function exceeds 25 statements" is binary and is enforced. "This code is clean" is a score.

A score invites the same Goodhart failure HOUSE-STYLE.md describes for readability indices. A maintainability metric is minimised by splitting functions past the point where the logic survives the break, and every one of those edits passes its own re-check.

The result is a small number of binary rules with a detector and a register, and a larger number of judgement rules with neither. The judgement rules are not weaker; they are what review is for. They are not things a machine may drive to zero.

The loop stays open. This document borrows AUTO-IMPROVEMENT.md's shape, not its automation. Nothing here proposes a code-fixing loop; R11 ("its only trigger is a person asking") is the reason, and it applies with more force to code than to prose.

๐Ÿ’ฌ The comment rules: record only what binds

The clean-code comment rules are eight, and they split cleanly in two:

Banned Required
2. Don't be redundant 6. Use as explanation of intent
3. Don't add obvious noise 7. Use as clarification of code
4. Don't use closing brace comments 8. Use as warning of consequences
5. Don't comment out code. Just remove

Rule 1, "always try to explain yourself in code", governs both: reach for a better name or an explanatory variable before reaching for a comment.

Stated for this repository, the required side is narrow. A comment or docstring records only a critical detail: what a code fragment, method or class must keep doing, and why a later change would break it. That means a constraint, a security property, an ordering, or a version pin that is load-bearing, written in a line or two. Rule 8, the warning of consequences, is the core of it.

Write new code at this density from the start. Long comments already in the repository are trimmed when a change touches them or in a dedicated PR, as #1259 did for tests/, pyproject.toml and three modules, never as a drive-by in an unrelated diff. DEVELOPER-AGENTS.md carries the same rule as a working checklist.

This is still SOUL.md's "Judgment is logged, not just made": the judgment that still binds is logged beside the code, and the rest is logged in git and plans/, where it does not have to be read again on every edit.

๐Ÿ’ก Why statements, not lines

"Functions should be small" is the rule; a line count is the usual proxy. Here that proxy mostly measures comment discipline:

Scope Functions over 25 physical lines Functions over 25 statements
chitragupta/ (383 functions) 128 26
tests/ (1926 functions) 63 1

Measured at 5.7.1. Unlike the register sizes below, these four numbers are deliberately dated rather than pinned by a test: the physical-line column moves whenever any function gains a comment, so pinning it would make this document churn on unrelated PRs. The conclusion it supports is an order-of-magnitude gap, which is stable; the exact figures are an illustration and are re-measured when someone has reason to.

The gap is comments. A function that carries the constraint it must keep, such as why a partial Docling parse must raise before anything is written, is not made longer by stating it. Counting physical lines would put the size rule and the comment rules in conflict, and would push even the comments that must stay onto the same line as code.

Counting statements measures what "do one thing" is about, how much a function does, and is blind to how well it is explained. On that measure the codebase is in good shape: 26 offenders in chitragupta/, not 128, and the tests hold the bar almost perfectly at 1 in 1926.

The same correction applies to files: chitragupta/core/config.py is 696 physical lines and 246 lines of code, the difference being 450 lines of per-setting rationale. The file rule counts code lines (non-blank, non-comment) for the same reason.

This is a re-expression, not a relaxation. One outlier got stricter under it, not looser: at 5.7.1, chitragupta/sync.py::run (now chitragupta/cli/corpus/sync.py::run) was 322 physical lines but 117 statements, 4.7ร— the next worst function in the repository. Physical lines ranked it 2.4ร— the next worst and understated how far out it was.

๐Ÿงน The Boy Scout Rule, and surgical changes

The clean-code general rules include:

3. Boy scout rule. Leave the campground cleaner than you found it.

Read as an instruction to each edit, that contradicts this project's process rule, which is that a change should be surgical: don't refactor unrelated code, match the local style, report pre-existing dead code rather than deleting it in the same diff (DEVELOPER-AGENTS.md's "Behavioural rules: think before coding"). Both cannot be followed at the level of a single edit.

They are reconciled by moving the Boy Scout Rule up one level. The ratchet is this project's Boy Scout Rule, applied to the repository across pull requests rather than to whatever file you happen to have open:

That keeps what the rule is for (decay is not permitted) while keeping diffs reviewable. Concretely: noticing that a module is on the register while fixing something unrelated in it is a reason to say so in the PR, not a licence to refactor it there.

The one case where the rule applies to your own edit unchanged is the orphan you created: an import, variable or helper that your change made unused is yours to remove.

โœ… The binary rules

Two rules. Both are enforced by tests/test_code_standards_scan.py, which rides the existing pytest --cov run rather than adding a second quality gate to keep in sync, the same idiom as tests/test_command_depth_scan.py, tests/cli/test_cli_help_is_short.py and tests/test_removed_command_scan.py.

Rule Scope Counted as
C1 A function body holds at most 25 statements chitragupta/, scripts/, tests/ ast statement nodes in the body, not descending into nested definitions. A docstring is one statement (an Expr); a lambda or comprehension is an expression and counts zero however large it is
C2 A module holds at most 250 lines of code chitragupta/, scripts/ Physical lines that are neither blank nor a whole-line comment. A line inside a triple-quoted string that begins with # is dropped as though it were a comment

Why the scopes differ. C1 covers the tests because the tests already hold it (1 offender in 1926), so including them locks in a bar that is met rather than declaring one that is not. C2 does not cover the tests because a test module here is one-per-source-module by convention, and its length tracks the surface of the module under test rather than a count of responsibilities; tests/core/corpus/test_pdf_text.py at over 2,000 code lines is thorough, not overloaded. (tests/core/corpus/test_enrich_real_libraries.py is the one exception to the convention rather than to the rule: it is a second module against chitragupta/core/corpus/enrich/embed_index.py, split out because it runs against the real libraries where the first mocks them.) Capping it would push tests into new files for no reason other than the cap.

bench/ is out of scope for both. It is the parser measurement harness, it is one of the four trees scripts/release.py deliberately excludes from the release archive, and its scripts are one-shot analysis code whose main() reads top to bottom on purpose. It is stated here so that nobody reads its long functions as silently left uncounted; see bench/README.md for the current self-check count and the reasoning behind each of the four things bench/ sits outside.

assets/webapp/ holds both rules too, scanned separately. This table's scope is Python-only (ast has no notion of a .js file), so scripts/webapp_code_standards.js re-derives C1 and C2 over assets/webapp/ (excluding vendor/, the one third-party file there) with its own small parser, ratcheted against code-standards-register.toml's c1js/c2js tables and enforced by tests/topic_app/code_standards.test.js under node --test rather than pytest. Two things do not carry over from the columns above, and that script's own docstring has why: a function is a C1 candidate only when it has a real, derivable name (every file here is a UMD module whose top-level anonymous wrapper holds the entire file as its own statements, which is the JS analogue of Python module-level code, and C1 never counted that either); and C2's line count excludes real comment spans the same way the Python side does, not wc -l's raw count, which would count every line of the rationale banners these files open with.

๐Ÿ“Š Cognitive complexity: the bar is 25, not SonarQube's default 15

SonarQube's Python analysis ships S3776 ("Cognitive Complexity of functions should not be too high") with a default threshold of 15. That default is not this project's standard. The standard here is 25, deliberately aligned with C1's 25-statement rule. The two measure different things (how much a function does against how hard its control flow is to follow), but they draw the line at the same altitude.

A complexity bar lower than the statement bar would drive exactly the over-splitting R3 warns about: functions cut past the point where the logic survives the break, with every cut passing its own re-check.

Operationally:

๐Ÿ—„ What a ratchet is, and the debt register

A ratchet is a mechanical pawl that lets a wheel turn one way and blocks it turning back. As a software check it means: measure something, freeze today's number, and fail the build if it gets worse, while saying nothing about it being imperfect today.

It exists to fill the gap between the two options a new rule normally has, both of which fail:

Option What happens here
Enforce the rule outright Every existing offender fails on day one (28 functions and 12 modules when the rules were adopted). The build is red for reasons nobody in this PR caused, so the rule gets disabled or the threshold raised until it passes, and a threshold tuned to today's worst code is not a standard
Write it down as guidance It is followed until the first deadline. Nothing detects the drift, and two years later the document describes a codebase that no longer exists

The ratchet takes the useful half of each. Here:

๐Ÿ’ก Why a ratchet suits this project specifically

Three reasons apply beyond the general argument.

  1. It matches the one invariant's shape. This project already believes that the way to prevent a bad outcome is a mechanical check that cannot be argued with, rather than a resolution to be careful; that is the citation gate. The ratchet is the same move applied to code decay: an agent cannot talk its way past a failing test, and a future session that has never read this document still cannot land a 40-statement function.
  2. The work is agent-driven and session-scoped. Each session wakes up fresh (SOUL.md's "Continuity"). Guidance that lives only in prose depends on the right file being read at the right moment; a failing test reaches a session that read nothing.
  3. It makes the debt legible instead of ambient. "The code quality is poor" is unactionable and, measured properly, was not even true here. A register entry with its size beside it is a worklist, ordered, with the entries worth taking first at the top.

The register is a debt list, not an allowance. Paying an entry off is a code change in its own pull request, because "several small, reviewable PRs over one large one" applies to the project's own housekeeping.

What the ratchet deliberately does not do is cap the growth of a module already on the C2 register. A registered file may get longer without failing. Capping each at today's exact size would fail on every ordinary edit and would be turned off within a week; the growth of a registered file is caught by C1 on its functions and by review.

๐Ÿ“‹ The rest of the checklist

Every remaining rule from the source, and where it lands. Review means a human reviewer looks for it in a PR; there is no detector, and the rule above says why most of these should not get one.

๐Ÿ“œ General rules

Rule Fate
Follow standard conventions Already here: DEVELOPER-AGENTS.md's "Conventions a new stage has to follow"
Keep it simple; reduce complexity Already here: the "Simplicity first" behavioural rule
Boy scout rule Reconciled above; the ratchet is this project's form of it
Always find root cause Already here, in a sharp form: "Classify a failure by cause on the exception, not by matching its message." Adding a cause means adding a mark, not a string match

๐Ÿ— Design rules

Rule Fate
Keep configurable data at high levels Already here: config.toml is the single source, every key overridable by an env var
Prefer polymorphism to if/else N/A as stated: chitragupta/ has no class hierarchies; its classes are dataclasses, exceptions and a few small wrappers. Its functional equivalent is used: review.AIDS is a dispatch table, and a new aid is added by registering it rather than by editing a branch
Separate multi-threading code Already here: the process pool lives in chitragupta/core/corpus/pdf_text/ and chitragupta/core/corpus/sync_pool.py, and nothing else in the codebase knows about it
Prevent over-configurability Review. A config.toml key with one caller and no user asking for it is a maintenance cost, not flexibility
Use dependency injection Already here as the probe pattern: a stage depends on "is pandoc on PATH?", answered at run time, never on a --target flag naming its environment
Follow Law of Demeter Already here as module boundaries: references.py reads the ledger's bib_fields column and must not reach through to bibliography.bib

SOLID is not in the source list and is not adopted as a slogan here, for the same reason polymorphism is N/A. Where its principles apply they already appear above under the names this project uses: single responsibility is "do one thing" plus module boundaries, and dependency inversion is the probe pattern.

๐Ÿ‘“ Understandability

Rule Fate
Be consistent Review, and the highest-value one in this list. A second way of doing something already done is the most common finding here
Use explanatory variables Review
Encapsulate boundary conditions Already here, as a whole module: chitragupta/core/draft/passages.py is the single place that decides which span of a source may be shown, so no caller re-derives it
Prefer dedicated value objects to primitive types Already here where it helps: records such as Passage, SearchResult and Reference are dataclasses. The exception is deliberate: a citekey is a bare str, because it is also a filename stem and a ledger key; the invariant is enforced by one shared validator (chitragupta/core/citekey_safety.py, re-exported as bib_reader.citekey_problem()) and by one path builder, citekey_safety.citekey_path(), which every per-citekey file name goes through (tests/core/test_citekey_path.py fails on any other join), rather than by a wrapper type
Avoid logical dependency Review
Avoid negative conditionals Review

๐Ÿท Names

All six (descriptive and unambiguous, meaningful distinction, pronounceable, searchable, named constants instead of magic numbers, no type prefixes) are review standards, adopted as written. The house example is unguarded(text) in test_command_depth_scan.py: it says what the thing is for, not what type it returns. MAX_STATEMENTS and _GUARD_WINDOW are the magic-number rule as practised.

๐Ÿงฉ Functions

Rule Fate
Small Enforced as C1, counted in statements
Do one thing Review, and the reason C1 works as a proxy. The common smell here is a main() that parses arguments, does the work, and formats the output; most of the C1 register has that shape
Use descriptive names Review (see Names)
Prefer fewer arguments Review
Have no side effects Review. Note the deliberate exception: the corpus layer's whole job is a side effect, and it is confined to the one layer that takes the write lock
Don't use flag arguments Review, with a live precedent: --target host|docker is documented as informational only, because the probes decide and nothing branches on it

๐Ÿ“ Source code structure

All review standards, adopted as written: vertical separation of concepts, related code dense, variables declared near use, dependent and similar functions close, functions in downward dependency order, short lines, no horizontal alignment, whitespace to group, consistent indentation.

"Keep lines short" is the one that could cheaply become a detector. Build order puts it with ruff, which enforces it as E501 rather than needing its own scanner.

๐Ÿงฑ Objects and data structures

Largely N/A, and the reason is stated so the gap does not read as an omission. chitragupta/ has no class hierarchies. Its classes are dataclasses holding records, exception types, and a few small context managers and wrappers (interrupt_guard, _AnnotatedStream).

"Prefer data structures" and "hide internal structure" are what the codebase already does: modules expose functions over dataclasses, plain dicts, tuples and sqlite3 rows. "Should be small", "do one thing" and "small number of instance variables" apply to any class that does appear, and C1 already covers its methods.

๐Ÿงช Tests

Rule Fate
One assert per test Adopted in spirit, not literally. One behaviour per test, named for it. A literal single assert would split test_a_deeper_path_is_flagged_and_reported_in_full into two tests that mean nothing apart
Readable Review, and the reason the tests duplicate setup freely rather than DRYing it. A test that reads top to bottom is worth more than a DRY one
Fast Already held: the whole suite runs in well under a minute
Independent Already held, and load-bearing: tests/conftest.py isolates per-test state
Repeatable Already held, and it is a product rule here too: the review layer's reports carry no timestamp, so two runs over unchanged input produce byte-identical output

๐Ÿ” Code smells: the review vocabulary

The six smells are adopted as the vocabulary for a review finding, because naming the smell is what turns "this feels wrong" into a claim someone can agree or disagree with.

Smell What it looks like here
Rigidity: a small change cascades Adding a parse failure cause that requires touching every caller, instead of adding a mark on the exception
Fragility: one change breaks many places The reason the review layer has one output contract in core/review/__init__.py, and one procedure around it in cli/review/_emit.py, rather than eleven aids each writing their own path
Immobility: code cannot be reused The reason chitragupta/core/draft/passages.py is a module and not logic inlined into verbatim_check
Needless complexity Speculative configurability, an abstraction with one call site, defensive handling for an impossible state
Needless repetition Two similar blocks are a coincidence; three are a pattern. Extracting from two call sites is as likely to produce a wrongly-shaped abstraction as to remove real duplication
Opacity: hard to understand Usually a missing why-comment rather than bad code

๐ŸŽฏ Behaviour before code

Four rules about how an agent should work rather than what the code should look like. They live with the process rules in DEVELOPER-AGENTS.md's "Behavioural rules: think before coding" rather than here: think before coding, simplicity first, surgical changes, goal-driven execution. The third is the one reconciled above.

โ–ถ Build order

The detectors that extend the enforced half, each at a binary bar.

Enforced today:

  1. C1 and C2, by tests/test_code_standards_scan.py for Python and tests/topic_app/code_standards.test.js for assets/webapp/, against code-standards-register.toml.

  2. A linter and a formatter. ci.yml's lint job runs pylint --rcfile=.pylintrc chitragupta scripts .claude/hooks, ruff check over the same roots, and ruff format --check over chitragupta/scripts/tests/bench/.claude/hooks, each at zero findings. pylint covers the Names rules and unused imports; ruff's E501 and the formatter enforce short lines. TECHNICAL-DEBT.md has the baselines.

  3. A # noqa-free policy. ruff's BLE makes a blind except a finding, and RUF100 makes every # noqa: BLE001 a checked claim rather than a comment nothing reads.

  4. Type annotations. Every def under chitragupta/ carries a return annotation, and tests/test_annotation_scan.py ratchets it the way C1/C2 are ratcheted. A type checker (mypy) is declined as part of this standard: worth having, and its own project.

  5. A doc-drift detector for the registers. Every claim about the registers is binary. test_the_registers_are_the_size_this_document_says pins this document's copy of the two sizes; tests/test_technical_debt_scan.py pins TECHNICAL-DEBT.md's copy, and fails when that document names a function or module as open C1/C2 debt that the register no longer lists.

  6. Import direction between core, CLI and webapp. tests/test_import_direction_scan.py puts each module under chitragupta/ in a layer by its path, and does the same for tests/core/, tests/cli/, tests/webapp/ and tests/feature-parity/ once they exist. It fails when:

    It also runs chitragupta --help in a subprocess and fails if that loads fastapi, starlette, uvicorn or chitragupta.webapp.

    The rules are hard: there is no allowlist, and any violation fails. Each rule is shown firing on a file planted in a temporary tree. The ratchet that held the old violations while #1280 split the commands was removed when that issue closed. Adding or removing a shim edits SHIMS in the same file, never the rules. The same file also fails if a core module binds a name main or has a module __getattr__ that returns one: a command's main lives in cli/.

    Two more tests in the same file hold where a front end may live: no module under chitragupta/ is named *_cli.py or __main__.py except the chitragupta/__main__.py shim the console scripts name, and no module under cli/ has a __main__ block. tests/cli/test_command_order.py pins the order --help lists the top-level commands and each layer's verbs in. tests/cli/test_census.py walks the parsers to every command and mode (68 leaves) and fails on one that is not split into a core builder and a cli/ renderer, the webapp server alone excepted. It also checks each builder's name against its help path and that each render_text takes one parameter typed as its builder's payload.

    tests/core/test_top_level.py holds the other end: the top level of chitragupta/ is __init__.py, __main__.py, the nine shims, cli/, core/ and webapp/, and nothing else. A new module goes into core/ or cli/, never beside the entry points.

Not built, and not a backlog item: a detector for free-standing factual claims in prose, the kind with no register behind them. There is nothing binary to check such a claim against, and R3 rules out reaching for a prose-accuracy score instead. A claim becomes checkable when something machine-readable becomes its source of truth, not when someone writes a cleverer scanner. This document has one such claim: the physical-line-versus-statement measurement above is quoted here and in tests/test_code_standards_scan.py's docstring, and a refactor that moves those numbers leaves two copies to update by hand.

๐Ÿšซ What this does not change