- Book: Hexagonal Architecture in Python
- Companion code: hexagonal-python-examples — every listing from the book, free on GitHub
- My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools
- Me: xgabriel.com | GitHub
In 2024, for the first time in a five-year dataset of 211 million changed lines, copy-pasted lines outnumbered moved lines. That is the headline finding of GitClear's 2025 AI Copilot code quality research, and "moved" lines are what GitClear calls "a proxy for refactoring activity": code that keeps its logic but changes place to improve the design.
Read that as a statement about your backlog. The ticket that says "extract this into a service once the feature settles" is competing with a tool that makes pasting the next variant cheaper than moving the first one. In this data, the paste is winning.
My take: if code almost never gets moved once it lands, an architecture that plans to tidy up later will stay untidy. With coding agents writing a growing share of the lines, the boundaries have to exist before the agent writes the first one, and a machine has to enforce them.
What GitClear actually measured
The 2025 report covers January 2020 through December 2024, across repos GitClear says are owned by Google, Microsoft, Meta and enterprise companies. Per GitClear's report page, moved lines fell from about 25% of changed lines in 2021 to under 10% in 2024, while cloned lines rose from 8.3% to 12.3%.
Two more numbers get quoted a lot. DevClass reports "a 39.9 percent decrease in the number of moved lines," and that "the number of code blocks with 5 or more duplicated lines increased by 8 times during 2024." LeadDev describes the same metric as blocks of five or more lines "that duplicate adjacent code." The report's own page headline uses a smaller number, "4x Growth in Code Clones," so be specific about which metric you cite.
GitClear has since published a follow-up, The Maintainability Gap, covering 623 million changes from 2023 to 2026. It reports moved code at 13% of changed lines in 2023, "freefalling to 3.8% year-to-date in 2026," and copy/paste climbing "from 9.4% (in 2022) to 15.7% in the first half of 2026." It is a different dataset with different baselines, so don't splice its numbers into the 2025 chart. The direction is the same in both.
Read the caveats before you quote it
Three caveats belong next to every one of those numbers.
First, GitClear sells developer analytics (its pricing page), and DevClass notes the code came "from customers of its own code review tools," along with open source projects. A company whose product measures code quality has a commercial reason to publish data saying code quality is slipping. That doesn't make the data wrong, but it should make you read the methodology before the headline.
Second, this is correlation. The trend lines move in the same years AI assistants spread, and that is all they show. GitClear's signal graphs page says AI-assisted commits are identified heuristically, from commit authors, API stats and "LLM fingerprint" signals, with no published error rate on that page. Other research is mixed: Google's 2024 DORA report found that a 25% increase in AI adoption was associated with a 3.4% increase in code quality and an estimated 7.2% reduction in delivery stability.
Third, the duplication count had a narrow scope, at least in the older data. GitClear's earlier 153-million-line study said its operations "only include code that is duplicated within a single commit" (Arc's write-up), so a block pasted on Monday and pasted again in a different commit on Friday may not have shown up at all. The 2026 follow-up still reports a signal called "within-commit copy/paste," but the signal graphs page now describes block duplication as detected "within the same commit or across the recent codebase," which suggests the scope has widened. Wherever the narrow scope applies, the real duplication is likely higher.
"We'll clean it up later" is a plan the data says rarely runs
An agent completing a task reads the files near the change and produces code that fits them. That is what makes it useful. It also means the first version of a pattern becomes the template for every later version. If the first handler builds a SQLAlchemy session inside a business rule, the handlers the agent writes after it will tend to look the same, because that is what the surrounding code says the project does.

Copies are cheap to make. Moving code back into shape is the step that stopped happening.
The usual answer is a refactoring pass once things settle. Moved code at under 10% of changed lines in the 2025 report, and 3.8% year-to-date in the separate 2026 one, is what that pass looks like in aggregate: rare. So the honest plan is to make the right shape the cheapest shape from the start. Put the core logic where it can't see the database, give the outside world narrow ports, and let the agent copy a pattern that is already correct.
What boundaries up front look like in Python
Hexagonal architecture (ports and adapters) gives you three places to put code. The domain holds the rules and the ports it needs. Adapters implement those ports against real infrastructure. Entry points, such as a FastAPI route, wire the two together.
app/
domain/
order.py # entities, no I/O
ports.py # Protocols the core depends on
checkout.py # use cases
adapters/
sql_orders.py # SQLAlchemy lives here
entrypoints/
http.py # FastAPI routes, wiring
The port is a typing.Protocol, so the domain names what it needs without importing anything that provides it:
# app/domain/order.py
from dataclasses import dataclass
@dataclass
class Order:
id: str
total_cents: int
# app/domain/ports.py
from typing import Protocol
from app.domain.order import Order
class OrderRepository(Protocol):
async def get(self, order_id: str) -> Order | None: ...
async def add(self, order: Order) -> None: ...
# app/domain/checkout.py
from app.domain.order import Order
from app.domain.ports import OrderRepository
async def place_order(
repo: OrderRepository, order_id: str, total_cents: int
) -> Order:
if total_cents <= 0:
raise ValueError("total must be positive")
order = Order(id=order_id, total_cents=total_cents)
await repo.add(order)
return order
The test needs no database, no container and no network. A fake adapter is a dictionary:
# tests/test_checkout.py
import asyncio
from app.domain.checkout import place_order
from app.domain.order import Order
class InMemoryOrders:
def __init__(self) -> None:
self._rows: dict[str, Order] = {}
async def get(self, order_id: str) -> Order | None:
return self._rows.get(order_id)
async def add(self, order: Order) -> None:
self._rows[order.id] = order
def test_place_order_stores_it() -> None:
repo = InMemoryOrders()
order = asyncio.run(place_order(repo, "o-1", 1200))
assert asyncio.run(repo.get("o-1")) == order
When an agent adds the next use case, the nearest example it reads already takes a port and keeps I/O out. Copying that shape is fine. That's the point of setting it up early.
Turn the boundary into a check that fails
A layout is a suggestion. An agent under pressure to make a test pass will import whatever fixes the error in front of it. import-linter turns the layout into contracts that lint-imports checks, configured in pyproject.toml:
[tool.importlinter]
root_package = "app"
include_external_packages = true
[[tool.importlinter.contracts]]
name = "Core never touches infrastructure"
type = "forbidden"
source_modules = ["app.domain"]
forbidden_modules = ["sqlalchemy", "fastapi", "httpx"]
[[tool.importlinter.contracts]]
name = "Dependencies point inward"
type = "layers"
layers = ["app.entrypoints", "app.adapters", "app.domain"]
The forbidden contract docs say external packages need include_external_packages and must be listed by their root name, and that indirect imports are checked by default. So a domain helper that pulls in a module that imports SQLAlchemy breaks the contract too. In a layers contract, the order runs from higher to lower: entry points may import adapters and the domain, and the domain may import neither.

The boundary only holds if something checks every import that tries to cross it.
Run it in CI, where it can block a merge. Then put it in the agent's loop, so the agent hears about a broken contract while it still has the context to fix it. With Claude Code, a PostToolUse hook that exits with code 2 shows its stderr to Claude after the edit; a hook that exits 0 with no output is silent to it. The docs note the tool has already run, so this can't undo the edit, which is why CI stays the real gate.
#!/usr/bin/env bash
# .claude/hooks/lint.sh: runs after every Write or Edit
cd "$(dirname "$0")/../.." || exit 0
if ! out="$(lint-imports 2>&1)"; then
echo "$out" >&2
exit 2
fi
The script assumes lint-imports is on the hook's PATH; if it only lives in the project virtualenv, call .venv/bin/lint-imports instead. The hook below runs the command directly, without a shell, so make the script executable with chmod +x .claude/hooks/lint.sh. Then register it in .claude/settings.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/lint.sh",
"args": []
}
]
}
]
}
}
Now the rule lives in a place the agent reads every time it edits, instead of a document it may never open.
This won't stop duplication inside an adapter, and it won't make a reviewer unnecessary. It stops the expensive kind of copy: infrastructure spreading into the core, one pasted handler at a time, until moving it back out is a project nobody gets to. Start with the forbidden contract on app.domain. It is a few lines of TOML, and lint-imports fails the first time anything in the core imports SQLAlchemy.
If this was useful
That separation between a core you can test with a dictionary and the database, framework and network around it is what Hexagonal Architecture in Python is about. It isn't an AI book: it builds one async FastAPI and SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered and vertical slice) and then measures them, so you can see what each boundary costs and buys. Every listing runs from the free companion repo.

Top comments (0)