AGENTS.md — 开发规范 / Development Guidelines
本文件为所有 AI 编码助手(Claude Code、pi、Cursor 等)提供统一的开发指导。
This file provides unified development guidelines for all AI coding assistants.
最后更新 / Last Updated: 2026-06-10
目录 / Table of Contents
- 语言 / Language
- 代码风格 / Code Style
- 禁止模式 / Forbidden Patterns
- 错误处理 / Error Handling
- 安全规范 / Security
- 数据库规范 / Database
- API 设计规范 / API Design
- 日志与可观测性 / Logging & Observability
- 性能规范 / Performance
- 测试规范 / Testing
- Git 规范 / Git Workflow
- 工作流程 / Workflow
- 架构决策记录 / ADR
- 审查清单 / Review Checklist
1. 语言 / Language
Always respond in Chinese (中文). Use the user's language for all conversations and explanations. Code, commands, and technical terms can remain in English.
始终使用中文回复。代码、命令和技术术语可以保留英文。
2. 代码风格 / Code Style
2.1 基本原则 / Basic Principles
| 规则 / Rule |
说明 / Description |
| 遵循现有风格 |
Follow existing project conventions |
| 有意义命名 |
Use meaningful variable names; avoid single-letter names except loop counters |
| 函数长度 |
Keep functions under 50 lines; split complex logic into smaller functions |
| 嵌套深度 |
Maximum nesting depth: 3 levels; use early returns to flatten logic |
| 圈复杂度 |
Function cyclomatic complexity should not exceed 10 |
| 注释 |
Add comments for complex logic only; prefer self-documenting code |
| 文档注释 |
Public items must have /// doc comments; private items only when logic is non-obvious |
2.2 Rust 最佳实践 / Rust Best Practices
| 规则 / Rule |
说明 / Description |
| 错误传播 |
Use ? operator for error propagation; never use unwrap() or expect() in non-test code |
unsafe |
Avoid unsafe blocks; if necessary, add a // SAFETY: comment explaining why |
clone() |
Minimize clone() usage; prefer references or Rc/Arc for shared ownership |
| 魔法数字 |
No magic numbers; define named constants with const |
| 硬编码字符串 |
No hardcoded strings for config/status; use enums or constants |
| 死代码 |
Remove dead code; don't leave commented-out code blocks |
| 未完成代码 |
Don't commit unimplemented!(), todo!(), or FIXME without a tracking issue |
2.3 导入规范 / Import Guidelines
3. 禁止模式 / Forbidden Patterns
以下代码模式在项目中严格禁止:
The following code patterns are strictly forbidden in this project:
| 禁止项 / Forbidden |
说明 / Reason |
// ── xxxx ────────── |
禁止使用此类分隔线注释;使用 // Section: xxx 格式替代 |
unwrap() / expect() (非测试) |
在非测试代码中禁止使用;使用 ? 或 unwrap_or 等安全替代 |
panic!() / unreachable!() |
除极少数不可能到达的分支外禁止使用;使用 AppError 替代 |
未处理的 todo!() |
不得提交包含 todo!() 的代码,除非有对应的 issue 追踪 |
| 注释掉的代码 |
不得提交被注释的代码块;使用 Git 历史追溯 |
| 过深嵌套 (≥4层) |
使用 early return、match、map/and_then 扁平化逻辑 |
| 过长函数 (>50行) |
拆分为更小的、职责单一的函数 |
| 魔法数字 |
使用 const 定义命名常量 |
| 硬编码字符串 |
使用枚举或常量定义配置值/状态值 |
| 死代码 |
删除未使用的代码、导入和变量 |
4. 错误处理 / Error Handling
4.1 错误类型体系 / Error Type System
- AppError: 统一错误枚举,包含领域错误和外部库包装
- AppResult:
Result<T, AppError> 的类型别名
4.2 错误处理原则 / Error Handling Principles
| 原则 / Principle |
说明 / Description |
| 显式处理 |
Handle all errors explicitly; no silent failures |
| 用户友好 |
Internal errors are logged and masked; user-facing messages should be helpful |
| 错误上下文 |
Use .context() or .map_err() to add meaningful context to errors |
| 错误分类 |
Domain errors (UserNotFound) vs Infrastructure errors (DatabaseError) |
| Postgres 映射 |
Map Postgres error codes (23505 unique, 23503 FK, 23514 check) to HTTP statuses |
4.3 错误日志格式 / Error Logging Format
4.4 错误恢复策略 / Error Recovery
| 场景 / Scenario |
策略 / Strategy |
| 数据库连接失败 |
重试 + 降级到只读模式 |
| 外部服务超时 |
断路器 + 降级响应 |
| 缓存 miss |
回退到数据库查询 |
| 队列积压 |
背压控制 + 告警 |
5. 安全规范 / Security
5.1 基础安全 / Basic Security
| 规则 / Rule |
说明 / Description |
| 密钥管理 |
Never hardcode secrets or API keys; use environment variables |
| 输入验证 |
Always validate and sanitize user input |
| SQL 注入 |
Use parameterized queries (sqlx handles this automatically) |
| XSS 防护 |
Escape output; use Content-Security-Policy headers |
| CSRF 防护 |
Use CSRF tokens for state-changing operations |
| 密码安全 |
Argon2 hashing with session-scoped RSA-2048 OAEP-SHA256 |
| 2FA |
TOTP with HMAC-SHA1, base32 secrets, backup codes |
5.2 OWASP Top 10 防护 / OWASP Top 10 Protection
| 风险 / Risk |
防护措施 / Mitigation |
| 注入 |
Parameterized queries, input validation |
| 失效认证 |
Strong password policy, 2FA, session management |
| 敏感数据暴露 |
Encryption at rest and in transit, data masking |
| XML 外部实体 |
Disable XML external entity processing |
| 失效访问控制 |
Role-based access control, resource ownership checks |
| 安全配置错误 |
Secure defaults, environment-based config |
| XSS |
Output encoding, CSP headers |
| 不安全反序列化 |
Validate serialized data, use safe formats |
| 使用含漏洞组件 |
Regular dependency updates, cargo audit |
| 日志和监控不足 |
Comprehensive logging, alerting |
5.3 企业级安全 / Enterprise Security
| 要求 / Requirement |
说明 / Description |
| 安全审计日志 |
Log all sensitive operations with actor, action, resource, timestamp |
| 访问控制 |
Implement RBAC/ABAC; check permissions at service layer |
| 数据脱敏 |
Mask PII in logs; encrypt sensitive fields in database |
| 依赖安全 |
Run cargo audit in CI; review new dependencies |
| 安全头 |
Set HSTS, X-Frame-Options, X-Content-Type-Options, etc. |
| 速率限制 |
Implement rate limiting for auth endpoints and API calls |
6. 数据库规范 / Database
6.1 基础规范 / Basic Rules
| 规则 / Rule |
说明 / Description |
| 参数化查询 |
Always use parameterized queries (sqlx does this by default) |
| 事务管理 |
Use ServiceContext::run_in_transaction() for multi-step operations |
| 读写分离 |
Use AppDatabase read/write pool methods appropriately |
| 迁移规范 |
All schema changes must go through migration files in migrate/ |
6.2 性能优化 / Performance Optimization
| 规则 / Rule |
说明 / Description |
| N+1 防护 |
Use JOIN or batch queries instead of N+1 patterns |
| 批量操作 |
Use INSERT ... ON CONFLICT, UPDATE ... FROM, bulk operations |
| 索引规范 |
Add indexes for frequently queried columns; document index rationale |
| 查询分析 |
Use EXPLAIN ANALYZE to verify query plans for complex queries |
| 连接池 |
Configure pool sizes based on workload; monitor connection usage |
| 慢查询 |
Log queries >100ms; investigate and optimize |
6.3 数据一致性 / Data Consistency
| 规则 / Rule |
说明 / Description |
| 事务边界 |
Keep transactions short; avoid long-running transactions |
| 幂等性 |
Design operations to be idempotent where possible |
| 乐观锁 |
Use version columns for concurrent update protection |
| 外键约束 |
Use database-level foreign keys for referential integrity |
7. API 设计规范 / API Design
7.1 RESTful 规范 / RESTful Conventions
| 规则 / Rule |
示例 / Example |
| 资源命名 |
/api/v1/workspaces/{id}/repos (复数名词) |
| HTTP 方法 |
GET (读取), POST (创建), PUT/PATCH (更新), DELETE (删除) |
| 状态码 |
200 (成功), 201 (创建), 204 (无内容), 400 (客户端错误), 401 (未认证), 403 (禁止), 404 (未找到), 500 (服务器错误) |
| 版本管理 |
URL path versioning: /api/v1/... |
7.2 响应格式 / Response Format
7.3 OpenAPI 文档 / OpenAPI Documentation
7.4 API 治理 / API Governance
| 规则 / Rule |
说明 / Description |
| 请求验证 |
Validate all request bodies and query parameters |
| 速率限制 |
Apply rate limiting to auth and resource-intensive endpoints |
| 幂等性 |
POST operations with same idempotency key should produce same result |
| 缓存策略 |
Use ETag/Last-Modified for cacheable resources |
| 错误码体系 |
Consistent error codes across all endpoints |
| 分页 |
Default page size 20, max 100; use cursor-based pagination for large datasets |
8. 日志与可观测性 / Logging & Observability
8.1 日志规范 / Logging Standards
| 级别 / Level |
用途 / Usage |
error |
错误需要立即关注 / Errors requiring immediate attention |
warn |
异常但可恢复的情况 / Abnormal but recoverable situations |
info |
关键业务操作记录 / Key business operation records |
debug |
开发调试信息 / Development debugging info |
trace |
详细执行路径 / Detailed execution paths |
8.2 敏感信息脱敏 / Data Masking
| 数据类型 / Data Type |
脱敏规则 / Masking Rule |
| 密码 |
完全隐藏 / Never log |
| Token/密钥 |
只显示前 4 位 / Show first 4 chars only |
| 邮箱 |
u***@example.com |
| IP 地址 |
保留网段 / Keep subnet |
| 个人信息 |
根据最小必要原则 / Minimum necessary principle |
8.3 性能指标 / Metrics
| 指标 / Metric |
说明 / Description |
| 请求延迟 |
HTTP request latency (P50, P95, P99) |
| 错误率 |
Error rate by endpoint and status code |
| 吞吐量 |
Requests per second |
| 数据库连接 |
Active/idle connections in pool |
| 缓存命中率 |
Cache hit/miss ratio |
| 队列积压 |
Queue depth and processing rate |
| 内存使用 |
Heap usage, allocation rate |
| 活跃会话 |
Active WebSocket sessions |
8.4 健康检查 / Health Checks
8.5 告警规则 / Alerting Rules
| 条件 / Condition |
级别 / Level |
| 错误率 > 5% |
Critical |
| P99 延迟 > 500ms |
Warning |
| 数据库连接池 > 80% |
Warning |
| 队列积压 > 1000 |
Critical |
| 内存使用 > 85% |
Warning |
| 健康检查失败 |
Critical |
8.6 请求链路追踪 / Request Tracing
9. 性能规范 / Performance
9.1 SLA 目标 / SLA Targets
| 指标 / Metric |
目标 / Target |
| 可用性 |
99.9% (每月宕机 <43 分钟) |
| P50 延迟 |
<50ms |
| P95 延迟 |
<200ms |
| P99 延迟 |
<500ms |
| 错误率 |
<0.1% |
| 数据库查询 |
<100ms (常规查询) |
| 缓存命中率 |
>90% |
9.2 性能原则 / Performance Principles
| 原则 / Principle |
说明 / Description |
| 基准测试 |
Establish performance baselines before optimization |
| 测量优先 |
Profile before optimizing; don't guess |
| 渐进优化 |
Optimize iteratively; measure impact of each change |
| 容量规划 |
Plan for 3x current load |
9.3 优化策略 / Optimization Strategies
| 场景 / Scenario |
策略 / Strategy |
| 热点查询 |
Add caching (L1 + L2) |
| 大量读取 |
Use read replicas |
| 批量操作 |
Batch database operations |
| 高并发 |
Use connection pooling, async I/O |
| 大数据量 |
Use cursor-based pagination |
10. 测试规范 / Testing
10.1 基础要求 / Basic Requirements
| 规则 / Rule |
说明 / Description |
| 新功能 |
All new features must have unit tests |
| Bug 修复 |
Bug fixes must include regression tests |
| 关键路径 |
Critical business logic must have integration tests |
| 测试隔离 |
Tests must be independent and not depend on execution order |
10.2 测试命令 / Test Commands
10.3 测试命名 / Test Naming
11. Git 规范 / Git Workflow
11.1 提交信息格式 / Commit Message Format
使用 Angular 风格,全部英文:
Use Angular style, all English:
| Type |
说明 / Description |
feat |
新功能 / New feature |
fix |
Bug 修复 / Bug fix |
refactor |
重构 / Code refactoring |
docs |
文档 / Documentation |
test |
测试 / Tests |
chore |
构建/工具 / Build/tooling |
perf |
性能优化 / Performance improvement |
style |
代码格式 / Code formatting |
ci |
CI/CD 相关 / CI/CD changes |
示例 / Examples:
11.2 提交原则 / Commit Principles
| 原则 / Principle |
说明 / Description |
| 原子提交 |
Each commit should address one concern |
| 完整性 |
Each commit should leave the codebase in a working state |
| 禁止强制推送 |
Never force push to main branch |
| 提交前检查 |
Run cargo check and cargo test before committing |
11.3 分支策略 / Branch Strategy
| 分支 / Branch |
用途 / Purpose |
main |
生产就绪代码 / Production-ready code |
feat/* |
功能开发 / Feature development |
fix/* |
Bug 修复 / Bug fixes |
release/* |
发布准备 / Release preparation |
12. 工作流程 / Workflow
12.1 开发流程 / Development Process
- 理解先于编写 — Read before write; understand context first
- 最小变更 — Minimal changes; don't refactor unrelated code
- 验证变更 — Verify after changes; run tests or check output
- 文档同步 — Update documentation when changing public APIs
12.2 AI 助手工作规范 / AI Assistant Guidelines
| 规则 / Rule |
说明 / Description |
| 先读后写 |
Always read existing code before making changes |
| 最小侵入 |
Make minimal changes; don't refactor unrelated code |
| 验证结果 |
Run cargo check or cargo test after changes |
| 解释变更 |
Explain what you changed and why |
| 询问不确定 |
Ask when unsure about requirements |
12.3 常用命令 / Common Commands
13. 架构决策记录 / ADR
架构决策记录存放在 docs/adr/ 目录下,使用 Markdown 格式。
Architecture Decision Records are stored in docs/adr/ directory in Markdown format.
索引 / Index
| ADR |
标题 / Title |
状态 / Status |
| ADR-001 |
选择 Actix-web 作为 Web 框架 |
Accepted |
| ADR-002 |
两级缓存架构 (L1 LRU + L2 Redis) |
Accepted |
| ADR-003 |
使用 NATS JetStream 作为消息队列 |
Accepted |
| ADR-004 |
使用 etcd 进行服务发现 |
Accepted |
| ADR-005 |
统一错误处理策略 |
Accepted |
ADR 模板 / ADR Template
14. 审查清单 / Review Checklist
代码审查 / Code Review
PR 审查 / PR Review
发布前审查 / Pre-release Review
附录 / Appendix
项目架构速查 / Quick Architecture Reference
基础设施速查 / Infrastructure Quick Reference
| 服务 / Service |
用途 / Purpose |
协议 / Protocol |
| Postgres |
主数据库 / Primary database |
sqlx |
| Redis |
缓存/会话/限流 / Cache/sessions/rate limiting |
redis + r2d2 |
| etcd |
服务发现 / Service discovery |
etcd-client |
| NATS |
消息队列 / Message queue |
async-nats |
| S3/MinIO |
对象存储 / Object storage |
object_store |
| Qdrant |
向量数据库 / Vector DB |
config only |
This document is maintained by the development team. For questions or suggestions, please open an issue.