跪拜 Guibai
← Back to the summary

A Four-Part AI Coding Spec That Enforces DDD Layers, Auto-Review, and Test Compliance

Practice yields real knowledge

This article is based on the internal project practices of our training camp, summarized for everyone's learning and reference.

Recently, a fan went for an interview and was asked how to do AI programming; their answer was too shallow.

After reading this article, I believe you will have a new understanding of AI programming.

Because the vast majority of students in our training camp develop based on Trae, we use Trae as an example.

If you develop using Claude or Codex, you need to place these files in .claude and also do some compatibility work.

image.png

You can directly make requests to the AI, for example:

I want to reuse Trae's AI programming specifications in Claude. Please provide a plan and implement it. First, confirm the plan with me, and after I confirm, you can proceed.

To learn more, feel free to connect with me, WeChat: wangzhongyang1993

Main Text Begins

After reading this document, you will definitely understand how the project specifications operate and know which tool to use in which scenario.


I. Why Build This Specification

Pain Points

In AI-assisted development, the following problems are common:

  1. Layer Confusion: The AI does not understand project layering constraints, and the generated code often makes cross-layer calls (Handler directly operates the database, Service introduces the HTTP framework).
  2. Uncontrollable Quality: The code produced by the AI lacks tests, has non-standard comments, and misses error handling, requiring repeated manual correction each time.
  3. Disconnect Between Planning and Execution: The AI writes code directly without a plan review phase, causing directional errors to be discovered too late.
  4. Context Pollution: A large number of retrieval and analysis tasks are executed in the main conversation, crowding the context window and reducing the AI's attention to core tasks.
  5. Inconsistent Team Standards: Code produced by different developers using AI has inconsistent styles, making maintenance difficult.

Solution Approach

Through four types of configurations under the .trae/ directory, team standards are solidified into constraints executable by the AI:

Configuration Type Directory Function Trigger Method
Rules .trae/rules/ Coding standards, layering constraints Automatically injected into context each conversation
Skills .trae/skills/ Standardized processes (generate plans, layer checks) Developer manually calls /command
Subagents .trae/agents/ Quality gates with independent context (plan review, test compliance) SOLO Agent automatically matches and calls
Hooks .trae/hooks.json Pre-commit specification reminders Automatically triggered when user sends a message

Core Principle: Let the AI automatically execute the correct process at the right time, rather than relying on humans to remind it every time.


II. Directory Structure

    .trae/
    ├── README.md                          # This document (comprehensive specification introduction)
    ├── hooks.json                         # Hook configuration (pre-commit reminders)
    │
    ├── rules/                             # Rule files (automatically loaded each conversation)
    │   ├── project_rules.md               #   Project general rules (tech stack, coding rules, documentation conventions)
    │   ├── handler.md                     #   Handler layer rules (api/handler/)
    │   ├── service.md                     #   Service layer rules (internal/service/)
    │   ├── repository.md                  #   Repository layer rules (internal/repository/)
    │   ├── domain.md                      #   Domain layer rules (internal/ragplatform/domain/)
    │   ├── milvus.md                      #   Milvus retrieval core rules (internal/milvus/)
    │   ├── rag.md                         #   RAG orchestration layer rules (internal/rag/)
    │   └── frontend.md                    #   Frontend rules (admin/src/)
    │
    ├── skills/                            # Skills (manually called by developer)
    │   ├── gen-plan/                      #   Generate standardized development plan
    │   │   ├── SKILL.md                   #     Skill definition and execution flow
    │   │   ├── template.md                #     Plan document template
    │   │   └── examples/
    │   │       └── example-feature.md     #     Complete example
    │   └── layer-check/                   #   Layer dependency check
    │       ├── SKILL.md                   #     Skill definition and execution flow
    │       └── layer_rules.json           #     Layer rule configuration (layer mapping, allowed/forbidden dependencies)
    │
    └── agents/                            # Subagents (automatically called by SOLO Agent)
        ├── plan-review.md                 #   Document plan review subagent
        └── test-compliance.md             #   Test and compliance detection subagent

III. Rule Files (Rules)

3.1 Mechanism

All Markdown files under .trae/rules/ are always-applied—automatically loaded into the context at the start of each AI conversation and effective throughout. The AI will automatically comply with the corresponding layer's rules when editing code.

3.2 Rule File Overview

File Scope Core Constraints
project_rules.md Entire project Tech stack, commit standards, documentation conventions, layering general rules, prohibited operations
handler.md api/handler/ Do not touch DB/Model/Milvus/Config, request-response isolation, DTO isolation
service.md internal/service/, internal/ragplatform/application/ Do not touch HTTP, constructor injection, transaction boundaries, error wrap
repository.md internal/repository/, internal/ragplatform/repository/ Do not return *gorm.DB, do not depend on upper layers
domain.md internal/ragplatform/domain/ Zero dependencies (currently relaxed, enforced after DDD refactoring)
milvus.md internal/milvus/ Do not depend on API/Service/Repository, pluggable strategy
rag.md internal/rag/ Orchestration layer, unaware of Web, distinct from milvus layer
frontend.md admin/src/ Five-layer separation of pages/components/services/types/config, prohibit components from directly calling fetch

3.3 Layer Dependency Direction

                        ┌──────────┐
                        │   cmd    │  Program entry (assembly point, can depend on all internal packages)
                        └────┬─────┘
                             │
              ┌──────────────┼──────────────┐
              ▼              ▼              ▼
        ┌──────────┐  ┌───────────┐  ┌───────────┐
        │ router   │  │ ragrouter │  │  handler  │  HTTP routing layer
        └────┬─────┘  └─────┬─────┘  └─────┬─────┘
              │              │              │
              │              │         ┌────┴─────┐
              │              │         ▼          ▼
              │              │    ┌────────┐ ┌─────────┐
              │              │    │response│ │middleware│
              │              │    └────────┘ └────┬────┘
              │              │                    │
              │              │              ┌─────┴─────┐
              │              │              │   auth    │
              │              │              └─────┬─────┘
              │              │                    │
              │              ▼                    │
              │         ┌──────────┐              │
              └────────►│ service  │◄─────────────┘
                        └────┬─────┘
                             │
              ┌──────────────┼──────────────┐
              ▼              ▼              ▼
        ┌──────────┐  ┌───────────┐  ┌───────────┐
        │repository│  │   model   │  │   rag     │  Business/Data layer
        └────┬─────┘  └───────────┘  └─────┬─────┘
             │                             │
             ▼                             ▼
        ┌──────────┐                 ┌───────────┐
        │  model   │                 │  milvus   │  Core/Foundation layer
        └──────────┘                 └───────────┘

Core BLOCK Rules (violations will be intercepted by layer-check):

Source Layer Forbidden Dependencies Reason
handler repository, model, milvus Handler does not touch DB, isolates with DTO
service handler, response, milvus Service is unaware of HTTP, retrieval decoupled via interface
repository service, handler, milvus Data layer does not inversely depend on business
milvus handler, service, repository, model Retrieval core isolated, does not touch DB

IV. Skills

4.1 Mechanism

Skills are standardized processes manually called by the developer. Triggered by entering /skill_name in the AI conversation input box. The Skill executes step-by-step according to predefined steps, ensuring no process steps are missed.

4.2 gen-plan: Generate Development Plan

Attribute Value
Call Method /gen-plan
Trigger Timing Manually called after developer describes requirements
Input Business requirement description
Output Standardized development plan document (saved to Docs/)

Execution Flow:

  1. Understand requirements → 2. Read project specifications → 3. Determine layer placement → 4. Design interface contract → 5. Formulate testing requirements → 6. Write acceptance checklist → 7. Output document → 8. Prompt for review

After producing the plan, the SOLO Agent will automatically prompt to call the plan-review subagent for review.

4.3 layer-check: Layer Dependency Check

Attribute Value
Call Method /layer-check
Trigger Timing Manually called after code writing is complete
Input Current diff (auto-acquired) or specified files
Output Layer check report (BLOCK / needs-review / Pass)

Check Logic:

  1. Read layer_rules.json → 2. Get diff files → 3. Extract imports → 4. Map to layers → 5. Check dependency direction → 6. Output report

Judgment Rules:

4.4 layer_rules.json Configuration Description

{
  "layers": { ... },        // File path → Layer mapping (29 layers)
  "allowed": { ... },       // Allowed dependencies (12 core layers configured, rest go to needs-review)
  "forbidden_cross": { ... }, // Forbidden dependencies (4 core BLOCK rules)
  "ignore": [ ... ]         // Ignored files (test files, vendor, etc.)
}

Design Principle: Core DDD layers (handler/service/repository/milvus) have precise allowed + forbidden_cross (hard gate), infrastructure layers go to needs-review (soft reminder). Do not over-constrain before DDD refactoring is complete.


V. Subagents

5.1 Mechanism

Subagents are specialized agents automatically called by the SOLO Agent. The SOLO Agent automatically matches based on user intent and the subagent's description field, deciding whether to delegate the task.

Subagents have independent context windows, and the intermediate reasoning and execution process does not pollute the main conversation history, suitable for tasks requiring extensive retrieval and analysis but only needing to return results.

5.2 plan-review: Document Plan Review

Attribute Value
File agents/plan-review.md
Auto-triggered After gen-plan produces a plan, when developer requests review of planning documents
Available Tools Read
Output Review report (Pass / Conditional Pass / Fail)

Review Content:

  1. Technical Feasibility: Tech stack consistency, layer placement compliance, interface contract completeness, resource reasonableness
  2. Risk Identification: Architectural risk, data risk, security risk, dependency risk (each marked High/Medium/Low)
  3. Test Plan Supplementation: Automatically supplement boundary cases (null/out-of-bounds/concurrency/idempotency), exception cases (infrastructure unavailable/network anomaly/permission anomaly), performance test suggestions

5.3 test-compliance: Test and Compliance Detection

Attribute Value
File agents/test-compliance.md
Auto-triggered After code writing is complete, before submitting MR, when compliance detection is needed
Available Tools Read, Terminal, Edit
Output Comprehensive test compliance report (Pass / Conditional Pass / Fail)

Detection Content:

  1. Compilation Check: go build ./... / npm run build
  2. Execute Tests: go test ./... / npx vitest run (record coverage)
  3. Compliance Detection: General standards (Chinese comments, error checks, no hardcoded keys) + Layer standards (reference rules/ rule files) + Layer dependency check
  4. Auto-fix: Missing comments, unwrapped errors, non-standard naming can be directly fixed; architectural violations provide fix suggestions

VI. Hooks

6.1 Mechanism

hooks.json is automatically triggered when the user sends a message, injecting project specification reminders into the AI.

6.2 Current Configuration

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "prompt",
            "prompt": "The project uses Go(Hertz) + Next.js dual stack. Before modifying backend code, confirm compliance with layering rules such as .trae/rules/handler.md; before modifying frontend, confirm compliance with .trae/rules/frontend.md. New code must include tests, comments in Chinese."
          }
        ]
      }
    ]
  }
}

Every time a message is sent, the AI receives this reminder, ensuring it is aware of layering rules and testing requirements before handling any task.


VII. Complete Workflow

Taking "add an alert query interface" as an example, the complete process is as follows:

    1. Developer describes requirements verbally
       "Implement a paginated query interface for the knowledge base alert list, supporting filtering by status and severity"

    2. Generate Plan (skill)
       /gen-plan
       → AI generates development plan according to template, including layer placement, interface contract, testing requirements, acceptance checklist
       → Document saved to Docs/

    3. Review Plan (subagent, auto-triggered)
       → SOLO Agent automatically calls plan-review
       → Technical feasibility analysis, risk identification, test plan supplementation
       → Output review report

    4. Administrator Review
       → Manually confirm review report, proceed to development after passing

    5. Code Writing
       → AI writes code according to handler.md / service.md / repository.md rules
       → Rules in rules/ are automatically effective throughout

    6. Layer Check (skill)
       /layer-check
       → Scan imports in diff files
       → Check if forbidden_cross is violated
       → BLOCK violations must be fixed

    7. Test Compliance (subagent, auto-triggered)
       → SOLO Agent automatically calls test-compliance
       → Compilation check → Execute tests → Compliance detection → Auto-fix
       → Output comprehensive report

    8. Submit MR
       → Submit code after all pass

VIII. Quick Start for Newcomers

8.1 First Contact with the Project

  1. Read this file to understand the specification system
  2. Read rules/project_rules.md to understand project general rules
  3. According to the code area you want to modify, read the corresponding layer rule file (e.g., read handler.md if modifying Handler)

8.2 Start Developing a New Feature

  1. Describe requirements verbally in the AI conversation
  2. Enter /gen-plan to generate a development plan
  3. Wait for plan-review subagent to automatically review
  4. Start coding after administrator review passes
  5. After coding is complete, enter /layer-check to check layers
  6. Wait for test-compliance subagent to automatically detect
  7. Submit MR after passing

8.3 Modifying Layer Rules

  1. Edit the corresponding .md file under rules/ (modify constraint description)
  2. Edit skills/layer-check/layer_rules.json (modify allowed / forbidden_cross)
  3. Both must be consistent—the constraints described in md and the check rules configured in json cannot contradict each other

8.4 Adding a New Subagent

  1. Create a <name>.md file under agents/
  2. Fill in name, description, tools according to frontmatter format
  3. Write system prompt (role, workflow, behavioral boundaries, output format)
  4. The description should be specific to avoid false triggers or missed triggers

IX. Technical Debt Annotations

The following issues have been identified and annotated, to be gradually fixed during the DDD refactoring process:

Issue Location Severity Description
config inversely depends on rag config/config.go Medium Imports internal/rag/governance, should inline config struct
middleware depends on repository middleware/auth.go Medium Should encapsulate user queries through auth package
handler depends on model (legacy) Some handler files Low Should gradually isolate with DTO
DDD refactoring incomplete internal/ragplatform/ application layer is an empty shell, domain layer constraints relaxed

New code must not continue the above violation patterns.


Learn More

To learn more, feel free to connect with me, WeChat: wangzhongyang1993

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

花鱼 1 likes

[Awesome][Awesome]