cd /news/ai-tools/architecture-smell-density-fell-6-7-… · home › topics › ai-tools › article
[ARTICLE · art-183053] src=dev.to ↗ pub= topic=ai-tools verified=true sentiment=· neutral

Architecture Smell Density Fell 6.7% After AI Agents. The Code Just Got 12.8% Bigger

A study by Larsen and Moghaddam, posted to arXiv on June 11, 2026, tracked 74 open-source Java projects that adopted AI coding agents against 77 matched controls over 13 months and found architectural smell density fell 6.7% (p = 0.004) while raw smell counts rose 1.1% (p = 0.82) and lines of code grew 12.8%, indicating the density drop came from a larger denominator rather than cleaner code. The authors concluded they found "no evidence that the observed agentic AI tools degrade software architecture in established projects over a six-month window," though the 95% confidence interval for raw smell counts spans roughly -8% to +11%.

recommendation

Track raw defect, smell and vulnerability counts alongside per-KLOC density when evaluating coding agents, because agents inflate code size and per-line metrics will look improving even when counts are stagnant.

more in playbook: Evals and testing for LLM apps
by read10 min views13 publishedDec 6, 2026

Seventy-four open-source Java projects adopted AI coding agents, and their architectural smells per thousand lines fell 6.7% against matched controls, with a p-value of 0.004. That could have been a slide in somebody's AI rollout deck.

The same paper then takes the slide apart. The total number of smells moved by +1.1% (p = 0.82), and lines of code grew 12.8%. The authors conclude that the drop in density came from the bigger denominator.

Stop judging coding agents with any score that divides problems by lines of code. Adding lines is the thing agents do most easily. Every clean line improves the score, and enough of them will pay for a broken rule.

The paper, by Larsen and Moghaddam, was posted to arXiv on June 11, 2026. It compares 74 adopting repos with 77 matched controls, following each for 13 months: six before adoption, the adoption month, and six after. Arcan, a static analysis tool, scanned 1,811 monthly snapshots for cyclic dependencies, unstable dependencies, hub-like dependencies and god components.

Before you quote the 12.8%, note that it is growth relative to the controls. That estimate says adopters grew faster than they otherwise would have. It doesn't mean each repo gained exactly that much code.

The percentages also don't divide neatly. Put 1.1% more smells over 12.8% more code and you get roughly 10% less density, but the paper reports 6.7%. It doesn't reconcile the two. It does call its percentages approximate, because the model uses log(density + 1), and it estimates smell count and code size in separate models. A strict-log version, run only on observations above zero, gives 13.0%. The size moves with the modeling choice, but the paper's explanation doesn't: code grew, and the smell count wasn't shown to change.

The authors state the lesson for other metrics too. Defects per KLOC, vulnerabilities per KLOC and churn per KLOC carry the same risk when the thing you're evaluating changes the size of the system.

The cracked bricks stay the same. The stack they're weighed against keeps growing.

If you wanted proof that agents wreck architecture, this paper isn't it. Its conclusion says: "We find no evidence that the observed agentic AI tools degrade software architecture in established projects over a six-month window, though under worst-case attrition the confidence interval includes zero".

The authors go further and say their findings "do not support escalating architectural safeguards" in response to agent adoption in the short term. The same sentence says the findings "warrant three monitoring practices", and the first is to "track raw smell counts alongside ASD, since density alone will look improving even when counts are stagnant". ASD is their smell density. Dropping density from the merge gate goes further than they do.

Take all of that seriously, then read the interval. The 95% confidence interval for the raw smell count runs from −0.0845 to 0.1061 on the log scale, which is about −8% to +11%. A real increase of up to about 11% would still fit this data. Unstable dependencies rose 5.8%, and that result did not survive correction for multiple tests (p = 0.128).

Another study got a worse picture. A difference-in-differences study of Cursor adoption found static analysis warnings up about 30% and cognitive complexity up about 42%. Those are totals for the whole codebase, so now the opposite problem shows up: a bigger codebase has more of everything. When that team controlled for size in a second model, it reported no significant effect on warnings, and the effect on complexity shrank to about 9%.

So the per-line number can flatter a team that adds bulk, and the raw total can punish a team that ships useful code.

Density exists for a good reason. A 400,000-line system with 50 problems isn't in worse shape than a 4,000-line script with 45. If you compare two unrelated codebases, or track one for years, you need to adjust for size.

A merge decision is a different question. You're asking whether this branch made things worse, and there the adjustment works against you. Some arithmetic with made-up numbers:

Before After the agent's branch
Lines of code 20,000 25,000
Boundary violations 10 11
Violations per KLOC 0.50 0.44

The agent broke a rule, and density improved by 12%. A gate on "violations per KLOC must not rise" lets this branch through, and the next one like it, as long as each carries enough clean lines.

You may already run a gate like this. In SonarQube, the technical debt ratio divides the cost of fixing the code by the cost of developing it, and the second cost is a set time per line times the number of lines. The maintainability grade comes from that ratio. To Sonar's credit, its own guidance avoids the trap for issues on new code: the Sonar way docs recommend the plain "0 issues" condition over ratings, because ratings can still let some debt in. The gate's duplication condition is still a percentage of new code.

The study's authors name a limit that points at the fix. Smells are a proxy. Arcan sees the dependency graph, and erosion proper "requires comparison against an intended architecture". A tool can't find your intended architecture in the code if you never stated it.

So state it. "Nothing under shop.domain imports an adapter, FastAPI or SQLAlchemy" is an intended architecture in one line. Breaking it is a fact you can point to in the source, and the target is zero whether the project has 2,000 lines or 200,000. You don't need a denominator for a target of zero.

This checker uses only the standard library. It prints the count and the density, then fails if any violation is new. The three blocks below are one file, and it starts with the rules:

import ast
import sys
from pathlib import Path

RULES = {
    "shop.domain": ("shop.adapters", "fastapi", "sqlalchemy"),
}

def within(name, prefix):
    return name == prefix or name.startswith(prefix + ".")

def module_name(path, root):
    parts = list(path.relative_to(root).with_suffix("").parts)
    if parts[-1] == "__init__":
        parts.pop()
    return ".".join(parts)

The scan resolves relative imports against the importing file's own package:

def imports(tree, module, is_package):
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            for alias in node.names:
                yield alias.name
        elif isinstance(node, ast.ImportFrom):
            parts = [node.module] if node.module else []
            if node.level:
                here = module.split(".")
                up = node.level - (1 if is_package else 0)
                parts = here[: len(here) - up] + parts
            for alias in node.names:
                yield ".".join([*parts, alias.name])

def scan(root):
    found, lines = set(), 0
    for path in sorted(root.rglob("*.py")):
        source = path.read_text(encoding="utf-8")
        lines += sum(1 for s in source.splitlines() if s.strip())
        module = module_name(path, root)
        is_package = path.name == "__init__.py"
        for name in imports(ast.parse(source), module, is_package):
            for package, banned in RULES.items():
                if within(module, package) and any(
                    within(name, prefix) for prefix in banned
                ):
                    found.add(f"{module} -> {name}")
    return found, lines / 1000

The entry point subtracts the violations you already know about and lists the rest:

def main():
    root, baseline = Path(sys.argv[1]), Path(sys.argv[2])
    found, kloc = scan(root)
    if not kloc:
        raise SystemExit(f"no Python code under {root}")
    known = set(baseline.read_text(encoding="utf-8").splitlines())
    new = sorted(found - known)
    print(f"violations: {len(found)}", file=sys.stderr)
    print(f"per KLOC: {len(found) / kloc:.2f}", file=sys.stderr)
    for edge in new:
        print(edge)
    return 1 if new else 0

if __name__ == "__main__":
    raise SystemExit(main())

Each entry is one module and one imported name, so from fastapi import Depends, Query counts as two, and renaming a file makes its old entries look new.

The baseline is a text file of violations you already have, one per line. An empty one works for a first run on macOS or Linux. The command exits 1 if it finds anything, which is expected here:

python boundary.py src /dev/null > boundary_baseline.txt

The trap from the table, as a test, needs only pytest and the file above:

from boundary import scan

def add(root, name, body):
    path = root / "shop" / "domain" / name
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(body, encoding="utf-8")

def test_density_improves_while_the_boundary_gets_worse(
    tmp_path,
):
    add(tmp_path, "orders.py",
        "import sqlalchemy\n" + "x = 1\n" * 99)
    before, kloc_before = scan(tmp_path)

    add(tmp_path, "refunds.py",
        "import fastapi\n" + "x = 1\n" * 299)
    after, kloc_after = scan(tmp_path)

    assert len(after) / kloc_after < len(before) / kloc_before
    assert after - before == {"shop.domain.refunds -> fastapi"}

The first file has one violation in 100 lines, so 10 per KLOC. After the second file there are two in 400 lines, so 5 per KLOC. Only the last assertion tells you which import to delete.

One crossing is one crossing, however long the fence gets.

Merge boundary.py and the baseline to main first, in a pull request without this step. From then on, CI reads both from main, so a branch can't pass by editing either one:

set -euo pipefail
base=$(mktemp -d)
git fetch origin main
git show FETCH_HEAD:boundary.py > "$base/boundary.py"
git show FETCH_HEAD:boundary_baseline.txt > "$base/known.txt"
python "$base/boundary.py" src "$base/known.txt"

The workflow file that runs this can still be edited in a branch, so put it under CODEOWNERS with required review. When you fix an old violation, delete its line from the baseline, or it can come back unnoticed. And check the checker once: add a forbidden import on purpose and watch the branch go red. A typo in RULES matches nothing and passes everything.

For a real project, use import-linter instead of my script. Its forbidden contracts also follow indirect imports by default, and mine sees only direct ones. Neither kind of check tells you whether the code is good. An agent can keep every import legal and still put a pricing rule in the wrong function. That part is still review.

The study covers Java only, in mature open-source projects, over six months after adoption. Moving its result to your Python service is my argument. The paper doesn't make it.

Adoption was detected from files such as CLAUDE.md and .cursorrules, plus commit trailers such as Co-Authored-By: Claude. Autocomplete leaves no such trace, so the method can't see it. And 8 of the 90 controls originally matched showed AI markers during their study windows anyway (77 of the 90 reached the analysis).

About 19% of the snapshots couldn't be analyzed. Under the most pessimistic correction for repos lost along the way, the density effect shrinks to −2.3% and stops being significant. It also loses significance under the strictest filter for inactive repos.

The authors don't support escalating safeguards because of agents in the short term, and I don't count a boundary check as an escalation. You'd want that rule enforced if every line were typed by hand. What agents change is the price of adding code, and with it how fast a per-line score can drift away from the thing you cared about.

If someone brings you a chart where quality per line went up after the agents arrived, ask to see the numerator: how many problems there were before, how many there are now, and which ones are new.

The import rule above only works if the domain is already kept apart from the framework and the database. Hexagonal Architecture in Python is about getting it there. It builds one async FastAPI and SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered and vertical slice), then measures the results. Every listing runs from the free companion repo.

── more in #ai-tools 4 stories · sorted by recency
── more on @larsen 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/architecture-smell-d…] indexed:0 read:10min 2026-12-06 · —