doc-authoring

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Documentation Authoring

文档编写

Generate accurate, maintainable documentation from systematic codebase analysis. Every document is classified by type, written to strict rules, and verified against the code.
基于系统化代码库分析生成准确、可维护的文档。每份文档都会按类型分类,遵循严格规则编写,并与代码进行验证。

Workflow Router

工作流路由

Determine the workflow type before starting. This drives which phases apply, which templates to use, and whether to write from scratch or edit existing docs.
Do any docs already exist?
  |
  NO --> GREENFIELD DOCS (new project, no docs)
  |       Phases: Analyze -> Plan -> Write -> Verify
  |
  YES --> What type of change?
           |
           +-> Code changed, docs not updated
           |     --> DOC REFRESH (brownfield)
           |     Phases: Analyze -> Audit Existing -> Drift Detection -> Write (delta) -> Verify
           |
           +-> New feature/module needs documenting
           |     --> DOC ENHANCEMENT (brownfield)
           |     Phases: Analyze -> Audit Existing -> Plan (delta) -> Write -> Verify
           |
           +-> Docs exist but quality/structure is poor
           |     --> DOC AUDIT (brownfield)
           |     Phases: Analyze -> Audit Existing -> Plan -> Rewrite -> Verify
           |
           +-> User wants a specific doc rewritten
           |     --> TARGETED REWRITE (brownfield)
           |     Phases: Analyze -> Audit Existing (single doc) -> Write (replace) -> Verify
           |
           +-> User wants a specific new doc (README, API ref, etc.)
           |     --> TARGETED NEW DOC
           |     Phases: Analyze -> Write (specific) -> Verify
           |
           +-> Version bump or migration
                 --> VERSION UPDATE (brownfield)
                 Phases: Analyze -> Audit Existing -> Drift Detection -> Write (delta) -> Verify
Signal detection:
Signal in requestLikely type
"Write docs", "document this", "add documentation" (no docs exist)Greenfield
"Write docs", "document this" (docs already exist)Doc Enhancement
"README", "write a README" (none exists)Targeted New Doc
"Rewrite the README", "redo the README" (one exists)Targeted Rewrite
"API docs", "API reference", "document the API"Targeted New Doc or Enhancement
"Architecture", "design doc", "how does this work"Targeted New Doc
"Docs are outdated", "update the docs", "sync the docs"Doc Refresh
"Review the docs", "audit", "docs are wrong"Doc Audit
"Upgrade to v2", "migration guide", "breaking changes"Version Update
"Contributing guide", "CONTRIBUTING.md"Targeted New Doc
"Changelog", "release notes"Targeted New Doc
"Developer guide", "onboarding"Targeted New Doc

开始前先确定工作流类型。这将决定适用的阶段、使用的模板,以及是从零开始编写还是编辑现有文档。
是否已有文档?
  |
  否 --> 新项目文档(全新项目,无现有文档)
  |       阶段:分析 -> 规划 -> 编写 -> 验证
  |
  是 --> 变更类型是什么?
           |
           +-> 代码已变更,文档未更新
           |     --> 文档刷新(存量项目)
           |     阶段:分析 -> 审计现有文档 -> 差异检测 -> 编写(增量) -> 验证
           |
           +-> 新功能/模块需要文档
           |     --> 文档增强(存量项目)
           |     阶段:分析 -> 审计现有文档 -> 规划(增量) -> 编写 -> 验证
           |
           +-> 文档存在但质量/结构不佳
           |     --> 文档审计(存量项目)
           |     阶段:分析 -> 审计现有文档 -> 规划 -> 重写 -> 验证
           |
           +-> 用户希望重写特定文档
           |     --> 定向重写(存量项目)
           |     阶段:分析 -> 审计现有文档(单文档) -> 编写(替换) -> 验证
           |
           +-> 用户需要特定新文档(README、API参考等)
           |     --> 定向新增文档
           |     阶段:分析 -> 编写(特定内容) -> 验证
           |
           +-> 版本升级或迁移
                 --> 版本更新(存量项目)
                 阶段:分析 -> 审计现有文档 -> 差异检测 -> 编写(增量) -> 验证
信号识别:
请求中的信号可能的工作流类型
"Write docs"、"document this"、"add documentation"(无现有文档)新项目文档
"Write docs"、"document this"(已有文档)文档增强
"README"、"write a README"(无现有README)定向新增文档
"Rewrite the README"、"redo the README"(已有README)定向重写
"API docs"、"API reference"、"document the API"定向新增文档或文档增强
"Architecture"、"design doc"、"how does this work"定向新增文档
"Docs are outdated"、"update the docs"、"sync the docs"文档刷新
"Review the docs"、"audit"、"docs are wrong"文档审计
"Upgrade to v2"、"migration guide"、"breaking changes"版本更新
"Contributing guide"、"CONTRIBUTING.md"定向新增文档
"Changelog"、"release notes"定向新增文档
"Developer guide"、"onboarding"定向新增文档

Phase 0: Analyze Repository

阶段0:分析代码仓库

Always run this phase. Before writing anything, build a complete picture of the codebase. See references/repo-analysis.md for the full analysis method.
必须执行此阶段。 开始编写前,先全面了解代码库。完整分析方法请参考references/repo-analysis.md

What to discover

需要挖掘的信息

  1. Language and runtime: Identify from manifest files (package.json, pyproject.toml, go.mod, etc.)
  2. Framework and libraries: Scan dependencies for framework signatures
  3. Architecture: Directory layout, monorepo indicators, service boundaries
  4. Entry points: main() functions, CLI interfaces, HTTP servers, scripts
  5. Public interfaces: Exported functions, API endpoints, CLI commands
  6. Configuration: Environment variables, config files, feature flags
  7. Data models: ORM definitions, schemas, migrations
  8. Tests and CI: Test frameworks, CI/CD config, build commands
  9. Existing documentation: README, docs/ folder, inline docstrings, CLAUDE.md, wiki references
  10. Dependencies: External services, databases, APIs consumed
  1. 语言与运行时:从清单文件(package.json、pyproject.toml、go.mod等)识别
  2. 框架与库:扫描依赖项识别框架特征
  3. 架构:目录结构、单体仓库标识、服务边界
  4. 入口点:main()函数、CLI接口、HTTP服务器、脚本
  5. 公共接口:导出函数、API端点、CLI命令
  6. 配置:环境变量、配置文件、功能标志
  7. 数据模型:ORM定义、Schema、迁移文件
  8. 测试与CI:测试框架、CI/CD配置、构建命令
  9. 现有文档:README、docs/目录、内联文档字符串、CLAUDE.md、Wiki引用
  10. 依赖项:外部服务、数据库、调用的API

How to explore

探索方法

  • Read README.md and CLAUDE.md first (if they exist)
  • Read manifest files (package.json, pyproject.toml, go.mod, Cargo.toml, etc.)
  • Scan directory structure to identify modules and services
  • Read 2-3 key source files to absorb patterns and conventions
  • Check for existing doc infrastructure (Sphinx conf, JSDoc config, OpenAPI specs)
  • Look for CI config that builds or tests documentation
  • 先阅读README.md和CLAUDE.md(如果存在)
  • 阅读清单文件(package.json、pyproject.toml、go.mod、Cargo.toml等)
  • 扫描目录结构识别模块与服务
  • 阅读2-3个关键源文件了解模式与约定
  • 检查现有文档基础设施(Sphinx配置、JSDoc配置、OpenAPI规范)
  • 查看用于构建或测试文档的CI配置

Output: Repository Profile

输出:代码库概况

Produce a mental model (do not write a file unless requested):
Language: [language and version]
Framework: [framework and version]
Architecture: [monolith, microservices, library, CLI tool, etc.]
Entry points: [main files, CLI commands, HTTP servers]
Public API surface: [exported functions, endpoints, commands]
Config: [env vars, config files]
Test setup: [framework, runner command, coverage]
Existing docs: [what exists, what's missing, what's stale]
Doc infrastructure: [generators, linters, CI checks]
This profile informs every subsequent phase.

形成认知模型(除非用户要求,否则无需写入文件):
语言:[语言及版本]
框架:[框架及版本]
架构:[单体应用、微服务、库、CLI工具等]
入口点:[主文件、CLI命令、HTTP服务器]
公共API表面:[导出函数、端点、命令]
配置:[环境变量、配置文件]
测试设置:[框架、运行命令、覆盖率]
现有文档:[已存在内容、缺失内容、过时内容]
文档基础设施:[生成器、检查器、CI校验]
此概况将指导后续所有阶段。

Phase 1: Audit Existing Documentation (Brownfield Only)

阶段1:审计现有文档(仅存量项目)

Skip this phase for greenfield projects.
Before planning or writing anything, understand what documentation already exists and assess its state. This is the brownfield equivalent of exploring existing code before modifying it.
新项目跳过此阶段。
规划或编写前,先了解现有文档的状态。这相当于修改现有代码前先探索代码的存量项目流程。

Read every existing doc

阅读所有现有文档

For each doc file found in Phase 0:
  1. Read it fully. Do not skim. Absorb its structure, voice, and content.
  2. Classify its Diataxis type (Tutorial, How-to, Reference, Explanation, or Hybrid).
  3. Note its conventions: heading style, code block formatting, terminology, section ordering, tone.
  4. Assess accuracy by spot-checking 3-5 factual claims against source code.
  5. Assess completeness by comparing documented interfaces against actual public interfaces found in Phase 0.
针对阶段0中发现的每个文档文件:
  1. 完整阅读:不要略读,理解其结构、语气与内容。
  2. 按Diataxis类型分类(教程、操作指南、参考文档、说明文档或混合类型)。
  3. 记录约定:标题样式、代码块格式、术语、章节顺序、语气。
  4. 评估准确性:抽查3-5个事实性描述与源代码对比。
  5. 评估完整性:将已记录的接口与阶段0中发现的实际公共接口对比。

Existing doc inventory

现有文档清单

Build a mental inventory (do not write a file unless requested):
Existing Documentation Inventory
  [file path] | [diataxis type] | [accuracy: high/medium/low] | [completeness: high/medium/low]
  README.md   | hybrid          | medium (install cmd outdated) | low (missing API section)
  docs/api.md | reference       | low (3 endpoints missing)     | medium
  ...
形成认知清单(除非用户要求,否则无需写入文件):
现有文档清单
  [文件路径] | [Diataxis类型] | [准确性:高/中/低] | [完整性:高/中/低]
  README.md   | 混合类型          | 中等(安装命令过时) | 低(缺少API章节)
  docs/api.md | 参考文档       | 低(缺失3个端点)     | 中等
  ...

Identify what to preserve

确定需保留内容

Critical for brownfield. Existing docs may contain valuable content that cannot be reconstructed from code alone:
Content TypeExamplePreserve?
Domain knowledgeBusiness rule explanationsAlways
Design rationale"We chose X because Y"Always
User-authored contextGotchas, tips, warningsAlways
Custom sectionsProject-specific categoriesDefault yes
Historical notesMigration history, deprecation contextYes unless user says remove
Stale factsWrong version, renamed functionReplace with correct facts
Fabricated contentDocumented endpoint that doesn't existRemove
Dead referencesLinks to deleted filesRemove
Rule: When in doubt, preserve. You can always delete later; you cannot reconstruct domain knowledge the original author had.
存量项目的关键步骤。 现有文档可能包含无法从代码中重建的宝贵内容:
内容类型示例是否保留?
领域知识业务规则说明始终保留
设计依据"我们选择X是因为Y"始终保留
用户撰写的上下文注意事项、技巧、警告始终保留
自定义章节项目特定分类默认保留
历史记录迁移历史、弃用上下文保留,除非用户要求删除
过时事实错误版本、重命名函数替换为正确事实
虚构内容已记录但不存在的端点删除
无效引用指向已删除文件的链接删除
规则:存疑时保留。 后续可随时删除,但无法重建原作者的领域知识。

Brownfield conventions contract

存量项目约定契约

Extract the writing conventions from existing docs and follow them:
  • Heading style: What levels are used? Are they noun phrases or verb phrases?
  • Code block language tags:
    bash
    vs
    shell
    vs
    sh
    ?
    javascript
    vs
    js
    ?
  • Terminology: What terms does the project use? ("service" vs "server", "endpoint" vs "route", "config" vs "configuration")
  • Section ordering: What comes first? How are things grouped?
  • Tone: Formal or casual? First-person or impersonal?
Match existing conventions. Do NOT impose new conventions on a brownfield project unless the user explicitly requests a style change. Consistency within the existing docs is more valuable than adherence to an ideal standard.

从现有文档中提取写作约定并遵循:
  • 标题样式:使用哪些层级?是名词短语还是动词短语?
  • 代码块语言标签
    bash
    vs
    shell
    vs
    sh
    javascript
    vs
    js
  • 术语:项目使用哪些术语?("service" vs "server"、"endpoint" vs "route"、"config" vs "configuration")
  • 章节顺序:什么内容放在前面?内容如何分组?
  • 语气:正式还是随意?第一人称还是客观表述?
匹配现有约定。 除非用户明确要求修改风格,否则不要在存量项目中引入新约定。现有文档的一致性比遵循理想标准更重要。

Phase 2: Plan Documentation

阶段2:规划文档

Greenfield planning

新项目规划

Derive a full documentation plan from the repository analysis.
从代码库分析中推导完整的文档规划。

Diataxis classification

Diataxis分类

Every document must be classified as exactly ONE of four types. See references/diataxis-guide.md for full rules.
TypePurposeUser is...Voice
TutorialGuided learning experienceStudying"First, do x. Now do y."
How-to GuideSolve a specific problemWorking"To achieve x, do y."
ReferenceTechnical description for lookupWorking"Returns x. Accepts y."
ExplanationContext, reasoning, backgroundStudying"The reason for x is..."
Critical rule: Never mix types. A tutorial must not explain. A reference must not instruct. A how-to must not teach. Link between types instead.
每个文档必须严格归类为以下四种类型之一。完整规则请参考references/diataxis-guide.md
类型目的用户角色语气
教程引导式学习体验学习者"首先,执行x。接下来执行y。"
操作指南解决特定问题从业者"要实现x,请执行y。"
参考文档用于查阅的技术描述从业者"返回x。接受y作为参数。"
说明文档上下文、依据、背景知识学习者"x的原因是..."
关键规则:切勿混合类型。 教程不得包含说明内容,参考文档不得包含指导内容,操作指南不得包含教学内容。应通过链接在不同类型文档间跳转。

Documentation plan algorithm

文档规划算法

  1. Always include: README.md (hybrid: summary + links to other docs)
  2. For each knowledge area, decide if a separate doc is needed:
ConditionDocumentDiataxis Type
Project existsREADME.mdHybrid (summary + pointers)
Nontrivial setupdocs/getting-started.mdTutorial
Public API or librarydocs/api-reference.mdReference
CLI tooldocs/usage.mdReference + How-to
Multi-component systemdocs/architecture.mdExplanation
Complex design decisionsdocs/adr/NNN-title.mdExplanation
External contributors expectedCONTRIBUTING.mdHow-to
Versioned releasesCHANGELOG.mdReference
Complex config/deploymentdocs/deployment.mdHow-to
Internal developmentdocs/developer-guide.mdHow-to
Test infrastructuredocs/testing.mdHow-to
  1. Omit irrelevant sections. No API means no API docs. No CLI means no CLI usage.
  2. Merge or split by project size:
    • Small projects: combine Installation, Usage, and Overview in README
    • Large projects: separate into focused files under docs/
  3. Order by audience need: Getting Started before deep reference. Overview before architecture.
  1. 必须包含:README.md(混合类型:摘要+其他文档链接)
  2. 针对每个知识领域,决定是否需要单独文档
条件文档Diataxis类型
项目已存在README.md混合类型(摘要+指引)
非 trivial 安装流程docs/getting-started.md教程
公共API或库docs/api-reference.md参考文档
CLI工具docs/usage.md参考文档+操作指南
多组件系统docs/architecture.md说明文档
复杂设计决策docs/adr/NNN-title.md说明文档
预期有外部贡献者CONTRIBUTING.md操作指南
版本化发布CHANGELOG.md参考文档
复杂配置/部署docs/deployment.md操作指南
内部开发docs/developer-guide.md操作指南
测试基础设施docs/testing.md操作指南
  1. 省略无关章节:无API则无需API文档,无CLI则无需CLI使用文档。
  2. 根据项目大小合并或拆分
    • 小型项目:将安装、使用、概述合并到README中
    • 大型项目:拆分为docs/目录下的聚焦文件
  3. 按受众需求排序:入门指南优先于深度参考文档,概述优先于架构文档。

Plan output

规划输出

Documentation Plan
- README.md (hybrid) — CREATE
- docs/getting-started.md (tutorial) — CREATE
- docs/architecture.md (explanation) — CREATE
- docs/api-reference.md (reference) — CREATE
- CONTRIBUTING.md (how-to) — CREATE
Present the plan to the user for approval before writing.
文档规划
- README.md(混合类型) — 创建
- docs/getting-started.md(教程) — 创建
- docs/architecture.md(说明文档) — 创建
- docs/api-reference.md(参考文档) — 创建
- CONTRIBUTING.md(操作指南) — 创建
编写前需将规划提交用户审批。

Brownfield planning

存量项目规划

Use the doc inventory from Phase 1. Do NOT plan from scratch. Plan only what changes.
使用阶段1的文档清单。 不要从零开始规划,仅规划需要变更的内容。

Doc Refresh: Drift detection

文档刷新:差异检测

Compare each existing doc against current code to identify drift. See references/drift-detection.md for the full method.
For each existing doc, produce a drift report:
Drift Report: [file path]
  STALE:    [fact in doc] → [current fact in code]
  MISSING:  [interface/feature not documented]
  DEAD:     [documented item that no longer exists]
  ACCURATE: [sections that are still correct]
将每个现有文档与当前代码对比,识别差异。完整方法请参考references/drift-detection.md
针对每个现有文档生成差异报告:
差异报告:[文件路径]
  过时内容:    [文档中的事实] → [代码中的当前事实]
  缺失内容:  [未记录的接口/功能]
  无效内容:  [已记录但不存在的项]
  准确内容:  [仍正确的章节]

Doc Enhancement: Delta plan

文档增强:增量规划

When adding documentation for new features/modules:
  1. Identify which EXISTING docs need updating (e.g., README features list, API reference for new endpoints)
  2. Identify which NEW docs need creating
  3. For each existing doc, specify ONLY what changes — do not rewrite
Documentation Delta Plan
- README.md (hybrid) — MODIFY: add new feature to Features section, update Quick Start
- docs/api-reference.md (reference) — MODIFY: add POST /widgets endpoint
- docs/widget-guide.md (how-to) — CREATE: new guide for widget feature
为新功能/模块添加文档时:
  1. 确定需要更新的现有文档(例如,README的功能列表、新增端点的API参考文档)
  2. 确定需要创建的新文档
  3. 针对每个现有文档,仅指定变更内容 — 不要重写
文档增量规划
- README.md(混合类型) — 修改:在功能列表中添加新功能,更新快速入门
- docs/api-reference.md(参考文档) — 修改:添加POST /widgets端点
- docs/widget-guide.md(操作指南) — 创建:针对widget功能的新指南

Doc Audit: Restructure plan

文档审计:重构规划

When docs exist but quality is poor:
  1. List all issues found in Phase 1 with severity
  2. Propose fixes grouped by severity (Critical → High → Medium → Low)
  3. For each doc, specify: KEEP (as-is), EDIT (fix specific issues), REWRITE (replace with new version), or DELETE (remove dead doc)
  4. Present to user for approval — let them decide scope
Audit Findings & Plan
  README.md:
    - [Critical] Install command references removed package → EDIT: fix command
    - [High] Missing API section → EDIT: add section
    - [Low] Mixed tutorial and reference content → EDIT: extract tutorial to separate doc
  docs/old-guide.md:
    - [Critical] Entire doc references removed feature → DELETE
  docs/api.md:
    - [Medium] 3 endpoints undocumented → EDIT: add missing endpoints
当文档存在但质量不佳时:
  1. 列出阶段1中发现的所有问题并标注严重程度
  2. 按严重程度分组提出修复方案(关键→高→中→低)
  3. 针对每个文档,指定:保留(原样)、编辑(修复特定问题)、重写(替换为新版本)或删除(移除无效文档)
  4. 提交用户审批 — 由用户决定范围
审计结果与规划
  README.md:
    - [关键] 安装命令引用已移除的包 → 编辑:修复命令
    - [高] 缺少API章节 → 编辑:添加章节
    - [低] 混合了教程与参考内容 → 编辑:将教程内容提取到单独文档
  docs/old-guide.md:
    - [关键] 整个文档引用已移除的功能 → 删除
  docs/api.md:
    - [中] 3个端点未记录 → 编辑:添加缺失端点

Targeted Rewrite: Single-doc plan

定向重写:单文档规划

When the user asks to rewrite a specific existing doc:
  1. Read the existing doc fully (done in Phase 1)
  2. Identify what to PRESERVE (domain knowledge, rationale, custom sections)
  3. Identify what to REPLACE (stale facts, broken examples, wrong structure)
  4. Identify what to ADD (missing content)
  5. Present the plan: "I will keep X, replace Y, add Z"
Rewrite Plan: README.md
  PRESERVE: Project description, design rationale in Architecture section
  REPLACE:  Install commands (outdated), Quick Start (broken example),
            Features list (missing 3 features)
  ADD:      Configuration section, link to new API docs
  REMOVE:   FAQ section (answers belong in specific docs)
Get user approval before rewriting.
当用户要求重写特定现有文档时:
  1. 完整阅读现有文档(阶段1已完成)
  2. 确定需保留的内容(领域知识、设计依据、自定义章节)
  3. 确定需替换的内容(过时事实、无效示例、错误结构)
  4. 确定需添加的内容(缺失内容)
  5. 提交规划:"我将保留X,替换Y,添加Z"
重写规划:README.md
  保留:项目描述、架构章节中的设计依据
  替换:安装命令(过时)、快速入门(无效示例)、功能列表(缺失3个功能)
  添加:配置章节、新API文档的链接
  移除:FAQ章节(答案应放在特定文档中)
重写前需获得用户批准。

Version Update: Migration plan

版本更新:迁移规划

When documentation needs updating for a version bump:
  1. Identify all version-specific references in existing docs
  2. Identify breaking changes (from changelog, git diff, or user input)
  3. Plan updates grouped by: version numbers, API changes, config changes, behavioral changes, deprecation notices
Version Update Plan: v1 → v2
  Version references: README.md (3), docs/install.md (2), docs/api.md (header)
  Breaking changes:
    - POST /users now requires `email` field → docs/api-reference.md
    - Config key `db_host` renamed to `database_url` → docs/deployment.md, README.md
  Deprecations:
    - GET /users/search deprecated in favor of query params on GET /users → docs/api-reference.md
  New features:
    - Batch API endpoints → docs/api-reference.md (add section)
Present the plan to the user for approval before writing.

当文档需要随版本升级更新时:
  1. 识别现有文档中所有版本相关引用
  2. 识别破坏性变更(来自变更日志、git diff或用户输入)
  3. 按以下类别规划更新:版本号、API变更、配置变更、行为变更、弃用通知
版本更新规划:v1 → v2
  版本引用:README.md(3处)、docs/install.md(2处)、docs/api.md(页眉)
  破坏性变更:
    - POST /users现在需要`email`字段 → docs/api-reference.md
    - 配置键`db_host`重命名为`database_url` → docs/deployment.md、README.md
  弃用内容:
    - GET /users/search已弃用,改用GET /users的查询参数 → docs/api-reference.md
  新功能:
    - 批量API端点 → docs/api-reference.md(添加章节)
编写前需将规划提交用户审批。

Phase 3: Write Documentation

阶段3:编写文档

Greenfield: Write from scratch

新项目:从零开始编写

Write each planned document using the appropriate template and writing rules. See references/doc-templates.md for all templates. See references/writing-rules.md for style rules.
使用合适的模板和写作规则编写每个规划文档。所有模板请参考references/doc-templates.md。风格规则请参考references/writing-rules.md

Writing sequence

编写顺序

Write documents in this order:
  1. README.md first (it's the front door; forces you to articulate purpose)
  2. Getting Started (validates that setup works)
  3. Reference docs (API, CLI usage — factual, derived from code)
  4. How-to guides (developer guide, deployment, contributing)
  5. Explanation docs (architecture, design decisions)
  6. Changelog (if applicable)
按以下顺序编写文档:
  1. README.md 优先(它是项目的入口,能促使你明确项目目标)
  2. 入门指南(验证安装流程是否可行)
  3. 参考文档(API、CLI使用 — 基于事实,从代码推导)
  4. 操作指南(开发者指南、部署、贡献指南)
  5. 说明文档(架构、设计决策)
  6. 变更日志(如适用)

Per-document process (greenfield)

单文档编写流程(新项目)

For each document:
  1. Classify: Confirm Diataxis type. Apply that type's rules strictly.
  2. Gather facts: Read the relevant source code, config, and tests. Never write about code you haven't read.
  3. Draft: Use the template from references/doc-templates.md. Follow the writing rules from references/writing-rules.md.
  4. Verify examples: Every code example, command, or snippet must be derived from actual code. Never fabricate examples.
  5. Cross-reference: Link to related docs. Never duplicate content that belongs in another document.
针对每个文档:
  1. 分类:确认Diataxis类型,严格遵循该类型规则。
  2. 收集事实:阅读相关源代码、配置和测试。绝不编写未阅读过的代码相关内容。
  3. 起草:使用references/doc-templates.md中的模板,遵循references/writing-rules.md中的写作规则。
  4. 验证示例:每个代码示例、命令或片段必须来自实际代码。绝不虚构示例。
  5. 交叉引用:链接到相关文档。绝不重复属于其他文档的内容。

Brownfield: Edit existing docs

存量项目:编辑现有文档

Read before writing. For every doc you modify, read it fully first (already done in Phase 1). Never modify a doc you haven't read.
先阅读再编写。 针对每个要修改的文档,先完整阅读(阶段1已完成)。绝不修改未阅读过的文档。

Per-document process (brownfield)

单文档编写流程(存量项目)

For each document being modified:
  1. Re-read the doc. Confirm your understanding from Phase 1.
  2. Apply only planned changes. Follow the delta plan from Phase 2. Do NOT restructure, restyle, or "improve" sections outside scope.
  3. Match existing conventions. Use the same heading style, terminology, code block formatting, and tone discovered in Phase 1.
  4. Preserve valuable content. Domain knowledge, design rationale, user tips, and custom sections survive unless explicitly marked for removal.
  5. Verify every edit. Each changed fact must be verified against code.
  6. Minimize diff. Change only what needs changing. Smaller diffs are easier to review and less likely to introduce errors.
针对每个要修改的文档:
  1. 重新阅读文档:确认阶段1中的理解。
  2. 仅应用规划的变更:遵循阶段2的增量规划。不要重构、修改风格或“优化”规划外的章节。
  3. 匹配现有约定:使用阶段1中发现的相同标题样式、术语、代码块格式和语气。
  4. 保留宝贵内容:领域知识、设计依据、用户技巧和自定义章节除非明确标记删除,否则均保留。
  5. 验证每个编辑:每个变更的事实必须与代码验证一致。
  6. 最小化差异:仅修改需要变更的内容。更小的差异更易于审核,也更不容易引入错误。

Brownfield-specific rules

存量项目特定规则

  • Edit, don't rewrite. Unless the user requests a rewrite, modify the existing doc surgically. Fix the wrong facts; leave correct content alone.
  • Match existing style. If the existing README uses
    ##
    for sections and
    bash
    for code blocks, continue that pattern. Do NOT switch to
    ###
    or
    shell
    because you prefer it.
  • Preserve structure. Keep the existing section ordering unless it's part of the planned changes. Users have muscle memory for where information lives.
  • Preserve authorship signals. If existing docs have a distinctive voice, project-specific terminology, or custom sections, maintain them. The original author's domain knowledge is irreplaceable.
  • Never silently delete content. If a section needs removal, note it in your plan and confirm with the user. Content that looks outdated may contain context you can't reconstruct from code.
  • Refactor only what you're asked to change. Do NOT improve adjacent sections, fix unrelated formatting, or add sections not in the plan. This mirrors the TDD principle: "refactor only what you wrote."
  • 编辑而非重写:除非用户要求重写,否则仅对现有文档进行精准修改。修正错误事实,保留正确内容。
  • 匹配现有风格:如果现有README使用
    ##
    作为章节标题、
    bash
    作为代码块标签,请继续遵循该模式。不要因为个人偏好而切换为
    ###
    shell
  • 保留结构:除非是规划变更的一部分,否则保持现有章节顺序。用户对信息位置有肌肉记忆。
  • 保留作者特征:如果现有文档有独特语气、项目特定术语或自定义章节,请保持。原作者的领域知识是不可替代的。
  • 绝不静默删除内容:如果需要移除章节,请在规划中注明并获得用户确认。看似过时的内容可能包含无法从代码中重建的上下文。
  • 仅重构要求变更的内容:不要优化相邻章节、修复无关格式或添加规划外的章节。这与TDD原则一致:“仅重构你编写的内容”。

Targeted Rewrite process

定向重写流程

When rewriting a specific doc (user explicitly requested):
  1. Create from the approved plan. Write the new version using the PRESERVE/REPLACE/ADD/REMOVE breakdown from Phase 2.
  2. Start from the template in references/doc-templates.md, then transplant preserved content into the new structure.
  3. For preserved content: Copy it verbatim. Do not rephrase domain knowledge or design rationale unless it's factually wrong.
  4. For replaced content: Write fresh from code analysis. Verify every fact.
  5. For added content: Follow greenfield per-document process.
  6. Present the full new doc for review before replacing the existing file.
当用户明确要求重写特定文档时:
  1. 基于获批规划创建:使用阶段2中的保留/替换/添加/移除 breakdown编写新版本。
  2. 从模板开始:使用references/doc-templates.md中的模板,然后将保留内容移植到新结构中。
  3. 保留内容:逐字复制。除非事实错误,否则不要改写领域知识或设计依据。
  4. 替换内容:从代码分析中重新编写。验证每个事实。
  5. 添加内容:遵循新项目单文档编写流程。
  6. 提交完整新版本供审核,然后再替换现有文件。

Shared: README generation

通用:README生成

The README is special — it's a hybrid document that serves as the project's front door. It must include:
  • Title + one-line description (what is this, what problem does it solve)
  • Badges (optional: build status, coverage, version)
  • Installation (copy-paste commands, minimal steps)
  • Quick start (runnable example with sample output)
  • Key features (bullet list of capabilities)
  • Usage examples (code blocks with real commands/code)
  • Architecture overview (brief summary or link to architecture doc)
  • Development (how to build/test, or link to developer guide)
  • Contributing (link to CONTRIBUTING.md)
  • License
See the README template in references/doc-templates.md.
Brownfield README: When editing an existing README, preserve its custom sections (badges, custom headings, project-specific content). Update only the sections identified in the delta plan.
README是特殊的混合文档,作为项目的入口。它必须包含:
  • 标题+一行描述(这是什么,解决什么问题)
  • 徽章(可选:构建状态、覆盖率、版本)
  • 安装(可复制粘贴的命令,最少步骤)
  • 快速入门(可运行的示例及输出)
  • 核心功能(能力列表)
  • 使用示例(真实命令/代码的代码块)
  • 架构概述(简要总结或架构文档链接)
  • 开发(构建/测试方法,或开发者指南链接)
  • 贡献(CONTRIBUTING.md链接)
  • 许可证
README模板请参考references/doc-templates.md
存量项目README:编辑现有README时,保留其自定义章节(徽章、自定义标题、项目特定内容)。仅更新增量规划中指定的章节。

Shared: API reference generation

通用:API参考文档生成

For libraries or services with a public API:
  1. Parse the code to identify all public interfaces (exports, endpoints, commands)
  2. For each interface, document: signature/URL, parameters, return type, authentication, example request, example response, error cases
  3. Mirror the code structure in the doc structure (classes, modules, endpoints)
  4. If OpenAPI/Swagger exists, use it as the canonical source
  5. Follow Reference type rules: austere, factual, no instruction or explanation
Brownfield API reference: When updating, add new endpoints in the same style as existing ones. Update changed signatures in place. Mark removed endpoints as deprecated (do not delete unless user confirms — downstream consumers may reference the docs).
针对有公共API的库或服务:
  1. 解析代码识别所有公共接口(导出项、端点、命令)
  2. 针对每个接口记录:签名/URL、参数、返回类型、认证方式、请求示例、响应示例、错误场景
  3. 在文档结构中镜像代码结构(类、模块、端点)
  4. 如果存在OpenAPI/Swagger,将其作为权威来源
  5. 遵循参考文档类型规则:简洁、基于事实,无指导或说明内容
存量项目API参考文档:更新时,以与现有内容相同的风格添加新端点。在原位置更新变更的签名。标记已移除的端点为弃用(除非用户确认,否则不要删除 — 下游消费者可能仍在参考文档)。

Shared: Architecture documentation

通用:架构文档

For multi-component systems, use the C4 model hierarchy:
  1. System Context: What is this system? What external systems and users interact with it? (No technical detail — readable by non-technical people)
  2. Container diagram: What are the major deployable units (apps, databases, queues)? What technologies? How do they communicate?
  3. Component diagram: (Optional) Inside a container, what are the major modules and their responsibilities?
Label every element: Name + Technology + one-line responsibility. Label every relationship: verb phrase describing what flows.
Record key design decisions as Architecture Decision Records (ADRs).
针对多组件系统,使用C4模型层级:
  1. 系统上下文:这是什么系统?哪些外部系统和用户与之交互?(无技术细节 — 非技术人员可阅读)
  2. 容器图:主要可部署单元(应用、数据库、队列)是什么?使用什么技术?如何通信?
  3. 组件图(可选):容器内部的主要模块及其职责是什么?
为每个元素标注:名称+技术+一行职责描述。 为每个关系标注:描述数据流的动词短语。
将关键设计决策记录为架构决策记录(ADR)。

Shared: Changelog generation

通用:变更日志生成

Follow the Keep a Changelog standard:
  • Name the file
    CHANGELOG.md
  • Maintain an "Unreleased" section at the top
  • Use reverse chronological order
  • Group changes under: Added, Changed, Deprecated, Removed, Fixed, Security
  • Use ISO 8601 dates (YYYY-MM-DD)
  • Never use raw git log as a changelog
Brownfield changelog: Append to existing changelog. Never rewrite history. Add new entries at the top under Unreleased or a new version heading.

遵循Keep a Changelog标准:
  • 文件命名为
    CHANGELOG.md
  • 在顶部维护“Unreleased”章节
  • 使用逆 chronological 顺序
  • 变更分组为:Added、Changed、Deprecated、Removed、Fixed、Security
  • 使用ISO 8601日期格式(YYYY-MM-DD)
  • 绝不使用原始git日志作为变更日志
存量项目变更日志:追加到现有变更日志中。绝不重写历史。在Unreleased或新版本标题下添加新条目。

Phase 4: Verify Documentation

阶段4:验证文档

After writing, verify every document against the code.
编写完成后,针对代码验证每个文档。

Verification checklist (all workflows)

验证清单(所有工作流)

  • Accuracy: Every factual claim matches the code
  • Commands work: Every shell command runs successfully
  • Code examples compile/run: Every code snippet is valid
  • Links resolve: All internal links point to existing files/headings
  • Completeness: All public interfaces are documented (for reference docs)
  • No fabrication: No invented API endpoints, flags, or behaviors
  • Type purity: Each doc stays within its Diataxis type (no mixing)
  • Consistent terminology: Same term used for same concept everywhere
  • Config matches code: Documented env vars, versions, and settings match actual code
  • No duplication: Content lives in one place and is linked elsewhere
  • 准确性:每个事实性描述均与代码匹配
  • 命令可行:每个Shell命令均可成功运行
  • 代码示例可编译/运行:每个代码片段均有效
  • 链接可解析:所有内部链接指向现有文件/标题
  • 完整性:所有公共接口均已记录(针对参考文档)
  • 无虚构内容:无编造的API端点、标志或行为
  • 类型纯粹:每个文档严格遵循其Diataxis类型(无混合)
  • 术语一致:同一概念使用相同术语
  • 配置与代码匹配:已记录的环境变量、版本和设置与实际代码一致
  • 无重复内容:内容仅存于一处,通过链接引用

Additional brownfield verification

存量项目额外验证项

  • Preserved content intact: Domain knowledge, rationale, and custom sections from existing docs were not lost or mangled
  • Conventions maintained: Heading style, terminology, code block formatting match the rest of the existing docs
  • No unplanned changes: Only the sections identified in the delta plan were modified. No drive-by formatting fixes or unsolicited rewrites.
  • No content silently deleted: Every removal was in the approved plan
  • Diff is minimal: Changes are surgical, not a full rewrite (unless Targeted Rewrite was the chosen workflow)
  • Existing cross-references still work: Changes didn't break links in OTHER docs that point to modified sections
  • 保留内容完整:现有文档中的领域知识、设计依据和自定义章节未丢失或被篡改
  • 约定保持一致:标题样式、术语、代码块格式与其他现有文档匹配
  • 无计划外变更:仅修改增量规划中指定的章节。无随意的格式修复或未经请求的重写。
  • 无静默删除内容:所有移除操作均在获批规划中
  • 差异最小化:变更精准,而非全面重写(除非是定向重写工作流)
  • 现有交叉引用仍有效:变更未破坏其他文档中指向修改章节的链接

Verification method

验证方法

For each document:
  1. Spot-check facts against source code (grep for documented functions, endpoints, env vars — confirm they exist)
  2. Test commands by reading them critically against the codebase (do the referenced files, scripts, and flags exist?)
  3. Validate examples against actual code signatures and return types
  4. Check cross-references (do linked files and headings exist?)
  5. Run doc linters if the project has them (markdownlint, link checkers)
  6. (Brownfield) Compare against original to confirm only planned changes were made and preserved content survived
针对每个文档:
  1. 抽查事实与源代码对比(grep已记录的函数、端点、环境变量 — 确认其存在)
  2. 测试命令:根据代码库仔细检查(引用的文件、脚本和标志是否存在?)
  3. 验证示例与实际代码签名和返回类型对比
  4. 检查交叉引用(链接的文件和标题是否存在?)
  5. 运行文档检查器(如果项目有)(markdownlint、链接检查器)
  6. (存量项目)与原始文档对比:确认仅执行了规划的变更,且保留内容未丢失

Common errors to catch

需要排查的常见错误

ErrorHow to Detect
Documented function doesn't existGrep for function name in source
Wrong parameter names/typesCompare doc to actual function signature
Outdated install commandCheck package.json/pyproject.toml for current versions
Broken internal linkCheck that target file/heading exists
Stale env var nameGrep for env var in source code
Example output doesn't matchRun or simulate the example mentally
Mixed Diataxis typesReview: does a tutorial explain? Does reference instruct?
Preserved content lost (brownfield)Compare with original doc
Convention mismatch (brownfield)Compare heading/code block style with existing docs

错误检测方法
已记录的函数不存在在源代码中grep函数名
参数名称/类型错误将文档与实际函数签名对比
安装命令过时检查package.json/pyproject.toml获取当前版本
内部链接失效检查目标文件/标题是否存在
环境变量名称过时在源代码中grep环境变量
示例输出不匹配实际运行或模拟示例
Diataxis类型混合检查:教程是否包含说明?参考文档是否包含指导?
保留内容丢失(存量项目)与原始文档对比
约定不匹配(存量项目)与现有文档对比标题/代码块样式

Phase 5: Maintenance Strategy

阶段5:维护策略

Documentation rots when it diverges from code. Embed maintenance practices.
当文档与代码脱节时,文档就会失效。需嵌入维护实践。

Docs-as-code principles

Docs-as-Code原则

  • Version docs alongside code. All docs live in the repo, not a wiki.
  • Update docs in the same commit as code changes. Never defer.
  • Review docs in PRs. Reviewers should reject PRs that change behavior without updating docs.
  • Delete dead docs. Outdated documentation is worse than no documentation. Remove or mark deprecated.
  • Link, don't duplicate. Point to canonical sources rather than copying.
  • 文档与代码版本同步:所有文档存于代码仓库,而非Wiki。
  • 代码变更时同步更新文档:绝不延迟。
  • PR中审核文档:审核者应拒绝未更新文档的行为变更PR。
  • 删除无效文档:过时文档比无文档更糟。移除或标记为弃用。
  • 链接而非重复:指向权威来源而非复制内容。

Automated checks (recommend to user)

自动化检查(推荐给用户)

Suggest these CI integrations where relevant:
CheckToolPurpose
Markdown lintmarkdownlint, remark-lintConsistent formatting
Link checkingmarkdown-link-checkNo broken links
Spell checkcspell, aspellCatch typos
Doc generationSphinx, JSDoc, typedocReference from source
Example testingdoctest, mdx-testExamples actually work
API syncswagger-diff, openapi-diffAPI docs match spec

根据场景建议以下CI集成:
检查项工具目的
Markdown检查markdownlint、remark-lint格式一致
链接检查markdown-link-check无失效链接
拼写检查cspell、aspell捕获拼写错误
文档生成Sphinx、JSDoc、typedoc从源代码生成参考文档
示例测试doctest、mdx-test示例可正常运行
API同步swagger-diff、openapi-diffAPI文档与规范匹配

Failure Recovery

故障恢复

Documentation issue
  |
  +-> Can't determine what code does
  |     +-> Read more source files
  |     +-> Check tests for behavioral clues
  |     +-> Ask user for clarification
  |
  +-> Conflicting information (code vs. config vs. comments)
  |     +-> Code is authoritative (it's what actually runs)
  |     +-> Note the conflict; update incorrect sources
  |
  +-> Unsure if feature is public or internal
  |     +-> Check exports, access modifiers, public API markers
  |     +-> When in doubt, document it (users may depend on it)
  |     +-> Ask user if unclear
  |
  +-> Existing docs are extensive but wrong (brownfield)
  |     +-> Fix accuracy first, preserve structure
  |     +-> Never rewrite from scratch unless user requests it
  |     +-> Track changes for user review
  |
  +-> Existing doc has valuable content mixed with stale content (brownfield)
  |     +-> Separate: identify each section as preserve/replace/add/remove
  |     +-> Fix the stale parts, keep the valuable parts
  |     +-> When uncertain, preserve and flag for user review
  |
  +-> Conventions in existing docs conflict with best practices (brownfield)
        +-> Follow existing conventions (consistency > correctness)
        +-> Only change conventions if user explicitly requests it
        +-> If existing convention causes real problems (e.g., broken rendering),
            fix that specific issue and note the change
Never fabricate. If you cannot determine a fact from the code, say so and ask the user. Do not guess API behaviors, default values, or configuration.
Never write about code you haven't read. Always read the source before documenting it.
Never silently rewrite. In brownfield workflows, if you find yourself wanting to restructure or rephrase content not in the plan, stop. That impulse means the scope needs revisiting, not expanding.

文档问题
  |
  +-> 无法确定代码功能
  |     +-> 阅读更多源文件
  |     +-> 检查测试获取行为线索
  |     +-> 向用户寻求澄清
  |
  +-> 信息冲突(代码vs配置vs注释)
  |     +-> 代码是权威来源(实际运行的是代码)
  |     +-> 记录冲突;更新错误来源
  |
  +-> 不确定功能是公共还是内部
  |     +-> 检查导出项、访问修饰符、公共API标记
  |     +-> 存疑时记录(用户可能依赖)
  |     +-> 不确定时询问用户
  |
  +-> 现有文档内容丰富但错误(存量项目)
  |     +-> 先修复准确性,保留结构
  |     +-> 除非用户要求,否则绝不从零开始重写
  |     +-> 记录变更供用户审核
  |
  +-> 现有文档包含宝贵内容与过时内容(存量项目)
  |     +-> 分离:将每个章节标记为保留/替换/添加/移除
  |     +-> 修复过时部分,保留宝贵部分
  |     +-> 不确定时保留并标记供用户审核
  |
  +-> 现有文档约定与最佳实践冲突(存量项目)
        +-> 遵循现有约定(一致性>正确性)
        +-> 仅在用户明确要求时修改约定
        +-> 如果现有约定导致实际问题(如渲染失效),修复特定问题并记录变更
绝不虚构内容。 如果无法从代码中确定事实,请告知用户并寻求澄清。不要猜测API行为、默认值或配置。
绝不编写未阅读过的代码相关内容。 记录前始终阅读源代码。
绝不静默重写。 在存量项目工作流中,如果发现想要重构或改写规划外的内容,请停止。这意味着需要重新审视范围,而非扩大范围。

Reference Files

参考文件

  • Document templates: See references/doc-templates.md for README, API Reference, Architecture, Developer Guide, Contributing, Changelog, Getting Started, ADR, and Testing templates
  • Diataxis guide: See references/diataxis-guide.md for the four documentation types with do/don't rules, voice, and structure
  • Repository analysis: See references/repo-analysis.md for the systematic codebase analysis method
  • Drift detection: See references/drift-detection.md for the section-by-section method to identify doc/code divergence
  • Writing rules: See references/writing-rules.md for style guide, formatting rules, and quality checklist
  • 文档模板:README、API参考、架构、开发者指南、贡献指南、变更日志、入门指南、ADR和测试模板请参考references/doc-templates.md
  • Diataxis指南:四种文档类型的规则、语气和结构请参考references/diataxis-guide.md
  • 代码库分析:系统化代码库分析方法请参考references/repo-analysis.md
  • 差异检测:逐节识别文档/代码差异的方法请参考references/drift-detection.md
  • 写作规则:风格指南、格式规则和质量清单请参考references/writing-rules.md