Give AI Agents a Map, Not a Maze: Restructuring a Frontend Monorepo for Stable Iteration
Title: Give the Agent a Map, Not a Maze: A Frontend Monorepo Directory Restructure Log
Author: 小龙6666
Tags: Frontend, Agent
theme: orange
Introduction
When a project contains both an Agent application and an admin console, and you want AI Agents to participate in iteration stably, the design goals of the directory structure change fundamentally. Traditional directory structures serve "human developer collaboration and long-term maintenance," while AI-iteration-friendly directory structures serve "Agent context acquisition cost and modification boundary constraints." They are not about depth, but different optimization goals.
This article starts from directory structure design, explains the differences from traditional programming development directory structures, the reasons for these differences, and how reuse issues are solved under the new structure.
I. Overall Structure: Dual Apps + Shared Contracts + Agent Operation Layer
A monorepo-style workspace is adopted, physically isolating the Agent application and the admin console, but sharing types and foundational components. The root directory holds the Agent's "operation entry point" so it can understand project rules without traversing the entire repo.
project-root/
├── AGENTS.md # Agent's only entry: tech stack, commands, directory safety boundaries
├── .agent/
│ ├── skills/ # Reusable operation processes (add page, change route, run verification)
│ ├── specs/ # Acceptance criteria for the current iteration (one file per feature)
│ └── contexts/ # Read-only context: route table, menu tree, component inventory snapshots
├── apps/
│ ├── agent-web/ # Agent user-facing application
│ └── admin/ # Admin console
├── packages/
│ ├── shared-types/ # API types and domain models shared across apps
│ ├── ui-core/ # Foundational components without business logic (Button, Modal, Table)
│ └── request-client/ # Unified request instance, error code mapping, interceptors
├── scripts/
│ └── verify # Only verification entry: typecheck + lint + test + build
└── pnpm-workspace.yaml
Design rationale: Before modifying code, the Agent needs to know "how routes are registered, where components go, what the verification command is." If this information is scattered across various src directories, the Agent has to re-infer each time, leading to inconsistent changes. A root AGENTS.md plus the .agent/ directory gives the Agent a map and an executable checklist, rather than making it work by guesswork.
Agent Application Directory: Separating Session State and Tool Calls
The Agent application is special because it has both traditional frontend UI and logic such as session management, tool call rendering, and streaming response handling. The directory needs to let the Agent clearly distinguish "pure presentation" from "stateful logic with side effects."
apps/agent-web/src/
├── app/ # Routing and page assembly
│ ├── (chat)/ # Main chat interface
│ ├── (history)/ # History sessions
│ └── layout.tsx
├── features/
│ ├── conversation/ # Conversation domain: message list, input box, streaming rendering
│ │ ├── components/
│ │ ├── hooks/ # useStreamingResponse, useMessageQueue
│ │ └── stores/ # Conversation state
│ ├── tools/ # Tool call rendering
│ │ ├── registry.ts # Mapping table: tool name → rendering component
│ │ └── renderers/
│ └── artifacts/ # Agent product preview
├── lib/
│ ├── agent-client/ # Client for communicating with Agent backend (SSE/WebSocket)
│ └── guardrails/ # Frontend safety fallback: output filtering, timeout handling
└── shared/
Design rationale: The most problematic area in the Agent application is the coupling of "rendering tool calls" and "session state." By making tools/registry.ts the single registration point, when the Agent adds a new tool renderer, it just adds one line to the registry without touching the main session flow. lib/agent-client centralizes streaming protocol handling, preventing each feature from implementing its own SSE parsing, reducing cascading risks during iteration.
Admin Console Directory: Domain-Based Splitting, Limiting Shared Spread
The admin console typically iterates more frequently than the Agent application, but its changes should not affect the stability of the Agent application. This is achieved through dependency direction constraints in packages/ : the admin console can depend on shared packages, but shared packages cannot depend back on the admin console.
apps/admin/src/
├── app/
│ ├── (dashboard)/
│ ├── (agent-config)/ # Agent configuration management (model, prompt, tool permissions)
│ └── (audit)/ # Audit logs, call records
├── domains/ # Split by business domain, each domain self-contained
│ ├── agent-config/
│ │ ├── api/
│ │ ├── components/
│ │ └── hooks/
│ ├── audit-log/
│ └── user-management/
├── components/ # Layout components used only by admin
└── lib/
└── permissions/ # RBAC permission checks
Design rationale: A common failure mode in admin consoles is piling all business components into components/, and after six months no one knows which component belongs to which feature. With domains/ splitting, each domain has clear boundaries; when the Agent modifies pages related to "Agent configuration," it only needs to look at domains/agent-config/ and won't accidentally modify audit log code.
II. Specific Conventions for the Agent Operation Layer
Beyond the directory structure, several hard rules are written into AGENTS.md:
Single verification entry point: scripts/verify must exist and be runnable. After any modification, the Agent runs only this command. It internally runs typecheck, lint, relevant packages' test, and build in order. Verification failure means no commit.
Snapshot mechanism for routes and menus: The admin console's menus and permission routes are usually returned dynamically by the backend, so the Agent cannot see the full picture during local development. A route/menu snapshot exported from the development environment is placed under .agent/contexts/. Before modifying route-related code, the Agent reads this snapshot to avoid inventing route names or permission codes.
Directories the Agent must not modify: Types in packages/shared-types/ are dictated by the backend contract, and the Agent must not modify them on its own. To add new types, the requirement must be stated in .agent/specs/, then updated after human confirmation, or generated from the backend schema via code generation.
Write specs for each iteration: Don't let the Agent work only from chat logs. Each iteration task creates a markdown file under .agent/specs/ that specifies: which application is involved, expected behavior, acceptance command, and directories that are off-limits. The Agent reads the spec before starting and self-checks against it when done.
Unify cross-application contract types: The interface return structure of the "Agent config" module in the admin console often differs subtly from the configuration structure the Agent application actually reads at runtime. Put such cross-application contract types in packages/shared-types/agent-config.ts and import from there in both ends. If the admin console changes a field, TypeScript immediately raises an error at the consuming point in the Agent application, preventing hidden breakage like "the backend changed the config but the frontend fails at runtime parsing."
III. Differences from Traditional Directory Structures and Their Causes
The root of the differences: traditional directory structures serve "human developer collaboration and long-term maintenance," while AI-iteration-friendly structures serve "Agent context acquisition cost and modification boundaries."
1. The root directory gains an "Agent operation entry layer"
Traditional project roots have src/, public/, package.json, README.md. README is written for humans, with free-form formatting, and the Agent has to guess which parts are rules and which are explanations.
An AI-friendly structure adds AGENTS.md and .agent/. AGENTS.md is a machine-parseable rules file: commands, safety boundaries, forbidden directories, itemized and unambiguous. .agent/skills/, .agent/specs/, .agent/contexts/ persist "operation procedures," "this iteration's acceptance criteria," and "route/menu snapshots" from chat logs and human memory into versioned files.
Cause: Human developers can pass this information through verbal communication, code review, and team conventions. Agents lack these implicit channels; every session is a cold start, so implicit knowledge must be made explicit and written down.
2. Verification entry point converges from "multiple scripts" to "one command"
Traditional projects often have multiple scripts in package.json: dev, build, test, lint, typecheck. Humans know which ones to run after changes; the Agent does not, and may skip or run them in the wrong order. An AI-friendly structure requires scripts/verify as the single verification entry.
Cause: Humans judge the verification order themselves; agents do not. Traditional projects have no motivation to achieve this level of "verification determinism."
3. Directory splitting basis shifts from "technical layering" to "modification boundaries"
Traditional frontends commonly layer by technical type: components/, hooks/, utils/, services/. This is human-friendly because people find things by "is this a component or a utility function" intuition.
For an Agent, technical layering means a single business change spans multiple directories. When changing the "Agent config" feature, components, hooks, APIs, and types are scattered everywhere. The Agent must understand the entire project's technical layering conventions to change correctly, which is costly and easy to miss a layer.
An AI-friendly structure uses features/ or domains/ to be self-contained by business domain. When the Agent changes a feature, the scope of modification is contained in one directory, boundaries clear.
Cause: Traditional layering optimizes for "humans searching by type," while AI structure optimizes for "isolation by modification scope."
4. Shared packages get "dependency direction constraints"
Traditional monorepos also extract packages/shared, but dependency direction is often by convention, and occasionally a shared package will reference business code back without anyone stopping it.
An AI-friendly structure turns dependency direction into a hard constraint: packages/ can only be depended on by apps/, never the reverse; shared-types/ is dictated by the backend contract and the Agent must not modify it.
Cause: Agents lack the global judgment of "will this change cause circular dependencies." Once a shared package becomes polluted, all applications break together. Traditional projects rely on human architectural awareness as a safety net; AI projects must rely on directory and rules.
5. Cross-application contract types are elevated to a separate package
In traditional projects, types shared between the admin console and user-facing applications are often placed under one side's types/, with the other side importing them, or each side writes its own and relies on integration testing. An AI-friendly structure elevates cross-application contracts to packages/shared-types/, and both sides import from there.
Cause: When an Agent changes code, it does not proactively think "the other end is still using this field." Traditional projects find these issues through integration testing; AI projects use the type system to intercept at compile time.
6. Snapshot files become part of the directory
In traditional projects, menus and permission routes returned dynamically by the backend are viewed by logging into the development environment during frontend development; there is no habit of writing them down. An AI-friendly structure puts route/menu snapshots under .agent/contexts/.
Cause: Human developers can see the menu by opening a browser; the Agent cannot see runtime state, so it relies on snapshot files to fill this information gap.
Comparison Table
| Dimension | Traditional Directory Structure | AI-Iteration-Friendly Directory Structure |
|---|---|---|
| Serves | Human developers | Agent + Human |
| Knowledge carrier | Verbal communication, conventions, Code Review | Versioned files (AGENTS.md, specs, snapshots) |
| Splitting basis | Technical type layering | Business domain self-containment (modification boundaries) |
| Verification method | Multiple scripts, human-judged order | Single command, fixed order |
| Dependency constraints | Architectural awareness | Hard rules via directory rules |
| Contract synchronization | Integration testing, test discovery | Shared type package, compile-time errors |
Essence: An AI-friendly directory structure shifts part of "human responsibility" to "the project structure itself." Traditional structures rely on human developers' implicit knowledge and active judgment; agents lack these, so implicit knowledge must be made explicit and judgment rules solidified into directories and files.
IV. What About Reuse?
The most questioned aspect of domain self-containment is: does every domain copy a set of components? The answer is: reuse does not disappear; it is re-layered — reuse happens at the "stable lower layers," while domains contain "volatile business combinations" .
Three Layers of Reuse
Layer 1: Foundational components without business semantics → packages/ui-core/
Button, Modal, Table, Form controls. They do not depend on any domain state, have stable interfaces, and change infrequently. Agents can safely reuse them because the contract is defined by props.
Layer 2: Cross-application contracts and clients → packages/shared-types/, packages/request-client/
API types, error code mappings, unified request instance. This is where "logical reuse" should occur — request interceptors, authentication, error handling written once.
Layer 3: In-domain business combinations → features/xxx/ or domains/xxx/
Conversation message list, tool call renderer, Agent config form. These are "business assemblies," and reuse typically happens within the same domain. In-domain components are not reused across domains by default, unless proven stable.
Cross-Domain Reuse: Promote, Not Copy
When two domains need the same business component, the traditional approach is to move it to a common components/. The AI-friendly approach is promotion:
- First it exists within a domain. When a second domain references it, do not import across domains directly; first evaluate whether business semantics have been stripped.
- If it depends only on props, not on specific domain state or interfaces, promote to
packages/ui-core/or createpackages/ui-business/. - If it still carries business semantics, promote to a business-named package under
packages/, rather than stuffing it back into some domain's directory.
Reuse is "proven," not "presupposed." A common failure in traditional projects is premature abstraction — a huge components/ where anyone can drop anything, and after six months no one knows which components are stable. The promotion mechanism gives every shared item a clear "promotion record," and what the Agent sees in packages/ is already verified stable components.
Two Types of Logical Reuse
Tool logic without business state (date formatting, debounce, SSE parsing, permission code matching) → packages/utils/ or packages/request-client/. Pure functions, zero-risk reuse.
Hooks with business state ( useStreamingResponse, useMessageQueue, useAgentConfigForm) → stay in domain features/xxx/hooks/. These hooks depend on the domain's state management and interfaces; forcing them up would leak business state into the shared layer. If two domains both need them, it indicates they share the same business model, and consideration should be given to merging the domains rather than extracting a common hook.
Hard rule: code under packages/ must not import anything from apps/. Dependency direction is one-way, keeping the shared layer clean. When the Agent tries to "take a shortcut" by moving a business hook to a shared package, this rule blocks it.
How the Agent Knows "What to Reuse"
Place a component inventory snapshot under .agent/contexts/:
.agent/contexts/component-registry.md
The content is not a full component list, but a layered inventory:
- Which foundational components exist in
packages/ui-core/and a one-sentence description of each prop contract - Which shared business packages exist in
packages/and their applicable scenarios - Which components in each domain are "marked as promotion candidates"
Before starting a task, the Agent reads this snapshot to know "the message bubble component already exists in the conversation domain, don't create a new one" or "date formatting is in packages/utils, just import it." The snapshot can be generated by a script (scanning exports and reading comments), avoiding manual maintenance that goes stale.
Reuse Scenario Comparison Table
| Reuse Scenario | Traditional Approach | AI-Friendly Approach |
|---|---|---|
| Foundational components | Put in global components/ |
Put in packages/ui-core/, stable contract |
| Business component used across domains | Move directly to common directory | Prove stability first, then promote to packages/ |
| Business hook | Often extracted to global hooks/ |
Stay in domain; cross-domain use indicates merging domains |
| Utility functions | utils/ hodgepodge |
Go to packages/utils/ or request-client based on responsibility |
| Agent finds reuse | Relies on humans or search | Reads .agent/contexts/ component inventory snapshot |
Conclusion
An AI-friendly structure does not abandon reuse; it changes reuse from "spatial centralization" to "layered convergence." Foundational components and contracts are reused centrally in packages/, while business combinations remain self-contained within domains and are promoted as needed.
The cost is an extra evaluation step during promotion. The benefit is that every time the Agent changes code, the modification scope and reusable items are deterministic — it does not need to understand the entire project's abstraction conventions; it only reads snapshots and follows dependency direction. Traditional reuse relies on human judgment; AI structure relies on directory rules and snapshot files, turning the judgment of "should we extract a common component" from human experience into an executable process.
In one sentence: the core of an AI-friendly directory structure is making implicit knowledge explicit, solidifying judgment rules into files, and converging modification boundaries into directories, so the Agent can iterate stably within a defined scope.
Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.
Using AGENTS.md as the single entry point is spot on. Agents know where to go right away instead of hunting around. Folding verification into a single command also saves hassle; after changes, running it once gives you confidence.
agent: I want my take, not yours [sly]