extract-rules
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseExtract 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 appendtext
/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: (takes precedence)
.claude/extract-rules.local.md - User-level:
~/.claude/extract-rules.local.md
File format: YAML frontmatter only (no markdown body). The file uses extension for consistency with other Claude Code config files, but contains only YAML between delimiters.
.md---yaml
---用户可在中配置提取设置:
extract-rules.local.md- 项目级:(优先级更高)
.claude/extract-rules.local.md - 用户级:
~/.claude/extract-rules.local.md
**文件格式:**仅支持YAML前置元数据(无Markdown正文)。为与其他Claude Code配置文件保持一致,文件使用扩展名,但仅在分隔符之间包含YAML内容。
.md---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
undefinedlanguage: ja
undefinedOutput 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 → Full Extraction Mode (Step 1-7)
--force - → Update Mode (Step U1-U5)
--update - → Conversation Extraction Mode (Step C1-C4)
--from-conversation
通过参数判断运行模式:
- 无参数或→ 完整提取模式(步骤1-7)
--force - → 更新模式(步骤U1-U5)
--update - → 对话提取模式(步骤C1-C4)
--from-conversation
Full Extraction Mode
完整提取模式
Step 1: Load Settings
步骤1:加载配置
Search for :
extract-rules.local.md- Project-level:
.claude/extract-rules.local.md - 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:
- (default:
target_dirs- all directories)["."] - (default:
exclude_dirs)[".git", ".claude"] - (default:
exclude_patterns)["*.generated.ts", "*.d.ts", "*.min.js"] - (default:
output_dir).claude/rules - (default:
language)ja
Note: patterns are always applied. Common exclusions like , , are typically in and automatically excluded.
.gitignorenode_modules/dist/build/.gitignore搜索文件:
extract-rules.local.md- 项目级:
.claude/extract-rules.local.md - 用户级:
~/.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中配置,会被自动排除。
.gitignorenode_modules/dist/build/Step 2: Detect Project Type
步骤2:检测项目类型
Detect project language and framework:
1. Check configuration files:
- → Node.js/TypeScript/JavaScript
package.json - → TypeScript
tsconfig.json - ,
pyproject.toml→ Pythonrequirements.txt - → Go
go.mod - → Rust
Cargo.toml - → Ruby/Rails
Gemfile - ,
pom.xml→ Javabuild.gradle
2. Count file extensions:
- ,
.ts→ TypeScript.tsx - ,
.js→ JavaScript.jsx - → Python
.py - → Go
.go - → Ruby
.rb
3. Detect framework-specific files:
Identify frameworks by their config files (e.g., , , ) and dependencies in package.json, requirements.txt, Gemfile, etc.
next.config.*playwright.config.*jest.config.*Output: List of detected languages and frameworks
检测项目使用的语言和框架:
1. 检查配置文件:
- → Node.js/TypeScript/JavaScript
package.json - → TypeScript
tsconfig.json - 、
pyproject.toml→ Pythonrequirements.txt - → Go
go.mod - → Rust
Cargo.toml - → Ruby/Rails
Gemfile - 、
pom.xml→ Javabuild.gradle
2. 统计文件扩展名:
- 、
.ts→ TypeScript.tsx - 、
.js→ JavaScript.jsx - → Python
.py - → Go
.go - → Ruby
.rb
3. 检测框架特定文件:
通过框架的配置文件(如、、)以及package.json、requirements.txt、Gemfile等中的依赖项识别框架。
next.config.*playwright.config.*jest.config.***输出:**检测到的语言和框架列表
Step 3: Collect Sample Files
步骤3:收集样本文件
Collect target files for analysis:
-
Get git-tracked files (if in a git repository)
- Use to get list of tracked files
git ls-files - This automatically respects ALL files (root and subdirectories)
.gitignore - If not a git repo, fall back to Glob with manual exclusions:
- Read if present and apply patterns
.gitignore - Apply and
exclude_dirsfrom settingsexclude_patterns - Note: Nested files may not be fully respected in non-git mode
.gitignore
- Read
- Use
-
Filter files bysetting
target_dirs -
Exclude files matching:
- from settings
exclude_dirs - from settings
exclude_patterns
-
Filter by detected language extensions
-
Sample files per category, distributed across directories for representative coverage
Note: Using ensures that nested files in subdirectories are automatically respected. Untracked files (e.g., , local configs) are excluded, which helps protect sensitive information.
git ls-files.gitignore.env收集用于分析的目标文件:
-
获取Git追踪的文件(若处于Git仓库中)
- 使用获取追踪文件列表
git ls-files - 这会自动遵循所有文件(根目录和子目录的)
.gitignore - 若不是Git仓库,回退到使用Glob模式并手动排除:
- 若存在.gitignore文件则读取并应用其模式
- 应用配置中的和
exclude_dirsexclude_patterns - 注意:在非Git模式下,嵌套的.gitignore文件可能无法完全生效
- 使用
-
根据配置过滤文件
target_dirs -
排除匹配以下条件的文件:
- 配置中的
exclude_dirs - 配置中的
exclude_patterns
- 配置中的
-
根据检测到的语言扩展名过滤文件
-
按类别抽取样本文件,分布在不同目录以确保代表性覆盖
**注意:**使用可确保自动遵循子目录中的嵌套.gitignore文件。未追踪的文件(如、本地配置文件)会被排除,有助于保护敏感信息。
git ls-files.envStep 4: Analyze by Category
步骤4:按类别分析
For each detected language and framework:
-
Use Grep/Read to collect relevant code patterns
-
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
-
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)
-
For project-specific patterns:
- Extract only the minimal signature (type definition, function signature, or API combination)
- Format as one line: - brief context (2-5 words)
signature - Avoid multi-line code blocks to minimize context overhead
-
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.
针对每个检测到的语言和框架:
-
使用Grep/Read工具收集相关代码模式
-
对每个模式进行分类(参考具体示例标准):
- 通用风格选择(仅使用语言内置特性)→ 抽象原则+提示
- 项目定义的符号(项目中定义的类型、函数、钩子)→ 包含具体示例
-
对于通用风格模式:
- 将相关模式分组(例如:“优先使用const”、“避免可变操作”、“使用扩展运算符” → 不可变性原则)
- 整理为带括号实现提示的原则(2-4个关键词)
-
对于项目特定模式:
- 仅提取最小签名(类型定义、函数签名或API组合)
- 格式为单行:- 简短上下文(2-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:生成输出
-
Check if output directory exists
- If exists and not set: Error "Output directory already exists. Use --force to overwrite."
--force - If exists and set:
--force- 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
- If exists and
-
Generate rule files:
- for language-specific rules
languages/<lang>.md - for framework-specific rules
frameworks/<framework>.md - for project-specific rules
project.md
Rule file format (hybrid: principles + project-specific patterns):
markdown
---
paths:
- "**/*.ts"
- "**/*.tsx"
----
检查输出目录是否存在
- 若已存在且未设置:抛出错误“输出目录已存在。使用--force参数可覆盖现有内容。”
--force - 若已存在且设置了:
--force- 警告:“现有规则将被覆盖。手动编辑的内容将丢失。”
- 列出将被覆盖的文件
- 继续执行覆盖操作(用户需通过Git自行备份)
- 若不存在:创建目录
- 若已存在且未设置
-
生成规则文件:
- 用于语言特定规则
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
项目特定模式
- - nullable relationships
RefOrNull<T extends { id: string }> = T | { id: null } - - Page Object navigation pair
pathFor(page) + url() - returns
useAuthClient()- auth hook interface{ user, login, logout }
**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() - returns
useAuthClient()- 认证钩子接口{ 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
undefinedExtraction Complete
提取完成
Project: [project name]
Languages: [detected languages]
Frameworks: [detected frameworks]
Analyzed files: [count]
项目: [项目名称]
语言: [检测到的语言]
框架: [检测到的框架]
分析文件数: [数量]
Generated Files
生成的文件
| File | Principles |
|---|---|
| languages/typescript.md | 3 principles |
| frameworks/react.md | 2 principles |
| project.md | 2 principles |
Output: (default: .claude/rules/)
<output_dir>| 文件 | 原则数量 |
|---|---|
| languages/typescript.md | 3条原则 |
| frameworks/react.md | 2条原则 |
| project.md | 2条原则 |
输出目录: (默认:.claude/rules/)
<output_dir>Recommended Actions
推荐操作
- Review generated rules and edit if needed
- Add reference to CLAUDE.md:
```markdown
Coding Rules
See .claude/rules/ for project-specific coding rules. ``` - Re-run with when codebase evolves
/extract-rules --update
---- 审核生成的规则并按需编辑
- 在CLAUDE.md中添加引用:
markdown
## 编码规则 项目特定编码规则请查看.claude/rules/目录。 - 当代码库演进时,使用重新提取
/extract-rules --update
---Update Mode
更新模式
When is specified, re-scan the codebase and add new patterns while preserving existing rules.
--update当指定参数时,重新扫描代码库并添加新规则模式,同时保留现有规则。
--updateStep U1: Check Prerequisites
步骤U1:检查前置条件
-
Check if output directory exists (default:)
.claude/rules/- If not exists: Error "Run /extract-rules first to initialize rule files."
-
Load existing rule files to understand current rules
-
检查输出目录是否存在(默认:)
.claude/rules/- 若不存在:抛出错误“请先运行/extract-rules初始化规则文件。”
-
加载现有规则文件以了解当前规则
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:
-
Check if already exists: Compare with existing rules
- Exact match → Skip
- Similar but different → Keep both (let user review)
- New → Add
-
Preserve manual edits: Do not modify existing rules
对于每个提取的原则/模式:
-
检查是否已存在:与现有规则对比
- 完全匹配 → 跳过
- 相似但不同 → 保留两者(由用户审核)
- 新规则 → 添加
-
保留手动编辑内容:不修改现有规则
Step U4: Append New Rules
步骤U4:追加新规则
- Append new principles to appropriate section ()
## Principles - Append new project-specific patterns to appropriate section ()
## Project-specific patterns - Maintain file structure and formatting
- 将新原则追加到对应章节()
## 原则 - 将新项目特定模式追加到对应章节()
## 项目特定模式 - 保持文件结构和格式不变
Step U5: Report Changes
步骤U5:报告变更
markdown
undefinedmarkdown
undefinedUpdate Complete
更新完成
Added to languages/typescript.md:
已添加到languages/typescript.md的内容:
Principles
原则
- (none)
- 无
Project-specific patterns
项目特定模式
- returns
useNewFeature()- new feature hook{ data, refresh }
- returns
useNewFeature()- 新特性钩子{ 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 is specified, extract rules from the conversation history.
--from-conversation当指定参数时,从对话历史中提取规则。
--from-conversationStep C1: Check Prerequisites
步骤C1:检查前置条件
-
Check if output directory exists (default:)
.claude/rules/- If not exists: Error "Run /extract-rules first to initialize rule files."
-
Load existing rule files to understand current rules
-
检查输出目录是否存在(默认:)
.claude/rules/- 若不存在:抛出错误“请先运行/extract-rules初始化规则文件。”
-
加载现有规则文件以了解当前规则
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 and
type: "user"entriestype: "assistant" - 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 for nullable refs" → Include type definition
RefOrNull<T> - "Always use with
pathFor()" → Include usage patternurl()
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:追加原则与模式
-
Categorize each extracted item:
- Language-specific →
languages/<lang>.md - Framework-specific →
frameworks/<framework>.md - Project-specific →
project.md
- Language-specific →
-
Check for duplicates: Skip if already exists or covered
-
Append in appropriate format:
- Principles:
Principle name (hint1, hint2, hint3) - Project-specific patterns: - brief context (one line)
signature
- Principles:
-
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
-
将每个提取的条目分类:
- 语言特定 →
languages/<lang>.md - 框架特定 →
frameworks/<framework>.md - 项目特定 →
project.md
- 语言特定 →
-
检查重复项:若已存在或已覆盖则跳过
-
按合适格式追加:
- 原则:
原则名称(提示1, 提示2, 提示3) - 项目特定模式:- 简短上下文(单行)
签名
- 原则:
-
报告添加的内容: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 after significant discussions about coding style
--from-conversation - 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 extension
.ts
当仅有一种可行实现方式的原则:
- 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 observed | Abstract principle |
|---|---|
| Immutability (const, spread, map/filter) |
| Arrow functions, no classes, pure functions | Functional style (arrow functions, pure, no this) |
| Strict TypeScript, explicit types, no any | Type 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()must be used together)url()
Important: Keep examples minimal
- One line per pattern: - context (2-5 words)
signature - 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, spread operators, map/filter/reducelet - Standard design patterns with well-known implementations
- Framework APIs documented in official docs
当模式仅使用语言内置特性或知名模式时:
- 、
const、扩展运算符、map/filter/reducelet - 有成熟实现的标准设计模式
- 官方文档中有记录的框架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
示例分类
| Pattern | Classification | Reason |
|---|---|---|
Prefer | Principle only | Language built-in, AI knows this |
| Concrete example | Project-defined type, AI cannot infer |
| Page Object Model | Principle + hints | Well-known pattern |
| Concrete example | Project-specific API combination |
| 模式 | 分类 | 原因 |
|---|---|---|
| 优先使用const而非let | 仅原则 | 语言内置特性,AI已知晓 |
| 具体示例 | 项目定义的类型,AI无法推断 |
| 页面对象模型 | 原则+提示 | 知名模式 |
| 具体示例 | 项目特定的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:
- only analyzes tracked files, automatically excluding untracked
git ls-files, credentials, and other gitignored files.env - Warning: If or credential files are accidentally tracked in git, they WILL be included in analysis
.env - 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、凭证文件和其他被gitignore的文件.env - 警告:若或凭证文件被意外提交到Git,它们会被包含在分析中
.env - 源代码中的硬编码密钥可能会出现在示例中
- 生成规则文件时,避免包含:
- 代码中发现的API密钥、令牌或凭证
- 内部URL或端点
- 客户名称或个人信息
- 可能是密钥的高熵字符串
- 若在样本中检测到敏感信息,使用占位符替换(如)
API_KEY_REDACTED - 在提交到代码仓库前,审核生成的规则文件
- **对话提取:**同样的规则适用 - 不要从对话历史中提取敏感信息(聊天中提到的API密钥、凭证、内部URL)