跳到主要内容

技术文档与 ADR

收藏0

把设计决策写成能长期用的文档:ADR(架构决策记录)的格式与编号、什么时候该写、何时该废弃,以及怎么发现文档已经和代码不一致并加上防止再次偏离的检查。

让 AI 安装

星光尘缘LV2最新版本 0.1.0更新于 2026-11-22下载 0 次

SKILL.md

12.3 KB查看排版效果
1---
2name: documentation-and-adrs
3description: Records decisions and documentation, and detects when documentation has drifted from the code it describes. Use when you need to document an architecture decision (ADR) or the reasoning behind a design choice, when changing public APIs, shipping features, when docs may be stale or out of sync with the code they describe, when working out which module docs are still accurate, or when setting up a check so docs cannot silently go out of date again.
4---
5
6# Documentation and ADRs
7
8## Overview
9
10Document decisions, not just code. The most valuable documentation captures the *why* — the context, constraints, and trade-offs that led to a decision. Code shows *what* was built; documentation explains *why it was built this way* and *what alternatives were considered*. This context is essential for future humans and agents working in the codebase.
11
12## When to Use
13
14- Making a significant architectural decision
15- Choosing between competing approaches
16- Adding or changing a public API
17- Shipping a feature that changes user-facing behavior
18- Onboarding new team members (or agents) to the project
19- When you find yourself explaining the same thing repeatedly
20
21**When NOT to use:** Don't document obvious code. Don't add comments that restate what the code already says. Don't write docs for throwaway prototypes.
22
23## Architecture Decision Records (ADRs)
24
25ADRs capture the reasoning behind significant technical decisions. They're the highest-value documentation you can write.
26
27### When to Write an ADR
28
29- Choosing a framework, library, or major dependency
30- Designing a data model or database schema
31- Selecting an authentication strategy
32- Deciding on an API architecture (REST vs. GraphQL vs. tRPC)
33- Choosing between build tools, hosting platforms, or infrastructure
34- Any decision that would be expensive to reverse
35
36### Match the existing convention first
37
38Before creating an ADR, inspect the available repository context for an established convention — existing ADRs, project instructions, and ADR-related configuration or tooling (e.g. an `.adr-dir` file). An established convention overrides the defaults below. Match:
39
40- **Location and format** — e.g. `docs/adr/*.md`, `Documentation/Decisions/*.rst`, a MADR layout, or an `adr-tools` setup. Match the existing directory, file extension, and markup (Markdown vs reStructuredText).
41- **Numbering and naming** — continue the existing sequence and filename pattern (`ADR-004-Title.rst`, `0004-title.md`, …); don't restart at 001 or introduce a second scheme.
42- **Section headings** — reuse the project's heading set rather than imposing this template's.
43
44If the available evidence conflicts, surface the conflict rather than silently introducing another scheme. Only when no convention can be established do you apply the default below.
45
46### ADR Template
47
48Store ADRs in `docs/decisions/` with sequential numbering (unless the project already uses another location — see above):
49
50```markdown
51# ADR-001: Use PostgreSQL for primary database
52
53## Status
54Proposed | Accepted | Superseded by ADR-XXX | Deprecated
55
56## Date
572025-01-15
58
59## Context
60We need a primary database for the task management application. Key requirements:
61- Relational data model (users, tasks, teams with relationships)
62- ACID transactions for task state changes
63- Support for full-text search on task content
64- Managed hosting available (for small team, limited ops capacity)
65
66## Decision
67Use PostgreSQL with Prisma ORM.
68
69## Alternatives Considered
70
71### MongoDB
72- Pros: Flexible schema, easy to start with
73- Cons: Our data is inherently relational; would need to manage relationships manually
74- Rejected: Relational data in a document store leads to complex joins or data duplication
75
76### SQLite
77- Pros: Zero configuration, embedded, fast for reads
78- Cons: Limited concurrent write support, no managed hosting for production
79- Rejected: Not suitable for multi-user web application in production
80
81### MySQL
82- Pros: Mature, widely supported
83- Cons: PostgreSQL has better JSON support, full-text search, and ecosystem tooling
84- Rejected: PostgreSQL is the better fit for our feature requirements
85
86## Consequences
87- Prisma provides type-safe database access and migration management
88- We can use PostgreSQL's full-text search instead of adding Elasticsearch
89- Team needs PostgreSQL knowledge (standard skill, low risk)
90- Hosting on managed service (Supabase, Neon, or RDS)
91```
92
93### ADR Lifecycle
94
95```
96PROPOSED → ACCEPTED → (SUPERSEDED or DEPRECATED)
97```
98
99- **Don't delete old ADRs.** They capture historical context.
100- When a decision changes, write a new ADR that references and supersedes the old one.
101
102## Inline Documentation
103
104### When to Comment
105
106Comment the *why*, not the *what*:
107
108```typescript
109// BAD: Restates the code
110// Increment counter by 1
111counter += 1;
112
113// GOOD: Explains non-obvious intent
114// Rate limit uses a fixed window that opens on the first request after the
115// previous one expires, not on a clock schedule. Known gap: a client can spend
116// the full limit just before a reset and again just after (2x in a moment)
117if (now - windowStart > WINDOW_SIZE_MS) {
118 counter = 0;
119 windowStart = now;
120}
121```
122
123### When NOT to Comment
124
125```typescript
126// Don't comment self-explanatory code
127function calculateTotal(items: CartItem[]): number {
128 return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
129}
130
131// Don't leave TODO comments for things you should just do now
132// TODO: add error handling ← Just add it
133
134// Don't leave commented-out code
135// const oldImplementation = () => { ... } ← Delete it, git has history
136```
137
138### Document Known Gotchas
139
140```typescript
141/**
142 * IMPORTANT: This function must be called before the first render.
143 * If called after hydration, it causes a flash of unstyled content
144 * because the theme context isn't available during SSR.
145 *
146 * See ADR-003 for the full design rationale.
147 */
148export function initializeTheme(theme: Theme): void {
149 // ...
150}
151```
152
153## API Documentation
154
155For public APIs (REST, GraphQL, library interfaces):
156
157### Inline with Types (Preferred for TypeScript)
158
159```typescript
160/**
161 * Creates a new task.
162 *
163 * @param input - Task creation data (title required, description optional)
164 * @returns The created task with server-generated ID and timestamps
165 * @throws {ValidationError} If title is empty or exceeds 200 characters
166 * @throws {AuthenticationError} If the user is not authenticated
167 *
168 * @example
169 * const task = await createTask({ title: 'Buy groceries' });
170 * console.log(task.id); // "task_abc123"
171 */
172export async function createTask(input: CreateTaskInput): Promise<Task> {
173 // ...
174}
175```
176
177### OpenAPI / Swagger for REST APIs
178
179```yaml
180paths:
181 /api/tasks:
182 post:
183 summary: Create a task
184 requestBody:
185 required: true
186 content:
187 application/json:
188 schema:
189 $ref: '#/components/schemas/CreateTaskInput'
190 responses:
191 '201':
192 description: Task created
193 content:
194 application/json:
195 schema:
196 $ref: '#/components/schemas/Task'
197 '422':
198 description: Validation error
199```
200
201## README Structure
202
203Every project should have a README that covers:
204
205```markdown
206# Project Name
207
208One-paragraph description of what this project does.
209
210## Quick Start
2111. Clone the repo
2122. Install dependencies: `npm install`
2133. Set up environment: `cp .env.example .env`
2144. Run the dev server: `npm run dev`
215
216## Commands
217| Command | Description |
218|---------|-------------|
219| `npm run dev` | Start development server |
220| `npm test` | Run tests |
221| `npm run build` | Production build |
222| `npm run lint` | Run linter |
223
224## Architecture
225Brief overview of the project structure and key design decisions.
226Link to ADRs for details.
227
228## Contributing
229How to contribute, coding standards, PR process.
230```
231
232## Changelog Maintenance
233
234For shipped features:
235
236```markdown
237# Changelog
238
239## [1.2.0] - 2025-01-20
240### Added
241- Task sharing: users can share tasks with team members (#123)
242- Email notifications for task assignments (#124)
243
244### Fixed
245- Duplicate tasks appearing when rapidly clicking create button (#125)
246
247### Changed
248- Task list now loads 50 items per page (was 20) for better UX (#126)
249```
250
251## Documentation for Agents
252
253Special consideration for AI agent context:
254
255- **CLAUDE.md / rules files** — Document project conventions so agents follow them
256- **Spec files** — Keep specs updated so agents build the right thing
257- **ADRs** — Help agents understand why past decisions were made (prevents re-deciding)
258- **Inline gotchas** — Prevent agents from falling into known traps
259
260## Prose Review
261
262After checking the technical content, review the prose for the people who will use it. Clearer wording must not change the decision or its limits.
263
2641. Mark the details that must survive the edit: names, numbers and units, commands, paths, links, conditions, trade-offs, and uncertainty. Check them against the available code and decision context; flag anything you cannot substantiate.
2652. Replace stock introductions, promotional adjectives, and repeated summaries with the concrete information the reader needs. Do not replace an unsupported claim with an invented example or a stronger guarantee. Keep necessary technical repetition and the project's established terminology.
2663. Compare the edited document with the original and its sources. Restore any lost qualifier or caveat, verify command and code examples still work as documented, and explain any unresolved factual question rather than polishing it away.
267
268## Documentation Drift
269
270A document that was true when written still reads as authoritative after the code moves on. When a doc may be stale, decide from version control, not from how confident the doc sounds:
271
272```bash
273code=$(git log -1 --format=%H -- src/rate-limiter.js)
274doc=$(git log -1 --format=%H -- docs/rate-limiter.md)
275if [ "$code" = "$doc" ]; then echo "current: changed together"
276elif git merge-base --is-ancestor "$doc" "$code"; then echo "stale: code changed after the doc"
277elif git merge-base --is-ancestor "$code" "$doc"; then echo "current: doc changed after the code"
278else echo "can't tell"; fi
279```
280
281Unordered history (divergent branches, a rebase, a shallow clone) means "can't tell". Say that; never report it as current.
282
283When you correct a doc that has a change log, append a dated entry that says why it changed. Never rewrite or collapse earlier entries: git keeps the old text, but the log is the only record of the reasons.
284
285## Common Rationalizations
286
287| Rationalization | Reality |
288|---|---|
289| "The code is self-documenting" | Code shows what. It doesn't show why, what alternatives were rejected, or what constraints apply. |
290| "We'll write docs when the API stabilizes" | APIs stabilize faster when you document them. The doc is the first test of the design. |
291| "Nobody reads docs" | Agents do. Future engineers do. Your 3-months-later self does. |
292| "ADRs are overhead" | A 10-minute ADR prevents a 2-hour debate about the same decision six months later. |
293| "Comments get outdated" | Comments on *why* are stable. Comments on *what* get outdated — that's why you only write the former. |
294| "I'll tidy the change log while I'm in here" | Git holds the old text; the log holds the reasons. Rewriting it destroys the only copy of the reasoning and preserves nothing. |
295
296## Red Flags
297
298- Architectural decisions with no written rationale
299- Public APIs with no documentation or types
300- README that doesn't explain how to run the project
301- Commented-out code instead of deletion
302- TODO comments that have been there for weeks
303- No ADRs in a project with significant architectural choices
304- Documentation that restates the code instead of explaining intent
305- A change log that has been rewritten rather than appended to
306- A doc called current when the commit order of the doc and its code could not be determined
307
308## Verification
309
310After documenting:
311
312- [ ] ADRs exist for all significant architectural decisions
313- [ ] README covers quick start, commands, and architecture overview
314- [ ] API functions have parameter and return type documentation
315- [ ] Known gotchas are documented inline where they matter
316- [ ] No commented-out code remains
317- [ ] Rules files (CLAUDE.md etc.) are current and accurate
318- [ ] Prose edits preserve source details, decision trade-offs, and qualifiers without adding unsupported guarantees
319- [ ] Change logs were appended to rather than rewritten
320- [ ] A doc whose staleness could not be determined is reported as "can't tell", not as current

文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。