当前位置: 首页 > Skill >

Code Documentation

Code Documentation

Code Documentation

全面的代码文档编写技能——在需要文档时、代码重大变更后、新的子系统入门时等任何时候使用。

1.0.0 2026.11.27 102
获取Skill文件查看使用说明
作 者:沈景 许可证: 更新时间:2026.11.27
本文目录展开

Code Documentation Skill

Purpose

This skill governs how code is documented at every level — from individual file headers to global architecture docs. Apply it consistently across all projects. When in doubt: document the why, not the what. The code already says what it does.

Phase 0 — Before You Write Anything

  1. Scan the repo structure. Understand what exists before touching anything.
  2. Identify subsystems. Group files by domain (Auth, Billing, API Layer, etc.).
  3. Read existing docs first. Check /docs/ in both frontend and backend. Note what's present, missing, or stale.
  4. Confirm the active branch. Never document against stale or wrong code.

Phase 1 — Source File Standards

Apply to every file that is ≥ 20 lines OR is imported by other modules.

1.1 — Line 1: Full Path Comment

The very first line of every source file must be a comment containing the file's full path from the project root. Use the comment syntax appropriate to the language.

// src/services/auth/tokenService.js
# src/services/auth/token_service.py

1.2 — File Header Block (lines 2–N)

Immediately after the path comment, add a header block. Use the language's block comment syntax. This block is mandatory and must be kept accurate.

/**
 * File: src/services/auth/tokenService.js
 *
 * Overview:
 *   Issues, validates, and refreshes JWT tokens for authenticated sessions.
 *   Exists to centralise all token logic so Auth routes stay thin.
 *
 * Exports:
 *   - issueToken(userId, role) → signed JWT string
 *   - verifyToken(token) → decoded payload or throws
 *   - refreshToken(oldToken) → new signed JWT string
 *
 * Imported By:
 *   - src/routes/auth.js
 *   - src/middleware/requireAuth.js
 *
 * Imports:
 *   - jsonwebtoken  — signing/verification
 *   - config/env    — JWT_SECRET, TOKEN_TTL
 *
 * Notes:
 *   - Tokens expire in 15 min; refresh window is 7 days.
 *   - verifyToken throws on expiry — callers must handle.
 */

Rules:

  • Keep it current. If you add an export, update Exports. If a new file imports this, update Imported By.
  • Do not pad with boilerplate. Every line must be accurate and useful.

1.3 — Function Headers

Top of every non-trivial function (any function with logic beyond a single expression):

/**
 * Signs a new JWT for the given user. Embeds userId and role in payload.
 * Throws if JWT_SECRET is not set in env.
 */
function issueToken(userId, role) { ... }

Rules:

  • Max 2 sentences.
  • Explain why the function exists or what makes it non-obvious, not just what it does.
  • No parameter/return type breakdown unless the types are genuinely surprising.

1.4 — Inline Comment Rules

Allowed (rare exceptions only):

const TIMEOUT = 5000 // 5 seconds

Prohibited — remove on sight:

Pattern Example Why banned
Restating the code // enable proxy above proxy: true Zero information
Removed/old code notes // removed legacy handler Use git for history
Change log comments // changed to use v2 API Not a changelog
Section dividers // ---- helpers ---- Use modules instead
Obvious steps // loop through users above a users.forEach Noise

If you encounter these, delete them. They are clutter that erodes trust in real comments.

Phase 2 — Subsystem Documentation

See references/subsystem-doc.md for the full template and field-by-field instructions.

One .md file per subsystem, located at:

  • /backend/docs/<subsystem>.md
  • /frontend/docs/<subsystem>.md

Subsystem identification heuristics:

  • A cohesive domain handled by a directory or cluster of files
  • Examples: auth, billing, search, notifications, api-layer, data-layer, file-upload, websockets, admin, onboarding

Discovery checklist — identify a subsystem when you find:

  • A directory with 3+ related files
  • A shared service/utility used by 3+ other files
  • A distinct API surface (routes/controllers grouped by concern)
  • A background job or scheduled process
  • A third-party integration (Stripe, S3, Twilio, etc.)

If a subsystem doc already exists:

  • Compare it against current code
  • Remove anything describing code that no longer exists
  • Add anything the doc misses
  • Update all file maps, function names, and flow diagrams

Phase 3 — Global Architecture Document

Location: /docs/architecture.md (or /backend/docs/architecture.md depending on repo layout)

See references/architecture-doc.md for the full template.

Required sections:

  1. System Overview — what this product does in 2–3 sentences
  2. Subsystems — bulleted list, one-liner per subsystem, link to its .md
  3. High-Level Diagram — ASCII or Mermaid, showing subsystem relationships
  4. Tech Stack — language, framework, DB, cache, queue, infra
  5. Cross-Cutting Concerns — how auth, error handling, validation, config, logging, and testing work across the system (not per-subsystem)

Phase 4 — API Reference

Required if a backend exists. Location: /backend/docs/api.md

For large backends: one file per subsystem, e.g. /backend/docs/api-auth.md, /backend/docs/api-billing.md, then an index in /backend/docs/api.md.

See references/api-reference.md for the full endpoint template.

Every endpoint must document:

  • Method + path
  • Description (1 sentence — what this does for the caller)
  • Request: path params, query params, body schema
  • Response: success schema + status codes + error codes
  • Source mapping: which controller file and service methods handle it

Phase 5 — Validation Pass

After writing or updating docs, audit them:

## Documentation Audit

### Missing
- List any subsystem without a doc

### Outdated
- List any doc that references removed files, functions, or endpoints

### Incorrect
- List any wrong dependency, wrong export name, wrong flow description

### Recommendations
- Specific fixes with file locations

Do not skip this pass. Stale documentation is worse than none — it actively misleads.

Enforcement Rules

These apply any time you touch code:

  1. Changed a function's logic? → Update its header.
  2. Added or removed an export? → Update the file header's Exports section.
  3. Added a new file that others import? → Add the file header; update importers' "Imported By" lists if practical.
  4. Added or changed an API endpoint? → Update api.md.
  5. Structural change to a subsystem? → Update that subsystem's .md.
  6. Added a new subsystem? → Create its .md from the template in references/subsystem-doc.md.
  7. Removed a file or feature? → Find every doc that mentions it and remove those references.

Never leave documentation in a state that describes code that doesn't exist.

Quick Reference: What Goes Where

Concern Location
File path + module summary Top of every source file
Function purpose Top of every non-trivial function
Subsystem deep-dive /[frontend|backend]/docs/<name>.md
System-wide architecture /docs/architecture.md
API contracts /backend/docs/api.md (or per-subsystem)

Reference Files

  • references/subsystem-doc.md — Full subsystem doc template + instructions
  • references/architecture-doc.md — Full architecture.md template
  • references/api-reference.md — Full API endpoint documentation template

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,037
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,020
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,019
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,016
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,015
Skill 文件
  • SKILL.md
    • Code Documentation Skill
    • Purpose
    • Phase 0 — Before You Write Anything
    • Phase 1 — Source File Standards
      • 1.1 — Line 1: Full Path Comment
      • 1.2 — File Header Block (lines 2–N)
      • 1.3 — Function Headers
      • 1.4 — Inline Comment Rules
    • Phase 2 — Subsystem Documentation
    • Phase 3 — Global Architecture Document
    • Phase 4 — API Reference
    • Phase 5 — Validation Pass
    • Enforcement Rules
    • Quick Reference: What Goes Where
    • Reference Files
  • 项目或源文件

相关 Skill

更多
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...
音频混音工具 音频混音工具 名称:Sound Mixing Tool(标识 sound-mixing-tool) 短简介(≤60字):音乐/音效响度精确对齐 + 融合混音工作流:用 ffmpeg 两段式 loudnorm 把多组素材 LUFS 偏差压到 <0.10,再最小干预融合、导出可进引擎的独立分轨。 标签/关键词:音频混音 响度匹配 LUFS ffmpeg 游戏音频 音效设计 Wwise FMOD 分轨导出 后期处理 触发词:混音 · 响度匹配 · LUFS 对齐 · MIX 版本 · 音乐音效分轨 · 融合 · 不打架 · 不能盖住 适用场景 :游戏音频集成、影视短视频配乐、播客后期