enolaBlog

architecture

How to Enforce Architecture Rules for AI Coding Agents: From Docs and Comments to Checks

Enola reads the architecture your code has. To check it against the one you want, it needs you to declare that. I used the enola-intent skill to do so for Gitea, and to extend what Enola already declares about itself.

Dejan Menges14 min read

Most codebases have architecture rules, which say what may depend on what: handlers don't talk to the database, the shared package depends on nothing. Some are in a document, some in comments, and some are only mentioned in code review.

A coding agent may never see them. It reads the files its task needs, adds an import that compiles, and nothing objects.

This is the last post in a series about the skills that come with Enola, an open-source CLI and MCP server that builds a graph of your code on your own machine. The earlier ones covered reviewing a change and planning its tests and checking an agent's notes. This one is about enola-intent, which helps you turn such rules into a file that Enola checks. In short:

  • On Gitea, the skill found the package order in the project's docs and declared it. A change that breaks the order passed the check before and failed it after.
  • It missed one of Gitea's rules, which I added during review.
  • On Enola, it proposed 15 rules on top of the layers we already declare. 13 hold today, and two are broken by one import each.
  • On a small policy-as-code example, one rule catches analytics code that can reach card numbers two calls away.

Implicit architecture: what a code graph shows

Enola reads which package imports which, which function calls which, and which route reaches which table. I call this the implicit architecture: nobody has declared it, and it needs no setup. With it, Enola can say what depends on a function before you change it, and which dependencies or cycles a change introduced.

The graph comes from parsing the source, without running the code and without a model. How Enola works follows a source file from parsing to the snapshot, The graph lists what is in it and what is not, and the code is on GitHub.

It can't say whether a new dependency is allowed. Enola does look for common layer patterns, but a recognised pattern is a guess about what you meant, so its confidence is capped at 0.80.

Explicit architecture: declaring layers and rules

Many projects describe their architecture in an ARCHITECTURE.md or a similar document, and point their agents at it. That tells people and agents what was decided and why. It doesn't tell anyone whether the code still follows it: an agent may not load the document, may lose it in a long session, or may read it differently than you meant, and nothing fails when it does. Gitea's guidelines, in the example below, state the package order in two sentences, and 81 dependencies in its code run against it. Instructions are not controls has more on this.

So keep the document, and declare the parts that can be checked. In Enola, they go into enola-intent.yaml at the root of the repository, and I call that the explicit architecture:

yaml
layers:                      # outermost first
  - {name: handlers, paths: ["app/handlers/**"]}
  - {name: domain,   paths: ["app/domain/**"]}
  - {name: storage,  paths: ["app/storage/**"]}

components:
  - name: storage
    match: ["app/storage/**"]
  - name: notify
    match: ["app/notify/**"]

rules:
  - id: storage-sends-nothing
    forbid: storage
    to: notify
    via: imports
    because: "persistence must not decide what the buyer is told"

Each layer may depend on itself and on the layers below it. Rules cover what an order can't express, and each carries its reason, which Enola includes in every violation it records.

A violation of a declared order has confidence 1.00, the level enola check requires by default before it can fail a build.

Why check architecture rules on a code graph

Checking architecture rules isn't new. ArchUnit does it for Java, dependency-cruiser for JavaScript and TypeScript, Deptrac for PHP and go-arch-lint for Go, and if you have one of them, it may be all a single codebase needs.

Enola checks its rules on one graph that holds every language it reads and, when you load several repositories together, the calls between them. That makes it useful for systems a language's own tool sees only a part of: a rule can say that the web app in one repository must not call the internal endpoints of a Go service in another. Constraints has an example of such a rule.

Writing architecture rules with the enola-intent skill

You can write the file by hand. Three things tend to go wrong:

  • A path selects nothing. After a typo, a rule covers no code and can never be broken. It looks the same as a rule that holds.
  • The rules are made up. An agent asked for architecture rules can write plausible ones, with plausible reasons that nobody on the team ever had.
  • Habits become rules. "This package rarely calls that one" may be true without anyone having decided it.

The skill gives your agent a procedure that deals with these:

  1. Read what is already declared, and what Enola infers.
  2. Look for patterns the code almost follows, and drop those that are only habits.
  3. Write a draft outside the repository.
  4. Check what each rule in the draft covers, and what it breaks today.
  5. Bring you one proposal, with the questions only you can answer.
  6. Write what you accept, with your reasons.

Turning on enforcement is left to you. Violations that exist when you declare a rule don't fail the check by default; only new ones do. Enola calls this the ratchet.

Example: enforcing layer dependencies in Gitea, a Go codebase

Gitea is a self-hosted Git service, written mostly in Go and one of the repositories we benchmark Enola on. Its backend guidelines say which way packages may depend on each other:

cmd → routers → services → models → modules

A package on the left may import a package on its right, but never the reverse.

I ran Enola 0.5.4 on a copy of the repository at commit 38b07d0c. Its snapshot had 258 findings and none was about layers: Enola recognised no layer pattern here.

Step 1: ask the agent to propose architecture rules

In Claude Code, with Claude Opus 5.5:

/enola-intent Set up architecture rules for this repository so they are checked from now on.

The proposal, shortened:

Already declared: nothing.

Proposed layer order. This is the order already written in docs/guidelines-backend.md.

Today: 6,100 imports follow the order and 81 go against it: 76 from modules to models, 2 from modules to services, 3 from services to routers.

Proposed rules: routers/web must not import routers/api, and the reverse.

Questions only you can answer

  1. Is the documented order still the decision? Is modules → models debt to work off, or have modules/indexer, modules/repository and modules/templates effectively become part of models or services?
  2. Where does modelmigration belong? The doc doesn't place it.
  3. Why do the two router rules exist, if you want them?

Left out: about 1,060 mined candidates. They describe how often a package is used, not a decision.

I checked the count with a text search and found 80 import lines against the order, in the same three directions. Enola also counts a dependency that goes through a call without an import line of its own.

Whether the 76 are debt, or the document is out of date, is a question for Gitea's maintainers.

Step 2: review and accept the rules

I'm not a Gitea maintainer, so I accepted only what the project itself states. That kept the layer order and dropped both router rules.

The skill had missed one. Gitea's linter configuration forbids migrations to import models or modules/structs, because an old migration must not change when those do. I asked for that rule, with the reason from a comment in Gitea's code. The resulting file:

yaml
# docs/guidelines-backend.md: "Dependencies only flow in one direction:
# cmd → routers → services → models → modules. A package on the left may import
# a package on its right, but never the reverse."
layers:
  - {name: cmd,            paths: ["cmd/**"]}
  - {name: routers,        paths: ["routers/**"]}
  - {name: services,       paths: ["services/**"]}
  - {name: modelmigration, paths: ["modelmigration/**"]} # imported by cmd and services, imports only models and modules
  - {name: models,         paths: ["models/**"]}
  - {name: modules,        paths: ["modules/**"]}

components:
  - name: migrations
    match: ["modelmigration/**"]
  - name: evolving-structs
    match: ["models/**", "modules/structs/**"]

rules:
  - id: migrations-use-frozen-structs # mirrors the depguard "migrations" rule in .golangci.yml
    forbid: migrations
    to: evolving-structs
    via: imports
    because: "the structs used in migrations should not be affected by the changes happen in the future"

The new rule has 28 breaches today. Four come from five import lines in three packages, each with a nolint comment saying why it is allowed. The other 24 are migration packages that have no such import. They call models/db through a type alias in modelmigration/base, which a check of import lines doesn't see.

The exceptions are deliberate, so these breaches may all be acceptable. The count shows how far the exception for modelmigration/base reaches.

Step 3: catch an architecture violation in a change

To test the declaration, I added a function to modules/issue/template that looks up a template's labels in the database:

go
func KnownLabels(ctx context.Context, repoID int64, tmpl *api.IssueTemplate) (int, error) {
	ids, err := issues_model.GetLabelIDsInRepoByNames(ctx, repoID, tmpl.Labels)
	return len(ids), err
}

This makes a module import a model, which the guidelines forbid. The linter configuration has no rule against it, and nothing in models imports this package, so it creates no import cycle either.

I ran the same check on it twice:

sh
enola check --fail-on=layers,constraints

Without enola-intent.yaml:

text
PASS — no structural regression.

New coupling (4: imports 1, calls 1, instantiates 1, declares 1):
  gitea.dev/modules/issue/template  --imports--> gitea.dev/models/issues
  ...

With it:

text
FAIL — 1 structural regression introduced.
law: 1 rule · 28 breaches · none excused

Regressions (fail):
  - [layers] 1.00 — Layer violation: modules -> models (declared)
      import of gitea.dev/models/issues

Enola reported the new import both times. Only the second run had an order to check it against, and it failed on that import alone, not on the existing violations.

Example: strengthening Enola's own architecture rules

Enola's own enola-intent.yaml has six layers, from entrypoint down to core, and every pull request is checked against them. I ran the skill on a copy of the repository:

/enola-intent Review and strengthen the architecture we already declare for this repository. Keep what holds, propose what is missing.

The existing order holds: 1,073 imports follow it and none go against it. The skill found three things it doesn't cover.

Dependency rules inside a layer

Of the 164 modules in the order, 125 are in one layer, analysis. It contains the passes that read source code (extractors), connect it (linkers), report on it (explainers) and write it out (renderers). Within a layer, any module may import any other.

A comment at the top of the file says about these passes: "They know about facts and about nothing above them, which is what lets a new extractor be written without reading the engine." The skill proposed six rules to keep them apart. Four hold, and two have one breach each:

  • extractors-do-not-link: the C++ extractor runs a linker to resolve what test code refers to.
  • linkers-do-not-explain: a linker uses helper functions that live in a package of the explainers.

Neither is a bug. The first may be a deliberate exception, and in the second the helpers may be shared code that belongs in another package. Both are still open.

Turning code comments into architecture rules

Other comments in the file make claims such as "internal/linescan is core, and depends on nothing". The layer check doesn't verify them, because it allows imports within a layer.

The skill turned nine of these into rules, and all nine hold. It also tested that such a rule can fail: a trial version that let pathglob import only itself caught its import of factpath. The proposed rule allows that import.

Finding a layer path that matches no code

One path in the core layer, internal/treesitter/**, matches no code, because our configuration excludes that directory as vendored. Enola's lint reports a layer that selects nothing, but not a single path inside one, so it had passed.

Checking a change against the architecture rules

On the copy, I accepted all 15 rules with our own comments as the reasons, and left the two breaches as they are. Then I added a helper to the Go extractor that uses a function from the explainers:

go
package goextractor

import "github.com/enola-labs/enola/internal/explainers/common"

// dirOfFile is the directory a fact's file belongs to.
func dirOfFile(file string) string { return common.FileDir(file) }

It compiles, and it passes go vet and the layer check our CI runs today. With the new rules:

text
FAIL — 1 structural regression introduced.
law: 15 rules · 3 breaches · none excused

Regressions (fail):
  - [constraints] 1.00 — Constraint extractors-do-not-explain violated: ...
      forbidden imports edge
      internal/extractors/goextractor/filedir.go:3

An agent can also test a patch before applying it:

sh
enola plan --patch change.diff
text
NEW — this patch WOULD introduce:
  Constraint extractors-do-not-explain violated: ...
    because: They know about facts and about nothing above them, which is
    what lets a new extractor be written without reading the engine.

Example: policy as code on the implicit architecture

Some rules can't be checked from a declaration and a list of imports. Take one modelled on PCI DSS, the security standard for card payments: reporting code must not be able to reach card numbers. Checking it means following every call that starts in the reporting code.

Enola's repository has a policy-as-code example, a small Go payments module with seven rules based on PCI DSS and GDPR. This is the one for reporting, with the reason shortened:

yaml
rules:
  - id: pci-dss-1-2-analytics-stays-out-of-scope
    forbid_reach: analytics
    to: cardholder-data
    mode: strict
    because: "PCI DSS 4.0 req 1.2: reporting is outside the audited boundary"

The example then adds a function to analytics:

go
// Reconcile re-runs the charge to check the ledger agrees.
func Reconcile(token string, cents int) bool {
	return gateway.Charge(token, cents)
}

It calls the payment gateway and never mentions card data. go build and go vet pass. The check doesn't, because gateway.Charge calls cardholder.ReadPAN, which returns the card number:

text
Strict constraint pci-dss-1-2-analytics-stays-out-of-scope violated:
  policyascode/analytics.Reconcile reaches policyascode/cardholder.ReadPAN
      reachable in 2 hop(s)

The rule is explicit: someone decided that analytics is out of scope. The path is implicit: nobody declared that Charge reads a card number, and Enola found it in the code. The check needs both.

It covers calls Enola can resolve. It says nothing about encryption, retention or anything else that happens at runtime. Policy as code: what a code graph can check goes through all seven rules.

What Enola, the agent and you each do

Enola counts and compares: the imports against an order, the code a path selects, the dependency a change added. That part involves no model, and the same code and declaration always give the same answer.

The agent reads the docs and comments and writes the proposal. It can miss a rule, as it did on Gitea, and another run may propose something different.

You decide which rules are right, and give the reason for each.

That last step matters more when agents write the code. An agent can see what the code does, but not whether anyone wanted it that way. On Gitea, it proposed two router rules only because today's code follows one and almost follows the other, and missed one the project had written down. If the agent also approved its own rules, the check would compare its work with its own guesses, and enforce a wrong rule as reliably as a right one. The person who accepts a rule is the one who can say why it exists, and when it no longer applies.

What declaring architecture rules costs

Each proposal was a fresh Claude Code session with Claude Opus 5.5, run once. Accepting continued the same session:

Repository Step Time Cost
Gitea Proposal 60 s $0.64
Gitea Accept and write 32 s $0.21
Enola Proposal 94 s $0.84
Enola Accept and write 30 s $0.20

This is the cost of declaring or revising rules. Checking them has no model cost.

Not having them costs too: a dependency in the wrong direction is easiest to remove in the change that adds it, and in Gitea there are now 81 to sort through.

How to add architecture rules to your repository and CI

The skill ships with Enola 0.5.4 and later.

New to Enola. Install the binary, then run two commands in your repository:

sh
curl -fsSL https://raw.githubusercontent.com/enola-labs/enola/main/install.sh | sh

enola install --hooks
claude mcp add-json enola '{"command":"enola","alwaysLoad":true}'

The last line is for Claude Code. Other agents are in Connect your coding agent.

Already using Enola. Run enola upgrade, then enola install again in the repository, because only install writes the skills.

Restart your agent session and ask:

/enola-intent Set up architecture rules for this repository.

When you review the proposal:

  1. Check it against what is already written. Guidelines, linter settings and comments hold decisions the agent may have missed.
  2. Start with the layer order. Add rules only for what it can't express.
  3. Reject a rule you can't give a reason for.

To enforce the rules, add one command to CI:

sh
enola check --base origin/main --fail-on=layers,constraints

With --hooks, Enola also checks at the end of each agent session, and tells the agent if it broke a declared rule. Install and upgrade lists the agents this works in.

What architecture rules won't tell you

Whether the declaration is right. Enola checks the code against it. A declaration can be wrong or out of date.

Anything about code outside the graph. A rule doesn't reach ignored directories or external libraries.

Layer violations in enola plan. It evaluates rules, not the layer order, so it reported nothing for the Gitea patch. enola check covers both.

Which old violations matter. The ratchet lets you start with violations in place and doesn't remind you of them. enola constraints ledger lists every rule with its breaches and exemptions.

FAQ

Will architecture rules fail my build on existing violations?

Not by default. Nothing fails until you pass --fail-on, and then only on violations a change introduced.

Can an AI agent change the architecture rules to make its change pass?

The skill tells it not to, and not to add exemptions. Nothing prevents the edit, but the declaration is a file in your repository, so the change shows up in review.

Can I keep my existing architecture linter?

Yes. The agent can read its configuration, so you can ask for the same rules in Enola, as I did with Gitea's depguard rule.

Can I enforce architecture rules in languages other than Go?

Yes. Layers, components and rules apply to the graph, which is the same for every language Enola supports.

Further reading