extract-rules

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Extract Rules

提取规则

Analyzes existing codebase to extract project-specific coding rules and domain knowledge, generating structured markdown documentation for AI agents.
分析现有代码库,提取项目特定的编码规则和领域知识,为AI Agent生成结构化的Markdown文档。

Usage

使用方法

text
/extract-rules                      # Extract rules from codebase (initial)
/extract-rules --update             # Re-scan and add new patterns (preserve existing)
/extract-rules --force              # Overwrite all rule files (discard existing)
/extract-rules --from-conversation  # Extract rules from conversation and append
text
/extract-rules                      # 从代码库提取规则(初始提取)
/extract-rules --update             # 重新扫描并添加新规则模式(保留现有规则)
/extract-rules --force              # 覆盖所有规则文件(舍弃现有规则)
/extract-rules --from-conversation  # 从对话中提取规则并追加

Configuration

配置

Users can configure extraction settings in
extract-rules.local.md
:
  • Project-level:
    .claude/extract-rules.local.md
    (takes precedence)
  • User-level:
    ~/.claude/extract-rules.local.md
File format: YAML frontmatter only (no markdown body). The file uses
.md
extension for consistency with other Claude Code config files, but contains only YAML between
---
delimiters.
yaml
---
用户可在
extract-rules.local.md
中配置提取设置:
  • 项目级:
    .claude/extract-rules.local.md
    (优先级更高)
  • 用户级:
    ~/.claude/extract-rules.local.md
**文件格式:**仅支持YAML前置元数据(无Markdown正文)。为与其他Claude Code配置文件保持一致,文件使用
.md
扩展名,但仅在
---
分隔符之间包含YAML内容。
yaml
---

Target directories for analysis

分析的目标目录

Default: "." (all directories not excluded by .gitignore)

默认值: "."(所有未被.gitignore排除的目录)

Set specific directories to limit scope

设置特定目录以限制分析范围

target_dirs:
  • .
target_dirs:
  • .

Directories to exclude (in addition to .gitignore)

需排除的目录(除.gitignore外额外排除)

These are applied even if not in .gitignore

即使未在.gitignore中列出,这些目录也会被排除

exclude_dirs:
  • .git
  • .claude
exclude_dirs:
  • .git
  • .claude

File patterns to exclude (in addition to .gitignore)

需排除的文件模式(除.gitignore外额外排除)

exclude_patterns:
  • "*.generated.ts"
  • "*.d.ts"
  • "*.min.js"
exclude_patterns:
  • "*.generated.ts"
  • "*.d.ts"
  • "*.min.js"

Note: .gitignore patterns are automatically applied

注意:.gitignore中的模式会自动生效

Common exclusions like node_modules/, dist/, build/ are typically in .gitignore

常见的排除项如node_modules/、dist/、build/通常已在.gitignore中配置

Output directory

输出目录

output_dir: .claude/rules
output_dir: .claude/rules

Output language for reports

报告的输出语言

language: ja

undefined

language: ja

undefined

Output Structure

输出结构

text
.claude/rules/
├── languages/
│   ├── typescript.md
│   └── ...              # python.md, go.md, ruby.md, etc.
├── frameworks/
│   ├── react.md
│   └── ...              # nextjs.md, firebase.md, rails.md, etc.
└── project.md           # Domain, architecture (not portable)
text
.claude/rules/
├── languages/
│   ├── typescript.md
│   └── ...              # python.md、go.md、ruby.md等
├── frameworks/
│   ├── react.md
│   └── ...              # nextjs.md、firebase.md、rails.md等
└── project.md           # 领域、架构相关规则(不可移植)

Processing Flow

处理流程

Mode Detection

模式检测

Check arguments to determine mode:
  • No arguments or
    --force
    Full Extraction Mode (Step 1-7)
  • --update
    Update Mode (Step U1-U5)
  • --from-conversation
    Conversation Extraction Mode (Step C1-C4)

通过参数判断运行模式:
  • 无参数或
    --force
    完整提取模式(步骤1-7)
  • --update
    更新模式(步骤U1-U5)
  • --from-conversation
    对话提取模式(步骤C1-C4)

Full Extraction Mode

完整提取模式

Step 1: Load Settings

步骤1:加载配置

Search for
extract-rules.local.md
:
  1. Project-level:
    .claude/extract-rules.local.md
  2. User-level:
    ~/.claude/extract-rules.local.md
Priority:
  • If both exist, use project-level only
  • If only one exists, use that file
  • If neither exists, use default settings
Extract from settings:
  • target_dirs
    (default:
    ["."]
    - all directories)
  • exclude_dirs
    (default:
    [".git", ".claude"]
    )
  • exclude_patterns
    (default:
    ["*.generated.ts", "*.d.ts", "*.min.js"]
    )
  • output_dir
    (default:
    .claude/rules
    )
  • language
    (default:
    ja
    )
Note:
.gitignore
patterns are always applied. Common exclusions like
node_modules/
,
dist/
,
build/
are typically in
.gitignore
and automatically excluded.
搜索
extract-rules.local.md
文件:
  1. 项目级
    .claude/extract-rules.local.md
  2. 用户级
    ~/.claude/extract-rules.local.md
优先级:
  • 若两个文件都存在,仅使用项目级配置
  • 若仅存在一个文件,使用该文件的配置
  • 若都不存在,使用默认配置
从配置中提取的参数:
  • target_dirs
    (默认:
    ["."]
    - 所有目录)
  • exclude_dirs
    (默认:
    [".git", ".claude"]
  • exclude_patterns
    (默认:
    ["*.generated.ts", "*.d.ts", "*.min.js"]
  • output_dir
    (默认:
    .claude/rules
  • language
    (默认:
    ja
注意:
.gitignore
中的模式会自动生效。常见的排除项如
node_modules/
dist/
build/
通常已在.gitignore中配置,会被自动排除。

Step 2: Detect Project Type

步骤2:检测项目类型

Detect project language and framework:
1. Check configuration files:
  • package.json
    → Node.js/TypeScript/JavaScript
  • tsconfig.json
    → TypeScript
  • pyproject.toml
    ,
    requirements.txt
    → Python
  • go.mod
    → Go
  • Cargo.toml
    → Rust
  • Gemfile
    → Ruby/Rails
  • pom.xml
    ,
    build.gradle
    → Java
2. Count file extensions:
  • .ts
    ,
    .tsx
    → TypeScript
  • .js
    ,
    .jsx
    → JavaScript
  • .py
    → Python
  • .go
    → Go
  • .rb
    → Ruby
3. Detect framework-specific files:
Identify frameworks by their config files (e.g.,
next.config.*
,
playwright.config.*
,
jest.config.*
) and dependencies in package.json, requirements.txt, Gemfile, etc.
Output: List of detected languages and frameworks
检测项目使用的语言和框架:
1. 检查配置文件:
  • package.json
    → Node.js/TypeScript/JavaScript
  • tsconfig.json
    → TypeScript
  • pyproject.toml
    requirements.txt
    → Python
  • go.mod
    → Go
  • Cargo.toml
    → Rust
  • Gemfile
    → Ruby/Rails
  • pom.xml
    build.gradle
    → Java
2. 统计文件扩展名:
  • .ts
    .tsx
    → TypeScript
  • .js
    .jsx
    → JavaScript
  • .py
    → Python
  • .go
    → Go
  • .rb
    → Ruby
3. 检测框架特定文件:
通过框架的配置文件(如
next.config.*
playwright.config.*
jest.config.*
)以及package.json、requirements.txt、Gemfile等中的依赖项识别框架。
**输出:**检测到的语言和框架列表

Step 3: Collect Sample Files

步骤3:收集样本文件

Collect target files for analysis:
  1. Get git-tracked files (if in a git repository)
    • Use
      git ls-files
      to get list of tracked files
    • This automatically respects ALL
      .gitignore
      files (root and subdirectories)
    • If not a git repo, fall back to Glob with manual exclusions:
      • Read
        .gitignore
        if present and apply patterns
      • Apply
        exclude_dirs
        and
        exclude_patterns
        from settings
      • Note: Nested
        .gitignore
        files may not be fully respected in non-git mode
  2. Filter files by
    target_dirs
    setting
  3. Exclude files matching:
    • exclude_dirs
      from settings
    • exclude_patterns
      from settings
  4. Filter by detected language extensions
  5. Sample files per category, distributed across directories for representative coverage
Note: Using
git ls-files
ensures that nested
.gitignore
files in subdirectories are automatically respected. Untracked files (e.g.,
.env
, local configs) are excluded, which helps protect sensitive information.
收集用于分析的目标文件:
  1. 获取Git追踪的文件(若处于Git仓库中)
    • 使用
      git ls-files
      获取追踪文件列表
    • 这会自动遵循所有
      .gitignore
      文件(根目录和子目录的)
    • 若不是Git仓库,回退到使用Glob模式并手动排除:
      • 若存在.gitignore文件则读取并应用其模式
      • 应用配置中的
        exclude_dirs
        exclude_patterns
      • 注意:在非Git模式下,嵌套的.gitignore文件可能无法完全生效
  2. 根据
    target_dirs
    配置过滤文件
  3. 排除匹配以下条件的文件:
    • 配置中的
      exclude_dirs
    • 配置中的
      exclude_patterns
  4. 根据检测到的语言扩展名过滤文件
  5. 按类别抽取样本文件,分布在不同目录以确保代表性覆盖
**注意:**使用
git ls-files
可确保自动遵循子目录中的嵌套.gitignore文件。未追踪的文件(如
.env
、本地配置文件)会被排除,有助于保护敏感信息。

Step 4: Analyze by Category

步骤4:按类别分析

For each detected language and framework:
  1. Use Grep/Read to collect relevant code patterns
  2. Classify each pattern (see Concrete Example Criteria):
    • General style choice (uses only language built-ins) → Abstract principle + hints
    • Project-defined symbol (types, functions, hooks defined in project) → Include concrete example
  3. For general style patterns:
    • Group related patterns (e.g., "prefer const", "avoid mutations", "use spread" → Immutability)
    • Formulate as principle with parenthetical implementation hints (2-4 keywords)
  4. For project-specific patterns:
    • Extract only the minimal signature (type definition, function signature, or API combination)
    • Format as one line:
      signature
      - brief context (2-5 words)
    • Avoid multi-line code blocks to minimize context overhead
  5. Apply AI judgment to determine which patterns meet the extraction criteria (see Principle Extraction Criteria)
Determine appropriate detection methods based on language and project structure.
针对每个检测到的语言和框架:
  1. 使用Grep/Read工具收集相关代码模式
  2. 对每个模式进行分类(参考具体示例标准):
    • 通用风格选择(仅使用语言内置特性)→ 抽象原则+提示
    • 项目定义的符号(项目中定义的类型、函数、钩子)→ 包含具体示例
  3. 对于通用风格模式:
    • 将相关模式分组(例如:“优先使用const”、“避免可变操作”、“使用扩展运算符” → 不可变性原则)
    • 整理为带括号实现提示的原则(2-4个关键词)
  4. 对于项目特定模式:
    • 仅提取最小签名(类型定义、函数签名或API组合)
    • 格式为单行:
      签名
      - 简短上下文(2-5个词)
    • 避免使用多行代码块,以减少上下文开销
  5. 运用AI判断哪些模式符合提取标准(参考原则提取标准)
根据语言和项目结构选择合适的检测方法。

Step 5: Analyze Documentation

步骤5:分析文档

Also analyze non-code documentation:
  • README.md
  • CONTRIBUTING.md
  • PR templates
  • Existing CLAUDE.md
Extract explicit coding rules and guidelines from these documents.
同时分析非代码文档:
  • README.md
  • CONTRIBUTING.md
  • PR模板
  • 已有的CLAUDE.md
从这些文档中提取明确的编码规则和指南。

Step 6: Generate Output

步骤6:生成输出

  1. Check if output directory exists
    • If exists and
      --force
      not set: Error "Output directory already exists. Use --force to overwrite."
    • If exists and
      --force
      set:
      • Warning: "Existing rules will be overwritten. Manual edits will be lost."
      • List files that will be overwritten
      • Proceed with overwrite (backup is user's responsibility via git)
    • If not exists: Create directory
  2. Generate rule files:
    • languages/<lang>.md
      for language-specific rules
    • frameworks/<framework>.md
      for framework-specific rules
    • project.md
      for project-specific rules
Rule file format (hybrid: principles + project-specific patterns):
markdown
---
paths:
  - "**/*.ts"
  - "**/*.tsx"
---
  1. 检查输出目录是否存在
    • 若已存在且未设置
      --force
      :抛出错误“输出目录已存在。使用--force参数可覆盖现有内容。”
    • 若已存在且设置了
      --force
      • 警告:“现有规则将被覆盖。手动编辑的内容将丢失。”
      • 列出将被覆盖的文件
      • 继续执行覆盖操作(用户需通过Git自行备份)
    • 若不存在:创建目录
  2. 生成规则文件:
    • languages/<lang>.md
      用于语言特定规则
    • frameworks/<framework>.md
      用于框架特定规则
    • project.md
      用于项目特定规则
规则文件格式(混合式:原则+项目特定模式):
markdown
---
paths:
  - "**/*.ts"
  - "**/*.tsx"
---

TypeScript Rules

TypeScript规则

Principles

原则

  • Immutability (spread演算子, map/filter/reduce, const優先)
  • Declarative style (命令的ループより宣言的変換)
  • Type safety (strict mode, 明示的型注釈, any禁止)
  • 不可变性(扩展运算符、map/filter/reduce、优先使用const)
  • 声明式风格(优先声明式转换而非命令式循环)
  • 类型安全(严格模式、显式类型注解、禁止使用any)

Project-specific patterns

项目特定模式

  • RefOrNull<T extends { id: string }> = T | { id: null }
    - nullable relationships
  • pathFor(page) + url()
    - Page Object navigation pair
  • useAuthClient()
    returns
    { user, login, logout }
    - auth hook interface

**Format guidelines:**

For **Principles** section:
- Each principle: `Principle name (hint1, hint2, hint3)`
- 2-4 implementation hints per principle
- Only for general style choices (language built-ins)

For **Project-specific patterns** section:
- **One line per pattern**: `signature/definition` - brief context
- Use inline code for signatures, not code blocks
- Keep context to 2-5 words maximum
- Only include the minimal signature needed for AI to infer usage

**paths patterns by category:**
- TypeScript: `**/*.ts`, `**/*.tsx`
- Python: `**/*.py`
- React: `**/*.tsx`, `**/*.jsx`
- (project.md: no paths frontmatter = applies to all files)
  • RefOrNull<T extends { id: string }> = T | { id: null }
    - 可空关联关系
  • pathFor(page) + url()
    - 页面对象导航组合
  • useAuthClient()
    returns
    { user, login, logout }
    - 认证钩子接口

**格式指南:**

对于**原则**部分:
- 每条原则格式:`原则名称(提示1, 提示2, 提示3)`
- 每条原则包含2-4个实现提示
- 仅适用于通用风格选择(语言内置特性)

对于**项目特定模式**部分:
- **每条模式占一行**:`签名/定义` - 简短上下文
- 签名使用行内代码格式,而非代码块
- 上下文控制在2-5个词以内
- 仅包含AI推断用法所需的最小签名

**按类别设置paths模式:**
- TypeScript: `**/*.ts`, `**/*.tsx`
- Python: `**/*.py`
- React: `**/*.tsx`, `**/*.jsx`
- (project.md: 无paths前置元数据 = 适用于所有文件)

Step 7: Report Summary

步骤7:生成总结报告

Display analysis summary:
markdown
undefined
显示分析总结:
markdown
undefined

Extraction Complete

提取完成

Project: [project name] Languages: [detected languages] Frameworks: [detected frameworks] Analyzed files: [count]
项目: [项目名称] 语言: [检测到的语言] 框架: [检测到的框架] 分析文件数: [数量]

Generated Files

生成的文件

FilePrinciples
languages/typescript.md3 principles
frameworks/react.md2 principles
project.md2 principles
Output:
<output_dir>
(default: .claude/rules/)
文件原则数量
languages/typescript.md3条原则
frameworks/react.md2条原则
project.md2条原则
输出目录:
<output_dir>
(默认:.claude/rules/)

Recommended Actions

推荐操作

  1. Review generated rules and edit if needed
  2. Add reference to CLAUDE.md: ```markdown

    Coding Rules

    See .claude/rules/ for project-specific coding rules. ```
  3. Re-run with
    /extract-rules --update
    when codebase evolves

---
  1. 审核生成的规则并按需编辑
  2. 在CLAUDE.md中添加引用:
    markdown
    ## 编码规则
    项目特定编码规则请查看.claude/rules/目录。
  3. 当代码库演进时,使用
    /extract-rules --update
    重新提取

---

Update Mode

更新模式

When
--update
is specified, re-scan the codebase and add new patterns while preserving existing rules.
当指定
--update
参数时,重新扫描代码库并添加新规则模式,同时保留现有规则。

Step U1: Check Prerequisites

步骤U1:检查前置条件

  1. Check if output directory exists (default:
    .claude/rules/
    )
    • If not exists: Error "Run /extract-rules first to initialize rule files."
  2. Load existing rule files to understand current rules
  1. 检查输出目录是否存在(默认:
    .claude/rules/
    • 若不存在:抛出错误“请先运行/extract-rules初始化规则文件。”
  2. 加载现有规则文件以了解当前规则

Step U2: Re-scan Codebase

步骤U2:重新扫描代码库

Execute Step 1-5 from Full Extraction Mode:
  • Load settings
  • Detect project type
  • Collect sample files
  • Analyze by category
  • Analyze documentation
执行完整提取模式中的步骤1-5:
  • 加载配置
  • 检测项目类型
  • 收集样本文件
  • 按类别分析
  • 分析文档

Step U3: Compare and Merge

步骤U3:对比与合并

For each extracted principle/pattern:
  1. Check if already exists: Compare with existing rules
    • Exact match → Skip
    • Similar but different → Keep both (let user review)
    • New → Add
  2. Preserve manual edits: Do not modify existing rules
对于每个提取的原则/模式:
  1. 检查是否已存在:与现有规则对比
    • 完全匹配 → 跳过
    • 相似但不同 → 保留两者(由用户审核)
    • 新规则 → 添加
  2. 保留手动编辑内容:不修改现有规则

Step U4: Append New Rules

步骤U4:追加新规则

  1. Append new principles to appropriate section (
    ## Principles
    )
  2. Append new project-specific patterns to appropriate section (
    ## Project-specific patterns
    )
  3. Maintain file structure and formatting
  1. 将新原则追加到对应章节(
    ## 原则
  2. 将新项目特定模式追加到对应章节(
    ## 项目特定模式
  3. 保持文件结构和格式不变

Step U5: Report Changes

步骤U5:报告变更

markdown
undefined
markdown
undefined

Update Complete

更新完成

Added to languages/typescript.md:

已添加到languages/typescript.md的内容:

Principles

原则

  • (none)

Project-specific patterns

项目特定模式

  • useNewFeature()
    returns
    { data, refresh }
    - new feature hook
  • useNewFeature()
    returns
    { data, refresh }
    - 新特性钩子

Added to frameworks/react.md:

已添加到frameworks/react.md的内容:

  • (none)

Unchanged files:

未变更的文件:

  • project.md
Tip: Review added rules and remove any that are incorrect or redundant.

---
  • project.md
提示: 审核新增规则,移除不正确或冗余的内容。

---

Conversation Extraction Mode

对话提取模式

When
--from-conversation
is specified, extract rules from the conversation history.
当指定
--from-conversation
参数时,从对话历史中提取规则。

Step C1: Check Prerequisites

步骤C1:检查前置条件

  1. Check if output directory exists (default:
    .claude/rules/
    )
    • If not exists: Error "Run /extract-rules first to initialize rule files."
  2. Load existing rule files to understand current rules
  1. 检查输出目录是否存在(默认:
    .claude/rules/
    • 若不存在:抛出错误“请先运行/extract-rules初始化规则文件。”
  2. 加载现有规则文件以了解当前规则

Step C2: Determine Conversation Source

步骤C2:确定对话来源

Option A: Read from transcript file (preferred, full history)
If transcript file path is known:
  • Location:
    ~/.claude/projects/<project-path>/<session-id>.jsonl
  • Read the JSONL file (each line is a JSON object)
  • Focus on
    type: "user"
    and
    type: "assistant"
    entries
  • This includes ALL messages from session start (even after compaction)
Option B: Use current context (fallback)
If transcript path is unknown (e.g., running in Codex or other AI tools):
  • Analyze the current conversation context
  • Note: May have limited history if context was compacted
选项A:从转录文件读取(推荐,完整历史)
若已知转录文件路径:
  • 路径:
    ~/.claude/projects/<project-path>/<session-id>.jsonl
  • 读取JSONL文件(每行是一个JSON对象)
  • 重点关注
    type: "user"
    type: "assistant"
    的条目
  • 这包含会话开始以来的所有消息(即使经过压缩)
选项B:使用当前上下文(备选)
若未知转录文件路径(例如在Codex或其他AI工具中运行):
  • 分析当前对话上下文
  • 注意:若上下文已被压缩,可能仅包含有限的历史内容

Step C3: Extract Principles and Patterns

步骤C3:提取原则与模式

Look for user preferences and classify them (same as Full Extraction Mode):
1. General style preferences → Abstract to principles:
  • "Use type instead of interface" → Type safety principle
  • "Avoid mutations" → Immutability principle
2. Project-specific patterns → Extract with concrete examples:
  • "Use
    RefOrNull<T>
    for nullable refs" → Include type definition
  • "Always use
    pathFor()
    with
    url()
    " → Include usage pattern
3. Code review feedback: Identify underlying philosophy or specific patterns
Apply the same criteria as Full Extraction Mode (see Principle Extraction Criteria and Concrete Example Criteria).
识别用户偏好并进行分类(与完整提取模式相同):
1. 通用风格偏好 → 抽象为原则:
  • “使用type而非interface” → 类型安全原则
  • “避免可变操作” → 不可变性原则
2. 项目特定模式 → 提取具体示例:
  • “使用
    RefOrNull<T>
    处理可空引用” → 包含类型定义
  • “始终将
    pathFor()
    url()
    配合使用” → 包含使用模式
3. 代码评审反馈:识别底层设计理念或特定模式
应用与完整提取模式相同的标准(参考原则提取标准和具体示例标准)。

Step C4: Append Principles and Patterns

步骤C4:追加原则与模式

  1. Categorize each extracted item:
    • Language-specific →
      languages/<lang>.md
    • Framework-specific →
      frameworks/<framework>.md
    • Project-specific →
      project.md
  2. Check for duplicates: Skip if already exists or covered
  3. Append in appropriate format:
    • Principles:
      Principle name (hint1, hint2, hint3)
    • Project-specific patterns:
      signature
      - brief context (one line)
  4. Report what was added:
    markdown
    ## Extracted from Conversation
    
    ### Added to languages/typescript.md:
    #### Principles
    - Immutability (spread operators, map/filter, avoid mutations)
    
    #### Project-specific patterns
    - `RefOrNull<T extends { id: string }> = T | { id: null }` - nullable refs
    
    ### No changes:
    - Functional style - Already documented

  1. 将每个提取的条目分类:
    • 语言特定 →
      languages/<lang>.md
    • 框架特定 →
      frameworks/<framework>.md
    • 项目特定 →
      project.md
  2. 检查重复项:若已存在或已覆盖则跳过
  3. 按合适格式追加:
    • 原则:
      原则名称(提示1, 提示2, 提示3)
    • 项目特定模式:
      签名
      - 简短上下文(单行)
  4. 报告添加的内容:
    markdown
    ## 从对话中提取的内容
    
    ### 已添加到languages/typescript.md的内容:
    #### 原则
    - 不可变性(扩展运算符、map/filter、避免可变操作)
    
    #### 项目特定模式
    - `RefOrNull<T extends { id: string }> = T | { id: null }` - 可空引用
    
    ### 无变更:
    - 函数式风格 - 已记录

Important Notes

重要说明

  • This skill uses AI to understand intent, not just pattern matching
  • Both code AND documentation are analyzed
  • Use
    --from-conversation
    after significant discussions about coding style
  • Generated rules are meant to be reviewed and refined by humans
  • 该技能使用AI理解意图,而非仅进行模式匹配
  • 同时分析代码和文档
  • 在关于编码风格的重要讨论后,使用
    --from-conversation
    提取规则
  • 生成的规则需由人工审核和完善

Principle Extraction Criteria

原则提取标准

Goal: Extract abstract principles that guide AI to write code consistent with project style.
**目标:**提取抽象原则,指导AI写出符合项目风格的代码。

Extract these principles

需提取的原则

Principles where multiple common approaches exist and AI might choose differently without guidance:
  • Immutability vs Mutability - AI often writes mutable code by default
  • Declarative vs Imperative - Both are common approaches
  • Functional vs Class-based - Both are valid paradigms
  • OOP vs FP - Different design philosophies
当存在多种常见实现方式,且AI在无指导时可能做出不同选择的原则:
  • 不可变性 vs 可变性 - AI默认常写出可变代码
  • 声明式 vs 命令式 - 两种方式都很常见
  • 函数式 vs 基于类 - 两种范式都有效
  • 面向对象 vs 函数式编程 - 不同的设计理念

Do NOT extract these

无需提取的原则

Principles where only one practical approach exists:
  • React components use PascalCase (no alternative)
  • Python uses snake_case (language standard)
  • TypeScript files use
    .ts
    extension
仅有一种可行实现方式的原则:
  • React组件使用PascalCase命名(无其他选择)
  • Python使用snake_case命名(语言标准)
  • TypeScript文件使用
    .ts
    扩展名

Decision criterion

判断标准

"Would a general AI write code differently without this principle?"
  • Yes → Extract it
  • No → Skip it
“如果没有这条原则,通用AI会写出不同风格的代码吗?”
  • → 提取该原则
  • → 跳过

Abstraction examples

抽象示例

Concrete patterns observedAbstract principle
const
preferred, spread operators, no mutations
Immutability (const, spread, map/filter)
Arrow functions, no classes, pure functionsFunctional style (arrow functions, pure, no this)
Strict TypeScript, explicit types, no anyType safety (strict, explicit, no any)
观察到的具体模式抽象原则
优先使用const、扩展运算符、无可变操作不可变性(const、扩展运算符、map/filter)
箭头函数、无类、纯函数函数式风格(箭头函数、纯函数、无this)
严格TypeScript、显式类型、禁止any类型安全(严格模式、显式类型、无any)

Concrete Example Criteria

具体示例标准

Goal: Determine when to include concrete code examples vs abstract principles.
**目标:**确定何时包含具体代码示例,何时使用抽象原则。

Include concrete examples when

需包含具体示例的情况

Pattern involves project-defined symbols that AI cannot infer:
  • Custom types/interfaces defined in the project (not from node_modules)
  • Project-specific hooks (e.g.,
    useAuthClient
    ,
    useDataFetch
    )
  • Utility functions with non-obvious signatures
  • Non-obvious combinations (e.g.,
    pathFor()
    +
    url()
    must be used together)
Important: Keep examples minimal
  • One line per pattern:
    signature
    - context (2-5 words)
  • Include only the type signature or function signature
  • Omit implementation details, only show the "shape" AI needs to know
当模式涉及项目定义的符号,且AI无法自行推断时:
  • 项目中定义的自定义类型/接口(非来自node_modules)
  • 项目特定钩子(如
    useAuthClient
    useDataFetch
  • 签名不明显的工具函数
  • 非直观的API组合(如
    pathFor()
    +
    url()
    必须配合使用)
重要提示:示例需保持简洁
  • 每条模式占一行:
    签名
    - 上下文(2-5个词)
  • 仅包含类型签名或函数签名
  • 省略实现细节,仅展示AI需要了解的“结构”

Keep abstract (principles only) when

仅使用抽象原则的情况

Pattern uses only language built-ins or well-known patterns:
  • const
    ,
    let
    , spread operators, map/filter/reduce
  • Standard design patterns with well-known implementations
  • Framework APIs documented in official docs
当模式仅使用语言内置特性知名模式时:
  • const
    let
    、扩展运算符、map/filter/reduce
  • 有成熟实现的标准设计模式
  • 官方文档中有记录的框架API

Decision criterion

判断标准

"Can AI correctly implement this pattern by knowing only its name?"
  • Yes → Abstract principle with hints
  • No → Include concrete example
“仅知道名称,AI就能正确实现该模式吗?”
  • → 使用带提示的抽象原则
  • → 包含具体示例

Example classification

示例分类

PatternClassificationReason
Prefer
const
over
let
Principle onlyLanguage built-in, AI knows this
RefOrNull<T>
type usage
Concrete exampleProject-defined type, AI cannot infer
Page Object ModelPrinciple + hintsWell-known pattern
pathFor()
+
url()
combination
Concrete exampleProject-specific API combination
模式分类原因
优先使用const而非let仅原则语言内置特性,AI已知晓
RefOrNull<T>
类型的使用
具体示例项目定义的类型,AI无法推断
页面对象模型原则+提示知名模式
pathFor()
+
url()
组合
具体示例项目特定的API组合

Gray zone handling

灰色地带处理

For patterns that are not clearly general or project-specific:
  • Extended types from node_modules (e.g.,
    type MyUser = User & { custom: string }
    )
  • Specific combinations of standard libraries (e.g., zod + react-hook-form patterns)
Fallback rule: When uncertain, include a concrete example.
Rationale: Over-specifying is less harmful than under-specifying. An unnecessary example adds minimal context overhead, but a missing example may cause AI to guess incorrectly.
对于无法明确归为通用或项目特定的模式:
  • 从node_modules扩展的类型(如
    type MyUser = User & { custom: string }
  • 标准库的特定组合(如zod + react-hook-form模式)
** fallback规则:不确定时,包含具体示例。**
理由:过度指定的危害小于指定不足。不必要的示例仅会增加少量上下文开销,但缺失示例可能导致AI猜测错误。

Security Considerations

安全注意事项

Sensitive Information Protection:
  • git ls-files
    only analyzes tracked files, automatically excluding untracked
    .env
    , credentials, and other gitignored files
  • Warning: If
    .env
    or credential files are accidentally tracked in git, they WILL be included in analysis
  • Hardcoded secrets in source code may appear in examples
  • When generating rule files, avoid including:
    • API keys, tokens, or credentials found in code
    • Internal URLs or endpoints
    • Customer names or personal information
    • High-entropy strings that may be secrets
  • If sensitive information is detected in samples, redact with placeholders (e.g.,
    API_KEY_REDACTED
    )
  • Review generated rule files before committing to repository
  • Conversation extraction: Same rules apply - do not extract sensitive information from conversation history (API keys, credentials, internal URLs mentioned in chat)
敏感信息保护:
  • git ls-files
    仅分析追踪的文件,自动排除未追踪的
    .env
    、凭证文件和其他被gitignore的文件
  • 警告:
    .env
    或凭证文件被意外提交到Git,它们
    被包含在分析中
  • 源代码中的硬编码密钥可能会出现在示例中
  • 生成规则文件时,避免包含:
    • 代码中发现的API密钥、令牌或凭证
    • 内部URL或端点
    • 客户名称或个人信息
    • 可能是密钥的高熵字符串
  • 若在样本中检测到敏感信息,使用占位符替换(如
    API_KEY_REDACTED
  • 在提交到代码仓库前,审核生成的规则文件
  • **对话提取:**同样的规则适用 - 不要从对话历史中提取敏感信息(聊天中提到的API密钥、凭证、内部URL)