Trusting AI-written code without reading every line

Trusting AI-written code without reading every line

I do not read every line of the code my coding agent writes. It produces most of the diffs for the mobile apps our small team maintains, faster than I can review them carefully. I needed a way to catch mistakes in code I hadn't read. I now require automated checks before a change counts as done, with standing instructions that the agent must never weaken them. Getting those checks to fail for the right reasons took more work than I expected. So did deciding which changes needed the full process. Each check has to be a command with an exit code. I ask for its output before accepting the result. Check why the test failed For changes to logic, I start with a failing test. A bug fix needs a regression test that fails before the fix and passes after it. Otherwise, I have no evidence that the test covers the bug. Small copy or visual changes follow the lighter process described below. A coding agent can hand me a "failing" test that fails for the wrong reason: the test file doesn't compile, or a fixture can't be found, and the runner exits non-zero. That is a broken build, and it proves nothing about the bug. So the check I trust is narrower. The run must report at least one executed test with a failure. import re EXECUTED = re.compile(r"Executed (\d+) tests?, with (\d+) failures?") def a_test_went_red(output: str) -> bool: return any(int(m.group(2)) > 0 for m in EXECUTED.finditer(output)) The regex matches XCTest's summary line. Jest and pytest need different patterns. I run the new test by name and read its failure message too: an executed test can still fail on an unrelated assertion. This function checks for a reported test failure; it cannot establish the cause. Behaviour tests for user flows For user-facing flows I write Given/When/Then tests and cite the acceptance criterion in each one. That gives me something to check when an agent later "simplifies" the code and breaks a test. I can go back to the required behaviour rather than argue about the implementation. // AC 4: a failed save keeps the draft on screen func testFailedSaveKeepsDraft() async { // Given a draft and a store that rejects every write let editor = Editor(draft: "weekly report", store: RejectingStore()) // When the user saves await editor.save() // Then the draft is still there and the failure is shown XCTAssertEqual(editor.draft, "weekly report") XCTAssertEqual(editor.banner, .saveFailed) } Keep the coverage floor visible Line coverage of the logic layer must stay at or above 90 percent. The floor is a constant in the script, so there is no flag to pass and no config value to edit: import json, subprocess, sys FLOOR = 90 # a constant on purpose report = json.loads(subprocess.check_output( ["xcrun", "xccov", "view", "--report", "--json", sys.argv[1]])) files = [f for t in report["targets"] for f in t["files"] if "/Logic/" in f["path"]] if not files: sys.exit("no logic-layer files in the report; was coverage enabled?") covered = sum(f["coveredLines"] for f in files) total = sum(f["executableLines"] for f in files) pct = 100 * covered / max(total, 1) print(f"logic-layer coverage {pct:.1f}% (floor {FLOOR}%)") sys.exit(0 if pct >= FLOOR else "coverage gate failed") An agent with write access can still edit that constant, so this raises the cost of lowering the floor without forbidding it. What backs it up is the standing instruction below and the fact that a lowered threshold is a small, greppable diff. The script also enforces only the floor: "changed code must not lose coverage" is an instruction to the agent, and nothing checks it. The if not files branch is there because a gate that passes on an empty report proves nothing. My mutation gate follows the same rule: a file with zero mutants is rejected unless the run log shows the tool looked at it. What the green tests missed A mutation tool makes a small change to your code, such as flipping a comparison, then re-runs the tests. If they still pass, the mutant survived. That can reveal an outcome the tests never assert, though some mutations leave behaviour unchanged. The score is roughly the share of mutants detected. I mostly use Muter for Swift and Stryker for TypeScript and JavaScript. I measured three modules of a small Node service. All three had tests and every test was green. Their mutation scores were about 17, 24 and 9 percent. After I added behaviour tests that asserted real outcomes (exact cooldown values, the full persisted record), they went to about 86, 90 and 84. The more useful lesson came from a number that was too good. Early on, the middle module read 95 percent. Several older tests left real writes to a JSON store on disk, and under Stryker's shared sandbox those writes raced on a file rename. Mutants counted as killed because of the race, not because an assertion noticed anything. With the writes isolated, the module scored about 24, the figure above. The 90 came later, from the new tests. Stryker's thresholds.break defaults to null, so unless you set it, a low score never fails the build. My config for one module: { "mutate": ["src/limiter/cooldown.js"], "testRunner": "command", "commandRunner": { "command": "node --test tests/cooldown.*.test.js" }, "coverageAnalysis": "off", "thresholds": { "high": 90, "low": 85, "break": 80 } } A test that stubs out the module under test can never kill a mutant in it, so the config runs only tests that load the real code. Stryker's command runner can't optimise and runs every listed test for every mutant, so that list has to stay short. Mutants can hang: flip a loop condition and a test never returns. Stryker counts a timeout as a detected mutant, which flatters the score. In one run, a few mutants reported as timeouts survived when I re-ran them alone, so I reported the lower number. With Muter on my setup, a hung test stalled the run until my own watchdog killed it, because Muter's timeout covers the whole suite and my per-test limit never reached the test step. A small wrapper around the xcodebuild call that appends its test-timeout flags fixed it. Check what your tool actually mutates. In November 2026, Muter's documentation lists four operators: negated conditionals, swapped logical connectors, removed side-effect calls and swapped ternary branches. They do not mutate arithmetic or literals, so the score cannot tell me whether a test would catch a changed rounding factor or date offset. After changing arithmetic I run a hand mutation. A small script reads a plan entry, changes one literal, runs the named tests and expects a red one: [{"file": "Sources/Rounding.swift", "old": "* 1.5", "new": "* 1.4", "tests": ["RoundingTests"]}] It reports KILLED, SURVIVED or INVALID. A survivor means I write a sharper test. It never means deleting the mutation. The other cost is time. Running the whole unit suite for every mutant took about 17 minutes each on my build machine, a Mac mini that also does other work; at a few hundred mutants, that is days. Limiting each mutant to the logic-layer tests brought a four-mutant sample on a laptop down to about 1.3 minutes each. Different machines, so read the ratio loosely. A full run still takes hours, so mutation testing gates a release, not every change. Failures outside the assertions Strict lint, warnings as errors and a clean build run on every change. The scripts enforcing these checks get their own tests as well; a broken check can otherwise report success. A CI run showed me a gate I didn't have. My suite creates thousands of throwaway preference stores. On a busy runner the OS started refusing writes partway through a run, and nothing failed, because no test read the value back. Two green runs on the main branch had refused one and three writes, and nobody noticed. A CI step now scans the test log for refused writes and fails the job. The real flow, on a simulator The logic tests above won't catch a label that wraps badly at the largest text size or a sheet with the wrong button tint. For visible changes I also run the flow on a simulator and inspect screenshots. The broader visual pass covers light and dark mode; a small change gets the narrower check in the table below. The run is scripted, but I still look at the pictures. Integrity rules These are written into the agent's instructions: Never delete, skip or weaken a test to make a run green. Never lower a coverage or mutation threshold. Never loosen lint. "Tests pass" and "it works" need the real command output pasted into the report. No output means not verified. A passing test is useful only if its assertions tell me something about the behaviour. In one of the Node modules, the remaining survivors were all log-message text. I left them as survivors. Asserting on those strings would raise the score, but the tests would then break on typo fixes without checking any more behaviour. Scale the process to the change My first version applied everything to every change. Then I measured two weeks of my own sessions. One small UI change, a progress indicator on a long-running screen, took a bit over six hours of wall-clock time, and about 45 minutes of that was coding. The rest went to review workflows (across those two weeks the median one ran about 50 minutes), a mutation run, a full visual matrix and CI waits. Each step is reasonable alone. Together they were out of proportion to a one-screen change. Now every request gets a lane before work starts: Lane Typical change Checks Small copy, color, icon, single-screen fix, bug with a known cause related tests and build; one screenshot if UI changed Medium a new screen or feature inside one module TDD on the changed logic; iPhone in light and dark; at most one short review at the end Large several modules, architecture, data migration, an audit everything above plus mutation, iPhone and iPad, long localized text Two things override the table. Anything that touches money, auth, secrets, schema migration or concurrency is never small, and a decision that is hard to undo makes the work large. And mutation testing and the full visual matrix run once per release, on the modules that changed. The agent picks the lane after reading the code and states it in the first line of its reply, with one sentence of reasoning, so I can disagree early. A small hook injects the lane rules and a keyword-based guess into each request, and it fails open: if the hook breaks, my prompt goes through untouched. The lanes are new. I have the measurement that motivated them, but not months of data on whether they let through something the full process would have caught. What this does not give me The agent writes both the code and the tests, so their mistakes can correlate. A misread requirement shows up on both sides and stays green. Mutation testing makes tests sharper, but it cannot tell me the spec was right. Mutation scores carry noise: equivalent mutants (changes that don't alter behaviour) make 100 percent the wrong target, so I gate at 80. The checks tell me the code does what the tests say. They say nothing about whether users want the feature. If you want to try one piece, take a module you believe is well tested, run a mutation tool on it and read the survivors. The lowest score I measured was 9 percent, on code whose tests were all green.

Original Source

Read the full article at Hackernoon →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.