Deep Dive into AI Agent Systems: From Directory Structures to Evidence Chains
This article explores the internal mechanisms of AI agent systems from an engineering perspective. It emphasizes analyzing the actual file directory structure over reading user manuals to understand runtime states. Key topics include the five-layer architecture model, the assembly logic of system prompts, the "three-ledger" evidence chain for auditability, the mechanics of expert plugins (SubAgents), and the standardization of agent identity using the "four-piece" markdown file suite. The article provides actionable strategies for debugging, ensuring accountability, and maintaining long-term consistency in agent engineering.
1. Why Reading Code is Better Than Reading Manuals
Most agent product documentation teaches users how to interact with the UI. However, engineers need to know what happens behind a single conversation: how the model is called, where memory is stored, how tools are orchestrated, and how multiple expert roles collaborate.
The most reliable way to answer these questions is to trace the code and data flow. The starting point is often the file system rather than architecture diagrams. A fundamental insight is that the entire complexity of an agent system usually lies quietly in an agreed-upon working directory.
For a typical localized agent application, its core state is often concentrated in the user’s home directory, such as ~/.agent-name/. Configurations, memory, sessions, skills, and expert plugins are stored here in layers. Understanding the directory means understanding the machine. Therefore, the first step in troubleshooting is not reading error logs, but checking the actual state of the files. When an agent gets stuck or behaves incorrectly, it is rarely because the “model went crazy,” but because a file’s state deviated—memory file pollution, corrupted session files, or missing skill descriptions will directly manifest in behavior.
A practical habit: treat the directory structure as the system’s “true architecture diagram.” Architecture diagrams show design intent, while directories store runtime facts. Comparing the two reveals discrepancies, which are the problems.
2. The Five-Layer Model: Use as an Index, Not Dogma
Textbook agent architectures are typically divided into five layers:
- User Interaction Layer: terminal UI, chat box, permission confirmation entry.
- Orchestration Layer: decides which model to call, which context to inject, and which tools to execute.
- Capability Layer: pluggable capabilities like tools, skills, and expert plugins.
- Context Layer: assembly of system prompts, memory retrieval, and session injection.
- Model Service Layer: underlying LLM invocation and inference.
The correct way to use these five layers is as an index, not rigid memorization. The real value lies in discovering the “seams” between layers, with the most informative being the assembly logic of the context layer.
3. The Anatomy of System Prompts: Rewritten Before Reaching the Model
Many people assume the prompt sent to the LLM is just the user’s input. In reality, before a request actually reaches the model, the system prompt has already been assembled from multiple components:
- Persona: defines the assistant’s basic tone and behavioral boundaries.
- Memory: cross-session user preferences and historical conclusions.
- Tool Descriptions: function, parameters, and usage timing for each tool.
- Rules: safety constraints, formatting requirements, and prohibitions.
The key detail in this assembly is that the same template often exists in multiple places. The application package might contain a preset template copy, while the user directory holds a dynamic version that can be overridden by skill packs or expert packs. This explains a common phenomenon: the same agent sounds and behaves differently after installing different skill packs or switching experts—because the request has been quietly rewritten by these components before leaving the client.
The engineering corollary: to debug agent behavior, you must dump and inspect the final assembled complete request, not just the user input. The root cause of many “supernatural issues” hides in an unexpected template override or the phrasing of a skill description.
4. The Evidence Family: Making Every Action Replayable and Accountable
Mature agent systems share a pervasive design philosophy: evidence. Every action must leave a trace, and these traces must be categorized and cross-verifiable. A typical evidence system consists of “three ledgers”:
- Session Logs (
projects/): session transactions grouped by project (e.g., JSONL format), answering “what did it do?” - File History: versioned records of files modified by the agent, answering “what did it change?”
- Traces and Audits (
traces/,audit-log/): execution trajectories and audit logs, answering “when and why was it done?”
Itemized, appendable formats (like JSONL, one JSON record per line) are the mainstream choice because they facilitate streaming writes and line-level parsing. Below is an example of a typical trace record:
{"ts":"2025-01-01T10:00:00Z","step":"tool_call","tool":"fs_write","args":{"path":"README.md"},"reason":"update install docs","session":"sess_abc123"}
The most valuable use of this evidence system is the “dual-track comparison method”: placing the model’s self-reported “I thought I did” next to the file-recorded “what actually happened.” When an agent hallucinates or exceeds its authority, the discrepancy becomes obvious at a glance—the model says “I checked the database,” but there is no corresponding tool call in the trace. This is the most straightforward and effective method to audit an agent’s credibility.
5. Expert Plugins: SubAgents with UI
Many agent products support “switching experts.” The underlying mechanism is worth dissecting: an expert is essentially a SubAgent with an independent UI, declaring whether it is a “single-agent type” or “team type” via a declarative type field (e.g., expertType).
The key runtime action is that the expert’s persona file is fully injected into the context. The model repositions its capability boundaries and behavior patterns accordingly, calling the corresponding skill sets. An “expert team” is another form of the orchestration layer—combining multiple experts, assigning tasks through a coordinator, and cross-verifying conclusions to form team-based collaboration.
A critical incident boundary to clarify beforehand: when the expert’s persona conflicts with the user’s own identity settings, which takes priority? When conflicts occur at the system prompt level, model behavior can become unstable or even contradictory. In engineering practice, you should explicitly define priority and fallback strategies, such as stipulating “global persona yields to expert persona, and expert persona must not override safety rules,” and construct specific conflict test cases for regression testing before launch.
6. The Identity Quartet: File-based Persona, Identity, Profile, and Memory
The long-term consistency of an agent ultimately depends on its identity system. In some ecosystems, a “quartet” convention is popular, managed using four Markdown files:
SOUL.md # Persona: personality, tone, value orientationIDENTITY.md # Identity: title, role positioning, capability boundariesUSER.md # User Profile: user preferences, background, habitsMEMORY.md # Long-term Memory: cross-session facts and conclusions
The benefit of “one file per aspect” is that each dimension can be independently edited, cleaned, and version-controlled. When an agent experiences “persona drift” or “misremembers the user,” you can precisely locate and fix a single file without rebuilding the entire memory system. Furthermore, file-based identity data is inherently auditable, completing the “long-term state” aspect of the aforementioned evidence system.
7. Conclusion: A Troubleshootable and Accountable Agent Engineering Mindset
From directory structures, prompt assembly, the three-ledger evidence system, expert plugins, to the identity quartet, the reliability of an agent system does not depend on how smart the model is, but on whether these engineering details are thoroughly designed. Three recommendations for practitioners:
- When working with any agent system, first understand its file layout and prompt assembly path. Treat the “complete pre-request context” as your primary debugging target.
- Replicate the “three ledgers + dual-track comparison” evidence design: session logs, file history, and trace audits each have their roles; use self-reports vs. facts comparison to locate hallucinations.
- Before launch, you must resolve persona conflict priorities and fallback strategies, using file-based identity management to ensure long-term consistency.
When every action of an agent has evidence and every state has ownership, it truly transforms from a “demo” into a “production tool.”
