跳到正文
DEV Community· Jack M·· 11 小時前AI 評分63

AI 編碼智能體架構差異:在結構變更累積成技術債前進行審查

AI Coding Agent Architecture Diffs: Review Structural Changes Before They Become Debt

AI 導讀

架構差異檢查可對照程式碼庫基礎分支與提議分支的結構,呈現編碼智能體提交新增或移除的模組依賴及違規邊界。文章建議由人手維護精簡架構規則,從程式碼生成依賴圖,並按風險要求測試、書面理由、負責人審批或阻擋 CI。靜態分析可能漏掉反射、動態載入等情況,因此架構差異應配合行為測試及安全審查,而非取代它們。

正文

A coding agent can pass every test in a pull request and still make the codebase harder to change. One new import from a UI handler into the database layer, one background worker that reaches into a private module, or one shared helper with a hidden network call can reverse a boundary that took months to establish.

That is the blind spot in a test-only workflow. Tests answer, “Does this behavior work?” They rarely answer, “Did this patch change who is allowed to depend on whom?” Architecture diffs make that second question visible. They turn a coding-agent patch into a small structural receipt: which modules and edges changed, which boundaries were crossed, why the change is allowed, and what evidence supports it.

This is not a call to generate a beautiful diagram for every pull request. It is a way to make structural review cheap enough that it happens before agent-written changes become permanent debt.

The result is a review process that rewards small, explainable changes.

What an architecture diff is

An architecture map is a snapshot of the repository’s meaningful parts: modules, ownership boundaries, and allowed relationships. An architecture diff compares the base branch with the proposed branch and reports changes to that map.

For a web application, a small map might state:

web -> application -> domain
application -> ports
adapters -> ports
workers -> application
web -X-> adapters/database
domain -X-> web

-X-> means “must not depend on.” The map does not need to model every file. Start with the boundaries that protect your system: layers, packages, service ownership, external clients, persistence, authentication, and side-effect entry points.

An architecture diff then answers questions that a line diff buries:

Change Why it matters Typical response
New import crosses a forbidden layer Can leak infrastructure concerns into core logic Block or redesign
New dependency reaches a protected module May bypass an API or owner boundary Require owner review
Existing edge moves from test-only to runtime Can add a production dependency Require deployment evidence
New public entry point appears Expands the maintenance and attack surface Document contract and tests

The goal is not to prevent change. It is to make the structural cost of change explicit while the pull request is still small.

Why coding agents need a structural receipt

Coding agents are good at finding a locally plausible path. When asked to add a feature, an agent can locate a convenient internal function, import it, and make the tests green. That path may be perfectly reasonable in isolation. Across dozens of tasks, however, these shortcuts become a web of dependencies that no one intentionally designed.

Recent work on checked repository maps emphasizes grounding an agent’s understanding in file-level evidence, while architecture-test guidance makes the complementary point: important boundaries should be executable rather than merely written in a document. The missing operational step is to review the delta an agent proposes.

Use an architecture-diff receipt when a task can:

  • add an import across package or service boundaries;
  • introduce a queue, scheduled job, API endpoint, webhook, or database access path;
  • move a responsibility between modules;
  • add a dependency that will ship at runtime; or
  • modify a shared package with many callers.

For a typo or isolated component change, the receipt can be empty. That is useful too: it proves the patch stayed contained.

Start with a small, owned map

Do not ask an agent to infer an entire enterprise architecture and then treat its diagram as truth. Put a compact, human-owned map in the repository. Keep it near the code and review it like any other interface.

Here is a deliberately simple YAML example:

modules:
  web: [apps/web/**]
  application: [packages/application/**]
  domain: [packages/domain/**]
  adapters: [packages/adapters/**]
  workers: [apps/workers/**]

allowed:
  - web -> application
  - application -> domain
  - application -> ports
  - adapters -> ports
  - workers -> application

forbidden:
  - web -> adapters
  - domain -> web
  - domain -> adapters

owners:
  adapters: platform-team
  domain: core-team

Two details matter. First, map globs to concepts your reviewers recognize, not to a clever taxonomy. Second, use a shrinking baseline for legacy violations. Record existing exceptions, forbid new ones, and remove the old list gradually. A rule that fails on day one because of hundreds of historic violations will simply be disabled.

Generate the diff from code, not agent narration

Ask the agent for an explanation, but derive the receipt from the repository. A static import graph, package dependency graph, service contract registry, or framework-aware analyzer is a stronger source of truth than a paragraph in a pull-request description.

A basic pipeline looks like this:

base commit  -> extract dependency graph -> map to modules
head commit  -> extract dependency graph -> map to modules
                             |                |
                             +-- compare changed edges --+
                                                 |
                                      policy + risk classifier
                                                 |
                                  PR receipt and CI decision

For JavaScript or TypeScript, parse imports rather than matching text with a regular expression. For Python, inspect imports and package metadata. For service repositories, add generated client calls, topic subscriptions, and route registrations to the graph when those are meaningful dependencies. The exact extractor can change; the review contract should not.

A useful receipt is short and concrete:

## Architecture receipt

- Added: `web -> application` via `CheckoutController.ts`
- Added: `workers -> application` via `sendReceipt.ts`
- Removed: none
- Policy violations: none
- Risk: medium — new asynchronous side effect
- Evidence: idempotency test, queue retry test, owner approval from platform-team

Notice what is absent: a claim that the agent “understood the architecture.” The receipt names observable changes and the evidence needed for the risk.

A minimal implementation pattern

You do not need a custom platform to begin. A repository can keep a tiny script that emits normalized edges, then compare the result against the base branch in continuous integration. The important design choice is to keep extraction separate from policy. The extractor says what it found; the policy decides whether that relationship is acceptable.

type Edge = { from: string; to: string; file: string };

const forbidden = new Set(["web->adapters", "domain->web"]);

for (const edge of changedEdges as Edge[]) {
  const key = `${edge.from}->${edge.to}`;
  if (forbidden.has(key)) {
    console.error(`Forbidden architecture edge: ${key} (${edge.file})`);
    process.exitCode = 1;
  }
}

In a real checker, normalize aliases first, ignore type-only dependencies when they have no runtime effect, and include the importing file in every finding. That final detail saves review time: a reviewer should be able to jump from a reported edge to the exact import rather than investigate an opaque graph node.

Keep an allowlist narrowly scoped. An entry such as web->adapters is too broad if only one adapter is justified. Prefer an exception that names the target, owner, reason, and expiry. Once it expires, CI should ask the team to remove it or renew it deliberately.

Classify risk before deciding what CI should do

Not every changed edge deserves the same friction. A policy that blocks every new relationship will train people to route around it. Instead, classify the edge.

Risk Example CI action
Low New dependency within one owned module Record only
Medium New worker-to-application edge Require tests and a written reason
High UI reaches persistence directly Fail unless an approved exception exists
Critical New path to payments, identity, or production administration Fail and require named owner approval

Risk should come from the target and direction, not from whether an agent wrote the code. A human patch that bypasses authorization deserves the same response.

This gives coding agents a much better correction loop than “please respect our architecture.” If CI reports web -> adapters as forbidden, the agent can move the behavior behind an application port, rerun the graph check, and show the corrected receipt.

Avoid the failure modes that make guardrails noisy

Architecture controls fail when they become either ceremonial or impossible to satisfy. Watch for these common mistakes.

  • Using a generated diagram as policy. A diagram may be helpful for orientation, but it is not a stable rule until its boundaries are written in a reviewed configuration or test.
  • Checking imports without checking direction. A dependency list can grow without exposing the important question: whether the caller crossed inward or outward through the intended API.
  • Letting the agent edit policy and implementation in one unreviewed patch. Require a different owner, or at least a separate review checkpoint, for changes that relax a protected boundary.
  • Confusing a clean graph with a safe release. Architecture receipts complement behavior tests, security review, migration checks, and deployment evidence. They do not replace them.
  • Ignoring false positives. If a checker routinely reports generated files or type-only imports, fix the classifier quickly. A trusted small report is better than a comprehensive report that reviewers mute.

These guardrails should be boring. Their job is to turn a structural concern into a specific next action, not to create another dashboard that people visit after a production issue.

Add a task contract before the agent edits

Architecture diffs work best when the agent knows the intended shape before it searches for shortcuts. Put a few constraints in the task or repository instructions:

Task: add receipt emails after checkout.

Allowed changes:
- web may call packages/application
- workers may call packages/application

Do not:
- import adapters/database from apps/web
- send email in the HTTP request path
- change public payment contracts

Required evidence:
- unit test for the application command
- retry-safe worker test
- architecture receipt with changed edges

This is a boundary, not an implementation prescription. The agent still has room to select names and local design, while reviewers get a clear standard for accepting the work.

Review the receipt with the code, not instead of it

An architecture diff has limits. Static graphs can miss reflection, dependency injection, dynamic imports, generated code, configuration-driven routes, and remote calls. They can also over-report harmless type-only imports or test fixtures. Treat the tool as a focused review aid, not proof of safety.

On every non-empty receipt, ask four questions:

  1. Is the changed edge actually necessary for the user outcome?
  2. Does it preserve the intended direction of dependency?
  3. Does the PR include behavior tests at the new boundary?
  4. Who owns the target module, and have they reviewed high-risk changes?

If the answer is “we need an exception,” make it explicit, scoped, and time-bound. An exception without an owner and expiry is just an undocumented new rule.

Make it a lightweight pull-request habit

Start with one protected boundary and one non-blocking report. After a week or two, inspect false positives and tune module globs. Then fail CI only for a short list of high-confidence violations.

A practical rollout sequence is:

  1. Commit a small architecture map with owners.
  2. Generate base and head dependency graphs in CI.
  3. Post changed edges as a pull-request comment or check summary.
  4. Require a reason and tests for medium-risk edges.
  5. Block only forbidden or critical edges.
  6. Review exceptions monthly and shrink the legacy baseline.

This approach keeps the system honest without demanding a modeling program. It also creates useful history: when a boundary changes intentionally, the receipt explains why instead of forcing the next engineer—or agent—to reverse-engineer a surprising import six months later.

FAQ

What is an architecture diff for a coding agent?

It is a comparison of the repository’s structural relationships before and after an agent-generated patch. It highlights changed module dependencies, policy violations, risk, and the evidence needed to review the change.

Are architecture diffs the same as architecture tests?

No. Architecture tests enforce whether a repository currently obeys a rule. An architecture diff focuses on what a specific pull request changed. Use both: tests protect the baseline, while diffs concentrate reviewer attention on new structural movement.

Do small teams need an architecture map?

Yes, but it can be small. Start with the two or three boundaries that are expensive to undo, such as UI-to-data access, domain-to-infrastructure, or application-to-external side effects. A concise map is more useful than an exhaustive diagram nobody updates.

Can an AI coding agent generate the architecture map?

An agent can propose or update a map, but a human should own the rules. Derive dependency evidence from code and require review for changes to the map itself. Otherwise the same patch could weaken the policy that judges it.

What should block a pull request?

Block high-confidence violations of critical boundaries, such as a new bypass around identity, payments, or protected persistence. For new but allowed dependencies, prefer a receipt, tests, and appropriate owner review over an automatic block.

How do you handle dynamic imports and framework magic?

Document the blind spots and supplement static analysis with framework-aware checks, integration tests, route inventories, and runtime traces where needed. The goal is useful coverage of important boundaries, not a claim that one graph captures every execution path.

Closing thought

The best coding-agent workflow does not ask reviewers to trust that a patch “looks clean.” It gives them a compact record of the structural promise the patch made—and enough automated evidence to check that promise before the next shortcut becomes the architecture.

來源:DEV Community · dev.to