


























你或许会觉得奇怪,在一本讨论前沿AI编程的书中,为什么我们要花一整章的篇幅,来讨论“写文档”这件听起来无比传统,甚至有些“老掉牙”的事情?
答案很简单:在AI时代,文档的价值,发生了核聚变式的跃迁。
过去,文档是“写给人看的”。它的主要作用是团队内的知识传递和项目交接。它很重要,但对于代码的“执行”本身,没有直接影响。一个程序员完全可以不读任何文档,仅凭代码本身去理解和修改系统(尽管这通常是灾难的开始)。
现在,情况完全不同了。AI时代的文档,首先是“写给机器看的”。它不再是代码的“附属品”,而是代码的“法律”和“生成指令”。 它从一个被动的“说明书”,进化成了一个主动的“约束器”。
一个维护良好的项目文档,对于AI来说,就如同物理世界中的“牛顿定律”。它不是一个“建议”,而是一个必须遵守的、构成其世界观的底层规则。当你在会话中反复引用这份文档时,它在AI的注意力权重中,会被提升到最高级别,甚至超过你当前输入的指令。
本章,我们将彻底改变你对“写文档”的认知。你将学会,如何不把它当成一种负担,而是当成你驾驭AI最强大的“缰绳”。
在开始构建文档之前,我们必须先彻底粉碎一个危险的幻觉——很多人认为,既然AI拥有超长的上下文记忆能力,我只需要在对话开始时告诉它一些规则,它就能一直记住。我为什么还需要多此一举去维护外部文档?
这种想法,是导致AI编程项目走向混乱和失控的头号元凶。依赖对话历史,无异于将你的摩天大楼建在沙滩上。
对话历史是易失的。一次意外的浏览器刷新、一次网络中断,或者你主动清空会话(我们后面会讲到,这是一种必要操作),所有的上下文都会瞬间消失。你将不得不像一个失忆症患者一样,重新向AI描述你的整个项目,这个过程既低效又极易出错。
更糟糕的是,对话历史是极易被污染的。在解决一个复杂问题的过程中,你和AI会进行大量的试错、走过很多弯路。这些错误的尝试、被否定的方案、调试用的console.log,都会作为“垃圾信息”永远地留存在对话历史中。当AI在后续生成代码时,这些垃圾信息会像“背景噪音”一样,干扰它的判断,甚至可能让它重新拾起一个早已被证明是错误的想法。
【实战对比】
CHANGELOG.md中记录下:“版本1.2.1:修复了因异步更新导致的状态不一致问题。核心解决方案:将状态更新从useEffect迁移至事件回调函数中。” 当你开始新功能时,你只需要让AI重新读取这份干净的、结论性的文档。对话历史是线性的、局部的。它只记录了你和AI之间“你一言我一语”的交互过程。它无法呈现项目的“全貌”和“最终状态”。
当项目变得复杂,涉及到多个模块时,你可能会在不同的时间点,和AI讨论不同的部分。
这三段对话,散落在长长的历史记录中。当你下周一再让AI写一个涉及前后端交互的功能时,它能否准确地将这三段“孤立”的记忆整合起来?答案是:非常困难。它很可能会忘记周三确定的UI库,而使用另一个它更“熟悉”的库来生成代码。
项目文档则提供了权威的、全局的视角。ARCHITECTURE.md这份文件,就是项目的“宪法”。无论何时何地,它都以最终的、不容置疑的形式,规定了数据库、UI库和API的最终设计。AI每一次行动前,都必须回到这里,“拜读”法典,而不是去翻阅那些充满了杂音的“法庭辩论记录”。
如果你的项目不只你一个人,依赖对话历史将直接导致协作的崩溃。
你的对话历史,是你的个人“私有财产”。团队里的其他成员无法访问,也无法理解你和AI之间达成的那些“默契”和“约定”。当你的同事B接手你的工作,他开启一个全新的会话,AI对他来说,就是一张白纸。他可能会让AI生成完全不符合你之前约定的代码风格,或者使用一个已经被你明确禁用的第三方库。
项目文档则是团队共享的“公共契约”。任何人,无论是人还是AI,在加入项目的第一天,都必须先阅读这份文档。它确保了整个团队(包括所有的人类和AI实例)对项目的核心规则,拥有完全一致的理解。这使得大规模、多人的AI协同开发成为可能。
对话历史是无法被版本控制的。你无法知道在两周前的某个下午,你和AI确定的那个重要架构决策,和今天的版本有什么不同。当项目出现问题,需要回溯和排查时,翻阅成千上万行的对话记录,是一场不可能完成的任务。
项目文档(.md文件)则是代码的一部分。它可以,也必须和你的.js、.go文件一样,被纳入Git的版本控制系统。
ARCHITECTURE.md,来评审架构变更的合理性。git blame,快速定位到是哪一次文档变更引入了误导性的信息。把文档像代码一样管理,这是AI时代工程师的核心素养。
我们在第一章讲过,对抗AI“确认偏误”最有效的武器,就是果断清空会话(/clear),强行“重置”它的思维。
如果你依赖对话历史,你就会陷入一个两难的境地:
这让你不敢,也无法使用这个最强大的纠错工具。
而有了项目文档,你就获得了终极的“自由”。你可以随时、随地、毫无心理负担地执行/clear。因为你知道,项目的所有“记忆精华”,都已经被安全地、结构化地保存在了那几个Markdown文件中。重置之后,你只需要一条简单的指令:“请重新阅读项目根目录下的所有.md文档,并根据CHANGELOG.md的最新条目,继续我们之前的工作。”
AI瞬间满血复活,恢复到最清醒、最专注、完全不受历史垃圾信息污染的“出厂设置”状态。
结论: 放弃对对话历史的任何幻想。它不是你的资产,而是你的负债。从今天起,养成一个铁的纪律:任何重要的决策、任何核心的规则、任何阶段性的成果,都必须在第一时间,沉淀到你的项目文档中。
让文档成为你和AI之间唯一的、永恒的、不可动摇的“单源真相”。
CLAUDE.md、ARCHITECTURE.md、CHANGELOG.md理论说清楚了,现在我们来点实际的。一个复杂的商业项目,可能需要很多种文档。但根据我的实践经验,有三份文档是绝对必要的,它们构成了AI约束体系的“三驾马车”。
我以我常用的AI模型Claude为例,将其中一份命名为CLAUDE.md。你可以根据你使用的模型(如GPT4.md)进行调整。
这三份文档分别是:
CLAUDE.md(或 AGENTS.md):AI行为准则与角色设定。 它是AI的“员工手册”,规定了它能做什么、不能做什么,以及它应该扮演的角色。ARCHITECTURE.md:项目架构与技术决策蓝图。 它是项目的“技术宪法”,记录了所有关键的技术选型、设计模式和接口契约。CHANGELOG.md:项目演进与状态记忆日志。 它是项目的“航行日志”,让AI能够随时“记起”项目已经完成了什么、正处在哪个阶段。让我们逐一来看如何创建和维护它们。
CLAUDE.md:AI的“员工手册”这份文档的核心目标,是为AI设定一个明确的“人设”和一套不可逾越的“行为红线”。它能极大地减少AI在交互过程中的“废话”和“不确定性”,让它的行为更像一个专业的、受过训练的工程师。
这份文档应该包含什么内容?
any类型”、“严禁在UI组件中直接进行DOM操作”等。【模板:CLAUDE.md】
# AI Agent Directives: Project "Phoenix"
This document defines your role, rules, and constraints for working on Project "Phoenix". You must adhere to these directives in all your responses.
## 1. Persona: Senior Full-Stack Engineer
You are a Senior Full-Stack Engineer with 10 years of experience in building complex, cross-platform enterprise applications. Your expertise lies in Go for the backend and TypeScript/React for the frontend. You value clean code, robust architecture, and comprehensive testing.
## 2. Core Directives
- Language: All code, comments, and commit messages must be in English.
- Clarity over cleverness: Write simple, self-explanatory code. Avoid obscure language features.
- No Apologies: Do not apologize or state that you are an AI. Be confident and direct.
- Code Blocks: All code snippets must be enclosed in markdown code blocks with the correct language identifier (e.g., ```go, ```typescript).
- Assume I have context: Do not repeat large blocks of code from our previous conversation unless I ask you to.
## 3. Tech Stack Constraints (The ONLY allowed technologies)
## Backend
- Language: Go (version 1.21)
- Web Framework: Gin (v1.9.1)
- Database: PostgreSQL 15
- ORM: GORM (v1.25.5)
- Testing: Go's built-in testing package. No third-party testing frameworks.
## Frontend
- Language: TypeScript (v5.1)
- Framework: React (v18.2)
- State Management: Zustand
- Styling: Tailwind CSS
- Build Tool: Vite
## 4. Absolute Prohibitions (Things you must NEVER do)
- DO NOT access the internet or any external real-time information.
- DO NOT use the `any` type in TypeScript. Use `unknown` for type-unsafe values and perform explicit type checking.
- DO NOT write API calls (`fetch`, `axios`) directly inside React components. All data fetching logic must be encapsulated in custom hooks (e.g., `useUserData`).
- DO NOT use default exports (`export default`). Always use named exports (`export const ...`).
- DO NOT suggest any new libraries or technologies not listed in the Tech Stack Constraints. If a task seems impossible with the current stack, state that and ask for clarification.
## 5. Output Formatting
- When providing code, first give a brief, one-sentence explanation of the change.
- When creating a new file, always provide the full file path, e.g., `// src/components/UserProfile.tsx`.
- If you need me to make a decision, present the options as a numbered list with pros and cons for each.
---
By acknowledging this document, you agree to act as a professional engineering partner on Project "Phoenix".
如果说CLAUDE.md是管“行为”的,那么ARCHITECTURE.md就是管“结构”的。它定义了项目的宏观设计,是所有模块和代码必须遵守的“蓝图”。
这份文档应该包含什么内容?
User、Product、Order等。【模板:ARCHITECTURE.md】
# Project "Phoenix" - Architecture Document
This document is the Single Source of Truth for the architecture of Project "Phoenix". All code must conform to the principles outlined here.
## 1. Project Overview
Project "Phoenix" is an internal dashboard for managing customer support tickets. It allows support agents to view, update, and close tickets.
## 2. Architecture Diagram (High-Level)
```mermaid
graph TD
A[Browser/Frontend] -- HTTPS/JSON --> B(Backend API - Go/Gin);
B -- SQL --> C(PostgreSQL Database);
```
## 3. Core Design Principles
- Layered Architecture: The application is strictly divided into three layers. There should be no cross-layer imports.
- Presentation Layer (React Components): Responsible for UI only. "Dumb" components.
- Business Logic Layer (React Hooks / Go Services): Handles application logic and state.
- Data Access Layer (Go Repositories): Communicates with the database.
- Stateless Backend: The Go backend API must be stateless. All session/user state is managed by the client using JWTs.
- Unidirectional Data Flow (Frontend): React components follow a unidirectional data flow. State flows down, events flow up.
## 4. Directory Structure
```
/
├── backend/
│ ├── api/ # Gin handlers
│ ├── cmd/ # Main application entrypoint
│ ├── internal/
│ │ ├── model/ # GORM models
│ │ ├── repository/ # Data access logic
│ │ └── service/ # Business logic
│ └── go.mod
└── frontend/
├── public/
├── src/
│ ├── api/ # API client functions
│ ├── components/ # Reusable UI components
│ ├── hooks/ # Custom React hooks (Business Logic)
│ ├── pages/ # Page-level components
│ └── App.tsx
└── package.json
```
## 5. API Contract
- Endpoint Naming: All endpoints are plural nouns, e.g., `/api/v1/tickets`.
- Authentication: All requests to `/api/v1/*` must include an `Authorization: Bearer <JWT>` header.
- Standard Success Response (200 OK):
```json
{
"success": true,
"data": { ... }
}
```
- Standard Error Response (4xx/5xx):
```json
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "A human-readable error message."
}
}
```
## 6. Core Data Models
## Ticket
- `id`: UUID (Primary Key)
- `title`: string
- `description`: text
- `status`: string (`'open'`, `'in_progress'`, `'closed'`)
- `priority`: string (`'low'`, `'medium'`, `'high'`)
- `created_at`: timestamp
- `updated_at`: timestamp
这份文档最简单,也最容易被忽略,但它在实际开发中,起着至关重要的“记忆锚点”作用。它的核心目标,是解决AI“记不住我们上次聊到哪了”的问题。
每当你完成一个重要的功能、修复一个关键的Bug,或者做出一个影响后续开发的决策时,你都应该花10秒钟,在这里记录下来。
这份文档应该包含什么内容?
【模板:CHANGELOG.md】
# Changelog - Project "Phoenix"
This log tracks the development progress and key decisions.
2023-10-27
- Implemented: User authentication endpoints (`/login`, `/register`) are complete on the backend. JWT generation and validation logic is in place.
- Decision: Frontend will store the JWT in `localStorage` for this internal tool. Security implications are accepted.
- Next Step: Begin work on the frontend login page.
2023-10-26
- Completed: Backend project setup with Gin and GORM.
- Completed: Database schema for `users` and `tickets` tables defined in `backend/internal/model`.
- Established: Initial connection to the PostgreSQL database is working.
---
如何使用这三份文档?
很简单。在每次开启一个新的开发会话,或者在执行/clear重置之后,你的第一条指令永远是:
"Please read and fully acknowledge the rules and context from
CLAUDE.md,ARCHITECTURE.md, andCHANGELOG.md. Based on the latest entry in the changelog, our next task is to build the frontend login page. Let's start by creating the filefrontend/src/pages/LoginPage.tsx."
这条指令,就像一个“系统启动盘”,瞬间将AI的大脑,加载了你项目的所有核心规则、完整架构和最新进度。它将一个“通用”的大模型,变成了一个专属于你项目的“领域专家”。
有了文档骨架,我们还需要掌握如何填充它们。编写给AI看的约束指令,是一门艺术,它和写给人类的文档有本质区别。人类能理解模糊、含蓄和暗示,而AI需要的是精确、无歧义、接近代码逻辑的语言。
以下是编写高效约束指令的五个核心原则:
不要用建议或描述的语气,要用命令的语气。
export const ...). Do not use default exports (export default)."使用Must, Must not, Always, Never, Do not这些词,能极大地提升指令在AI模型中的权重。
光说“不要做什么”是不够的,最好能提供一个“正确的该怎么做”的示例。这能帮助AI更快地学习和匹配你想要的模式。
// In MyComponent.jsx
function handleClick() {
const complexData = someData.map(...).filter(...);
// ... more logic
}
// In useMyLogic.js (Hook)
export function useMyLogic() {
const processData = () => { ... };
return { processData };
}
// In MyComponent.jsx
const { processData } = useMyLogic();
避免使用“好”、“快”、“简单”这类主观的、无法量化的词。尽可能用数字和具体的标准来定义。
模糊: "Functions should not be too long."
精确: "Constraint: No single function should exceed 50 lines of code. If it does, you must suggest refactoring it into smaller helper functions."
模糊: "API response should be fast."
精确: "Performance Budget: All P1 API endpoints must have a median response time under 100ms."
当你设定的规则是基于某个行业标准或最佳实践时,明确地指出来。这会增加约束的“权威性”。
对于一些复杂的逻辑,可以使用“如果...那么...”的句式,来定义一个场景触发的自动化行为。
通过以上五个原则,你可以将你的项目文档,从一本模糊的“指导手册”,锻造成一套精确的“法律条文”。AI在阅读这些指令时,会像编译器解析代码一样,将其转化为自己行为模型中不可动摇的底层规则。
这就是“把话说死”的真正含义。你用文档的“僵化”和“不容置疑”,换来了AI执行的“稳定”和“高度可预测”。在这场人机共生的舞蹈中,你不是在限制AI的创造力,而是在为它的巨大能量,构建一个安全的、能创造出真正价值的舞台。
为了方便你立刻开始实践,这里提供一个整合了上述所有理念的、可以直接复制到你项目根目录的文档骨札。你只需要根据你的具体项目,填充其中的内容即可。
项目根目录结构:
/
├── .docs/
│ ├── AGENTS.md // Or CLAUDE.md, GPT4.md etc.
│ ├── ARCHITECTURE.md
│ └── CHANGELOG.md
├── src/
└── ...
# AI Agent Directives: [Your Project Name]
> Instructions for Human: Before starting a new coding session with the AI, copy the content of this file and paste it as the first message.
This document defines your role, rules, and constraints. You must adhere to these directives in all your responses.
## 1. Persona
You are a [e.g., Senior Backend Engineer specializing in distributed systems]. You prioritize [e.g., code simplicity, performance, and testability].
## 2. Core Directives
- Language: All code and text must be in English.
- Clarity: Write clear, self-documenting code.
- No Apologies: Be direct and confident. Do not state you are an AI.
- Code Blocks: Always use markdown code blocks with language identifiers.
## 3. Tech Stack Constraints (The ONLY allowed technologies)
- Language: [e.g., Go 1.21]
- Framework: [e.g., Gin v1.9.1]
- Database: [e.g., PostgreSQL 15]
- ... (add other categories like Frontend, Testing, etc.)
## 4. Absolute Prohibitions (Things you must NEVER do)
- DO NOT access the internet.
- DO NOT use `[e.g., any type in TypeScript]`.
- DO NOT `[e.g., write business logic in UI components]`.
- DO NOT suggest any technologies not listed above.
## 5. Output Formatting
- Provide a brief explanation before code blocks.
- Use full file paths when creating new files.
- Present options as a numbered list with pros and cons.
# Architecture Document: [Your Project Name]
> Instructions for Human: After providing the agent directives, you should instruct the AI to read and acknowledge this architecture document.
This is the Single Source of Truth for the project's architecture.
## 1. Project Overview
[A brief, one-paragraph description of what the project does and its goals.]
## 2. Architecture Diagram
```mermaid
[Paste your Mermaid.js or ASCII diagram here]
```
## 3. Core Design Principles
- Principle 1: [e.g., Layered Architecture. Describe the layers and their responsibilities.]
- Principle 2: [e.g., Stateless Services. Explain how state is managed.]
- ...
## 4. Directory Structure
```
[Paste the agreed-upon directory structure here.]
```
## 5. API Contract
- Endpoint Naming: [e.g., Plural nouns, kebab-case.]
- Authentication: [e.g., JWT in Authorization header.]
- Standard Response Formats: [Provide JSON examples for success and error cases.]
## 6. Core Data Models
## [Model Name 1]
- `id`: [type] ([constraints])
- `name`: [type]
- ...
## [Model Name 2]
- ...
# Changelog: [Your Project Name]
> Instructions for Human: After the AI has acknowledged the first two documents, provide the latest entry from this changelog to give it the current context. Update this file after every significant milestone.
[YYYY-MM-DD]
- Implemented: [Describe the feature/fix.]
- Decision: [Record any important decisions made.]
- Next Step: [State the immediate next task.]
[Previous YYYY-MM-DD]
- ...
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。