关于 patchwork — Codebase Conventions for AI Agents
patchwork 是用于分析代码库约定的工具,可生成 CONVENTIONS.md,也能通过 MCP 工具向编码 Agent 提供约定。它使用 AST 分析提取命名、结构、测试和 API 模式,分析在本地完成。
主要功能
- 01AST 分析代码约定
- 02生成 CONVENTIONS.md 或 AGENTS.md
- 03检测命名、导入与项目结构
- 04提取错误处理、测试和 API 模式
- 05检查约定并监视变更
- 06本地分析,无 API 调用
适用场景
- 01为编码 Agent 提供项目命名规则
- 02创建文件前了解目录组织方式
- 03编写测试或错误处理时参考现有模式
- 04在 CI 中检查约定变化
MCP 相关
MCP 服务提供 8 个工具,供 Agent 查询代码库约定、检查拟用名称及了解项目结构、技术栈、测试和 Git 风格。
配置
本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。
工具
本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。
详细介绍
patchwork
挖掘你的代码库。生成 CONVENTIONS.md。阻止 AI Agent 胡乱编造你的代码风格。
每个使用 AI 编码助手的团队都会遇到同样的问题:Claude 在使用 get_user_by_id 的代码库中写出 getUserById。Cursor 在使用 user-card.tsx 的项目中创建 components/userCard.tsx。Agent 编造了一种与 API 其余部分不匹配的响应格式。
你手动编写 CLAUDE.md。两周后它就过时了。于是你又重新编写。
patchwork 可自动完成这项工作。 它使用 AST 分析扫描你的实际源代码,识别团队真正采用的做法,而不是你以为自己采用的做法。
可检测的内容
| 类别 | 挖掘内容 |
|---|---|
| 命名 | 函数、类、变量、常量、文件——附带置信度评分和真实示例 |
| 导入 | 绝对导入与相对导入、路径别名(@/、src/)、barrel 文件、解构风格 |
| 结构 | 源代码根目录、测试布局、按功能或按层组织、monorepo 检测 |
| 错误处理 | try/except 与 Result 类型、日志框架、自定义异常命名、传播风格 |
| 测试 | 框架、断言风格、模拟库、覆盖率工具、fixture 模式 |
| API 模式 | 响应格式、路由参数风格、ORM、异步模式、是否使用 GraphQL/gRPC |
| Git 工作流 | 提交消息风格、分支命名、共同变更的文件对 |
| 技术栈 | 框架、包管理器、linter、格式化工具、类型检查器、构建工具、脚本 |
快速开始
pip install patchwork-conventions
cd your-project
patchwork scan
就是这样。你将得到类似这样的 CONVENTIONS.md:
# CONVENTIONS.md
> Auto-generated by patchwork on 2026-06-25
## Tech Stack
**Language:** python
**Runtime:** Python >=3.11
**Package Manager:** uv
**Frameworks:** fastapi, sqlalchemy
**Linters:** ruff
**Formatters:** ruff, black
## Naming Conventions
### Python
- **Functions:** `snake_case` (97% consistent)
- Examples: `get_user`, `parse_response`, `create_session`
- **Classes:** `PascalCase` (100% consistent)
- Examples: `UserService`, `AuthHandler`, `DatabaseClient`
- **Constants:** `SCREAMING_SNAKE`
- Examples: `MAX_RETRIES`, `API_BASE_URL`
- **Files:** `snake_case`
- **Private prefix:** `_`
- **Test functions:** prefix `test_`
## Project Structure
**Source root:** `src/`
**Organisation:** layer-based
**Tests:** separate (`tests/`)
**Key directories:**
- `src/` — source root
- `tests/` — test suite
- `migrations/` — database migrations
## Error Handling
### Python
- **Pattern:** try/except
- **Propagation:** raise
- **Logging:** `structlog`
- **Custom exception naming:** Error suffix
- `ValidationError`, `AuthError`, `NotFoundError`
## Testing Conventions
### Python
- **Framework:** pytest
- **Coverage:** 34 test files / 89 source files (38% ratio)
- **Assertions:** `assert(...)`
- **Coverage tool:** `pytest-cov`
- **Patterns:** fixtures, factories
## Git Conventions
- **Commit style:** conventional commits
- **Examples:** `feat(auth): add JWT refresh`, `fix(api): handle null user`
- **Branch naming:** feature/name + fix/name
为什么不选 argus 或 sourcebook?
| 功能 | patchwork | argus | sourcebook |
|---|---|---|---|
| 基于 AST 的命名分析 | ✅ tree-sitter | ❌ 仅文件系统 | ❌ 未实现 |
| 置信度评分 | ✅ 按类别 | ❌ | ❌ |
| 来自代码的真实示例 | ✅ | ❌ | ❌ |
| 反例(不一致之处) | ✅ | ❌ | ❌ |
| 错误处理模式挖掘 | ✅ | ❌ | ❌ |
| API 响应格式检测 | ✅ | ❌ | ❌ |
| 共同变更的文件对 | ✅ | ❌ | ✅ |
约定检查(check 命令) | ✅ | ❌ | ❌ |
| 含 8 个工具的 MCP 服务 | ✅ | ❌ | ✅(4 个工具) |
| 监视模式 | ✅ | ✅(sync) | ✅ |
| 无需 LLM | ✅ | ✅ | ✅(第 A 层) |
| 开源 / MIT | ✅ | ✅ | ❌ BSL |
命令
# Generate CONVENTIONS.md
patchwork scan
# Generate for a specific path
patchwork scan /path/to/project
# Generate AGENTS.md
patchwork scan --agents-md
# Append to CLAUDE.md
patchwork scan --claude-md
# Output JSON (for programmatic use)
patchwork scan --json
# Print to stdout (don't write file)
patchwork scan --stdout
# Limit to specific languages
patchwork scan --lang python --lang typescript
# Re-scan and update, preserving manual edits
patchwork update
# Show what would change
patchwork diff
# Print detected conventions to terminal
patchwork show
# Auto-watch mode (regenerate on change)
patchwork watch
# Start MCP server
patchwork serve --stdio # for Claude Code
patchwork serve --port 3742 # HTTP mode
Claude Code 集成
选项 1:CONVENTIONS.md(推荐)
patchwork scan # run once
# CONVENTIONS.md is automatically read by Claude Code
选项 2:追加到 CLAUDE.md
patchwork scan --claude-md
选项 3:MCP 服务
Claude Code — 添加到 ~/.claude.json(或交互式运行 claude mcp add):
{
"mcpServers": {
"patchwork": {
"command": "patchwork",
"args": ["serve", "/path/to/your/project", "--stdio"]
}
}
}
Claude Desktop — 添加到 ~/Library/Application Support/Claude/claude_desktop_config.json(macOS)或 %APPDATA%\Claude\claude_desktop_config.json(Windows):
{
"mcpServers": {
"patchwork": {
"command": "patchwork",
"args": ["serve", "/path/to/your/project", "--stdio"]
}
}
}
Cursor — 添加到项目根目录下的 .cursor/mcp.json:
{
"mcpServers": {
"patchwork": {
"command": "patchwork",
"args": ["serve", ".", "--stdio"]
}
}
}
然后,你的 AI Agent 就可以按需使用 8 个工具:
| 工具 | 使用时机 |
|---|---|
patchwork_scan | 获取完整的约定概览 |
patchwork_naming | 编写新的标识符之前 |
patchwork_structure | 创建新文件或目录之前 |
patchwork_stack | 选择库或命令时 |
patchwork_errors | 编写错误处理之前 |
patchwork_testing | 编写测试文件之前 |
patchwork_git | 编写提交消息之前 |
patchwork_check | 验证拟定的名称 |
选项 4:Claude Code 技能(SKILL.md)
将此仓库中的 SKILL.md 复制到 ~/.claude/skills/patchwork/SKILL.md,即可使用 /patchwork 斜杠命令。
监视模式(CI/自动更新)
# Keep CONVENTIONS.md updated as you code
patchwork watch &
# Or in CI — fail if conventions changed
patchwork diff || (patchwork update && git add CONVENTIONS.md && git commit -m "chore: update conventions")
Python API
from patchwork import scan
from patchwork.scanner import ScanOptions
from pathlib import Path
# Full scan
report = scan(ScanOptions(root=Path(".")))
# Render to markdown
print(report.to_markdown())
# Render to JSON
import json
data = json.loads(report.to_json())
# Access specific results
naming = report.naming.get("python")
print(f"Functions: {naming.functions.style} ({naming.functions.confidence:.0%})")
print(f"Examples: {naming.functions.examples}")
structure = report.structure
print(f"Source root: {structure.source_root}")
print(f"Organisation: {structure.organisation}")
支持的语言
| 语言 | AST(tree-sitter) | 正则回退 |
|---|---|---|
| Python | ✅ 完整 | ✅ |
| TypeScript | ✅ 完整 | ✅ |
| JavaScript | ✅ 完整 | ✅ |
| Go | ✅(需安装 full extra) | ✅ |
| Rust | ✅(需安装 full extra) | ✅ |
| Java | ✅(需安装 full extra) | ✅ |
| Ruby、PHP、C#、C++ | ❌ | ✅ 仅正则 |
安装完整语言支持:
pip install 'patchwork-conventions[full]'
工作原理
your codebase
│
▼
ConfigDetector ← reads package.json, pyproject.toml, go.mod, Cargo.toml
│
▼
File discovery ← respects .gitignore, skips node_modules etc.
│
▼
Per-language AST ← tree-sitter parses every file into a syntax tree
│
├── NamingMiner → extracts function/class/variable names, classifies style
├── ImportMiner → detects import patterns, aliases, barrel files
├── StructureMiner → analyses directory layout, test co-location
├── ErrorHandlingMiner → detects try/catch patterns, logging, custom exceptions
├── TestingMiner → identifies framework, assertion style, mocking
├── APIPatternMiner → finds response shapes, ORMs, route styles
└── GitPatternMiner → mines commit history, branches, co-change pairs
│
▼
ConventionReport
│
├── CONVENTIONS.md (default)
├── AGENTS.md (--agents-md)
├── CLAUDE.md (--claude-md, appends)
└── JSON (--json)
所有分析都在完全本地进行——不会调用 API,不会进行遥测,也不会有任何数据离开你的设备。
性能
在一个包含 1,000 个文件的 TypeScript 单体仓库中:
- 不使用 tree-sitter:约 0.8 秒
- 使用 tree-sitter(完整 AST):约 2.1 秒
在一个包含 500 个文件的 Python 项目中:
- 约 1.1 秒
结果是确定性的——相同的代码库始终会产生相同的输出。
贡献
git clone https://github.com/yourusername/patchwork
cd patchwork
pip install -e '.[dev]'
pytest
欢迎提交拉取请求。请参阅 CONTRIBUTING.md。
许可证
MIT——可免费用于个人和商业用途。
主题
claude-code · agent-skills · mcp · context-engineering · hallucination-detection · code-conventions · static-analysis · tree-sitter · developer-tools · ai-coding
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。