Big News: Kosli’s achieves Series A milestone with Deutsche Bank as an investor - Read the announcement
New, open source: Explainable policies that run on Open Policy Agent and Rego. Explore ergo →
New: Kosli Answers is here! AI-powered insights for compliance and security. Learn more →
To be filled in

When AI writes the code, the quality bar has to rise

Jon Jagger
Author Jon Jagger
Published November 17, 2026 in technology
clock icon 13 min read

AI now writes much (if not all) of our code. More code, arriving faster, needs more emphasis on quality, not less. This is not simply because of its volume, but also because AI-written code tends to contain, for example, long complicated functions, and a lot of duplication. This blog post outlines some of the ways Kosli is increasing its emphasis on quality.

Introduction

When people wrote the code and tests, they typically used various metrics, such as coverage, to try and measure quality. Projects rarely insisted on 100% coverage. If you had 90% coverage, it was rarely worth the effort to try and close the last 10%.

There are also various “levels” of coverage. Most projects use line/statement or branch coverage. Almost no one uses the harder-to-achieve path coverage. Indeed, many languages do not even have an open-source path coverage tool.

However, with AI writing the code and tests, the balance is changing. Aspirations that were previously out of reach are now practical, and will no doubt become more and more important as automated guard-rails.

The ratchet: gate the diff, not the repo

Kosli was born during covid. All the code and tests were, until relatively recently, written by people. Kosli has always had a very strong focus on testing and quality but, like most projects, its coverage was not 100%, and did not include path coverage.

We aspire to use raised quality gates (such as 100% path coverage) for the whole repo. But we are not there yet. Putting the gates on the whole repo would fail every PR. So, for now, like the child who plugged the hole in the dyke with their finger, we are targeting the raised quality gates only at each PR’s diff.

What do we mean by “the diff”? It’s everything the branch has changed since it forked from master, including files that aren’t committed yet. A local run and CI both work out the same starting point, so they check the same changes. (In CI, this needs the repo checked out with a depth of 2, not the default of 1, so git can see the commit before the PR’s changes.)

Each ratchet then looks at the diff at its own grain:

  • the src lines added (in git, an edited line is a removed line plus an added one)
  • the src functions that are new, or that hold a changed line
  • the unit test files added or changed
  • the duplicate code added, in src and in test

Gating only the diff has a hole: a PR can lower the coverage of code outside the diff. A PR that deletes a test, or weakens one, passes, even though code that the test used to cover, which the PR never touched, is now uncovered. An AI asked to make a failing test pass might do exactly that.

So we also check the coverage of the whole unit-test suite against a minimum. The minimum sits 0.1 below the current coverage, and only ever goes up. A PR that lowers the coverage by more than 0.1 fails.

Ratchet 1: 100% line/branch coverage for edited code

Every source line changed, and every branch from it, must be covered (by the whole unit test suite). When there is a gap, the output quotes the code of each uncovered line or branch:

src/lib/flow_badge.py:6: line never ran
    return "green"
src/lib/flow_badge.py:5: branch never taken, to line 6
    if compliant:
src/lib/flow_badge.py:11: branch never taken, to function exit
    for trail in trails:

When there is no gap:

Every src line added since abfc1969f1d852e72f975a0dbebecae3fe17d904 ran, and took every branch, in 55 files.

Ratchet 2: 100% path coverage for new code

Line, branch and path coverage

Consider this function:

def banner(member, coupon):
    if member:
        text = "Welcome back"
    if coupon:
        text = "Coupon applied"
    return text
  • Line coverage asks: did every line run? One test, with
    member/coupon == true/true, runs every line. 100% line coverage.
  • Branch coverage asks: did every decision go both ways? That needs each
    if to be both true and false. Two tests do it: member/coupon == true/false
    and member/coupon == false/true. 100% branch coverage.
  • Path coverage asks: did every route through the function run? Each if
    is a choice, and the choices combine, so there are 4 paths:
    member/coupon == true/true, true/false, false/true and false/false.
    Branch coverage’s two tests run only two of them.

Neither of the two branch-coverage tests runs the member/coupon == false/false path, where text is never set and the function crashes. The code has 100% line and branch coverage, and a bug on every call down that path. Path coverage makes a test run the path where the bug hides.

With branch coverage, complexity adds. Each new if adds two branches, and the same two tests can still cover them all. With path coverage, complexity multiplies. Each new if doubles the number of paths. Ten ifs in a row have 2*10 branches but 2^10 paths, each needing its own test!

We want simpler code, not more tests

We do not actually want 1,024 tests for one function. What we want is simpler
code: functions with few enough paths that every one of them can be tested.

In practice we find that, left to itself, Claude will happily write a function with many thousands of paths. So, crucially, we also cap the number of paths in each new function at 8. A function over the cap fails the gate, however well it is tested. This forces Claude to refactor: to split the function into smaller ones, each with few enough paths to test them all.

Loops: zero items, or one or more

We experimented with treating every loop as a decision with two outcomes: the loop body runs zero times, or it runs at least once. A loop isn’t a decision in the usual sense, because the code doesn’t split into two different routes. But the empty case is where bugs often hide. Consider:

def average_age(people):
    total = 0
    for person in people:
        total += person.age
    return total / len(people)

One test, with two people, runs every line and takes both branches of the for (into the body, and out of it once the items run out). That is 100% line and branch coverage. But call it with no people and it divides by zero. Nothing in line or branch coverage asks for that test. Counting zero items as its own path does. The same goes for comprehensions, which have no branches at all.

It did find bugs in the code Claude writes, which often handles the one-or-more case well and forgets the empty one. But it proved too strict. Many loops can never be given zero items, for example a loop over a fixed list of settings, and each one needed a comment to say so. So the tool now counts loops only when asked to (--loops).

The path-coverage tool

There was no open source path coverage tool for Python. So we wrote one (with
Claude’s help, naturally). It is open source, at https://github.com/path-coverage/python. It dogfoods itself so its source has 100% path coverage.

It can run on its own, or alongside coverage.py’s line and branch coverage. It finds every decision in a function (if/elif, and, or, match, comprehension filters and more), records which way each one goes while the tests run, and from that works out which paths through the function were taken. Most of this comes from the branch events that Python 3.14’s sys.monitoring reports. The repo explains the details.

Path coverage can easily get complicated. For example, should the tool try to detect impossible paths, ones no input can take? It does not aim to be complete, only to be useful. It treats a path as impossible only in the simplest case: a leaf whose form fixes its outcome, such as a literal [], which is always false. Everything else is left open, because reporting a gap that cannot be closed is a lesser error than hiding one that can. And in practice an impossible path is useful too: it usually means two decisions test the same fact (if x: and, later, if x and y:). So rather than write a contrived test, Claude refactors so the fact is tested once. When the refactor would read worse than the original, a pair of # path: disable/enable comments can selectively disable path coverage. The function is still held to the path cap.

There is also an implementation for Ruby (the path_coverage gem). Both write the same two JSON files, defined by a shared schema. The JSON output is designed for an AI to read. It is enough for Claude to write the missing tests without reading a coverage report.

For each function with an untested path, a console reporter (for people) lists the choices a test must make to take each one, naming every decision by its source text:

src/fee.py:5 fee() has 2 untested paths.
Add tests that take each of these paths:
  1. line 8 `user.member` true, `order.paid` false, then line 10 `order.big` true
  2. line 8 `user.member` false, then line 10 `order.big` true

Ratchet 3: new tests must be deterministic

The Kosli source has always been structured to be easy to unit test. Every external service (email, Slack, feature flags, authentication, and so on) is reached through a dedicated seam, which a unit test replaces with a stand-in.

A unit test that reaches the network (for example), has either tried to slip around a seam, or has introduced a new external without a seam. We force this to become a test failure by monkeypatching. Before any test runs, we replace the standard library functions that reach outside, such as socket.connect, with wrappers that raise an error naming the file and line that called them.

This makes the unit tests fast, because they do not run code we did not write. It also makes them, in theory, deterministic: the same test, run again, should do the same thing. In practice it is not so simple. For example, a test can still depend on something it shares with a test that ran before it.

So the tests a PR adds or changes are run three times, in one process, each time in a different random order. Each time, we count how often each source line runs, test by test. The first run is ignored, because it alone pays for things that happen once per process, such as imports. The second and third runs are compared, and a test whose counts differ between them fails.

Note that this compares what each test executes, not whether it passes. A test can pass every time and still be nondeterministic: it took a different route through the code. Catching flakiness on the way in is cheaper than hunting flakiness later.

Ratchet 4: no new duplicate code, in src or in test

We have found that Claude will quite happily create a lot of duplication. Asked to add something that looks like an existing thing, it copies the existing thing and edits the copy. If you use AI to write code and have not measured your duplication, we encourage you to do so.

Each file the PR changes must not end up with more duplicated lines than it had at the base. Copies already in the codebase do not fail you. We care about the quality of our tests as well as our code, so we look for source code duplicated in the source, and test code duplicated in the tests. To find the copies we use arid, an open source duplicate code detector.

When new duplication is found, there are two ways out: extract the shared code into a helper, or, where a copy is intended, mark it as such, with a reason.

Less duplication seems to help Claude itself. Claude is very example driven: it learns how to do things from the code it reads. Every bit of duplication is another example of a pattern it should not follow, but often does.

Other bars we have raised

Tests you can trust

  • Random, 100% replayable test order. The unit tests run in a different random order each time. This does not guarantee that a test which depends on another test running first will fail, but over many runs it makes that much more likely. Each run’s order comes from a seed, so when an order does fail, it can be replayed exactly, even when the tests are spread across parallel workers with pytest-xdist: the seed fixes which worker runs which test, and in what order. And with the failing order fixed, we can easily binary-chop it, running only half of the tests before the failing one, then half of whichever half still makes it fail, and so on, to find the test that is actually causing the flake.

  • A cap on test size. A unit test longer than the current limit fails. A long test usually either checks several things at once, or spells out a lengthy setup (that other tests typically repeat). The cap pushes it to be split, one claim per test, with the repeated setup moved into a shared, named helper. The few “legacy” tests over the cap are listed by name, each with its own limit, which can only go down.

  • One id prefix per test file. Every test is named by a short hex id, and every test in a file shares the same prefix, so a whole file can be run by its prefix.

  • Every test says what it does, in English. A test’s name is just a hex number, so it says nothing about what the test checks. That goes in a docstring, in plain English, and a test with no docstring fails. For example:

    def test_1938ce80():
        """
        Do not send slack notifications when no webhook 
        URL has been configured for that server.
        """
        ...
    

    We think this emphasis on English helps Claude, in just the way it would help a human reader.

  • Warnings are errors. Any warning raised during a test run fails it, and we have removed the entries that used to let some warnings through.

Architecture as a lint

  • Hexagonal boundaries. import-linter checks that each layer of the code imports only what it is allowed to. For example, the domain layer cannot import the database layer. A boundary that is checked cannot quietly erode, however fast new code arrives.
  • Unit tests tiered by layer. The unit tests are split into tiers, one per layer of the code, and each tier’s imports are checked too. A test in the domain tier cannot reach into the web layer, so when it fails, you know which layer broke.
  • Every API operation tested. The end-to-end API test run fails if any operation in our OpenAPI schema is not called, with a successful response, by at least one passing test.

Stricter linting

  • Ruff and pre-commit. We replaced Black and pylint with Ruff, run as a pre-commit hook as well as in CI, so problems are caught before a commit is made.
  • More bug-catching rules. We keep adding Ruff rules that catch real bugs rather than matters of style, eg: local variables assigned but never read, names that may be unbound when they are read, etc.

Summary

A full unit-test run, on a developer’s machine, runs the same checks as CI, and our CLAUDE.md tells Claude to run it before every push. So Claude finds out that it has fallen short of the bar while it can still fix it, not after the PR is opened.

We plan to keep adding automated guard-rails, each held first to new code, and then raised across the rest of the codebase as it catches up. Next on our list is mutation testing: a new test must fail when the code it covers is changed, and readability testing of all comments.

AI now writes much (if not all) of our code. More code, arriving faster, needs more emphasis on quality, not less, and more automated guard-rails to “police” that quality.


ABOUT THIS ARTICLE

Published November 17, 2026, in technology

AUTHOR
Get started

Ready to ship at
AI speed, safely?

See how Kosli automates SDLC Governance inside your environment.

Governing 14,383,047 compliance events across the world's largest banks and regulated enterprises