rules-creation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRules Creation for OpenCode
OpenCode规则创建指南
Configure custom instructions to guide OpenCode's behavior for your projects and personal workflows.
配置自定义指令,为你的项目和个人工作流指导OpenCode的行为。
What Rules Are
什么是规则
Rules are custom instructions defined in files that OpenCode includes in the LLM's context. They allow you to:
AGENTS.md- Define project conventions - Code standards, architecture patterns, naming conventions
- Specify workflows - Build processes, deployment procedures, testing approaches
- Document context - Project structure, technology stack, team practices
- Set preferences - Personal coding style, communication preferences
Rules customize how OpenCode works without requiring configuration changes.
规则是定义在文件中的自定义指令,OpenCode会将其纳入LLM的上下文。它们允许你:
AGENTS.md- 定义项目约定 - 代码标准、架构模式、命名规范
- 指定工作流 - 构建流程、部署步骤、测试方法
- 记录上下文信息 - 项目结构、技术栈、团队实践
- 设置偏好选项 - 个人编码风格、沟通偏好
无需修改配置,规则即可自定义OpenCode的工作方式。
Quick Start
快速开始
Create rules in three steps:
-
Run thecommand in OpenCode to auto-generate project rules:
/init/initThis scans your project and createswith project-specific context.AGENTS.md -
Or create manually:bash
# Project rules touch AGENTS.md # Global rules mkdir -p ~/.config/opencode touch ~/.config/opencode/AGENTS.md -
Add instructions using markdown:markdown
# Project Name Brief description of the project. ## Code Standards - Use TypeScript with strict mode - Follow functional programming patterns ## Project Structure - src/ - Source code - tests/ - Test files
分三步创建规则:
-
在OpenCode中运行命令自动生成项目规则:
/init/init该命令会扫描你的项目并创建包含项目特定上下文的文件。AGENTS.md -
或者手动创建:bash
# 项目规则 touch AGENTS.md # 全局规则 mkdir -p ~/.config/opencode touch ~/.config/opencode/AGENTS.md -
使用Markdown添加指令:markdown
# 项目名称 项目的简短描述。 ## 代码标准 - 使用严格模式的TypeScript - 遵循函数式编程模式 ## 项目结构 - src/ - 源代码 - tests/ - 测试文件
Rule Types
规则类型
Project Rules
项目规则
Place in your project root for project-specific instructions that apply when working in that directory or subdirectories.
AGENTS.mdUse project rules for:
- Code style and standards
- Project architecture
- Technology stack details
- Team conventions
- Build and deployment procedures
Commit to version control - Project rules should be shared with your team via Git.
Example location:
my-project/
├── AGENTS.md ← Project rules
├── src/
└── package.json将放在项目根目录下,适用于该目录及其子目录的项目特定指令。
AGENTS.md项目规则适用于:
- 代码风格与标准
- 项目架构
- 技术栈细节
- 团队约定
- 构建与部署流程
提交到版本控制 - 项目规则应通过Git与团队共享。
示例位置:
my-project/
├── AGENTS.md ← 项目规则
├── src/
└── package.jsonGlobal Rules
全局规则
Create for personal rules that apply to all OpenCode sessions.
~/.config/opencode/AGENTS.mdUse global rules for:
- Personal coding preferences
- Communication style
- Tool preferences
- Cross-project conventions
Keep personal - Global rules are not committed to Git and remain on your machine.
创建作为适用于所有OpenCode会话的个人规则。
~/.config/opencode/AGENTS.md全局规则适用于:
- 个人编码偏好
- 沟通风格
- 工具偏好
- 跨项目约定
仅个人使用 - 全局规则无需提交到Git,仅保存在你的本地机器上。
Custom Instructions via opencode.json
通过opencode.json配置自定义指令
Reference existing documentation files as instructions using the field:
instructionsProject configuration ():
opencode.jsonjson
{
"$schema": "https://opencode.ai/config.json",
"instructions": [
"CONTRIBUTING.md",
"docs/guidelines.md",
".cursor/rules/*.md"
]
}Global configuration ():
~/.config/opencode/opencode.jsonjson
{
"$schema": "https://opencode.ai/config.json",
"instructions": [
"https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"
]
}Instructions support:
- Local files - Relative paths and glob patterns
- Remote URLs - Fetch from web (5 second timeout)
- Multiple files - Combined with AGENTS.md files
This reuses existing documentation rather than duplicating to AGENTS.md.
使用字段引用现有文档作为指令:
instructions项目配置 ():
opencode.jsonjson
{
"$schema": "https://opencode.ai/config.json",
"instructions": [
"CONTRIBUTING.md",
"docs/guidelines.md",
".cursor/rules/*.md"
]
}全局配置 ():
~/.config/opencode/opencode.jsonjson
{
"$schema": "https://opencode.ai/config.json",
"instructions": [
"https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"
]
}指令支持:
- 本地文件 - 相对路径和通配符模式
- 远程URL - 从网络获取(5秒超时)
- 多文件 - 与AGENTS.md文件合并生效
这样可以重用现有文档,无需将内容复制到AGENTS.md中。
Rule Precedence
规则优先级
OpenCode loads rules in this order (first match wins in each category):
1. Local files (searches up from current directory):
- (OpenCode standard)
AGENTS.md - (Claude Code compatibility)
CLAUDE.md
2. Global file:
~/.config/opencode/AGENTS.md- (unless disabled)
~/.claude/CLAUDE.md
3. Custom instructions:
- Files from
opencode.jsonfieldinstructions
All matched files combine together in final context.
OpenCode按以下顺序加载规则(每个类别中匹配到的第一个规则优先):
1. 本地文件(从当前目录向上搜索):
- (OpenCode标准)
AGENTS.md - (兼容Claude Code)
CLAUDE.md
2. 全局文件:
~/.config/opencode/AGENTS.md- (可禁用)
~/.claude/CLAUDE.md
3. 自定义指令:
- 来自中
opencode.json字段的文件instructions
所有匹配到的文件内容会合并到最终上下文中。
Writing Effective Rules
编写有效规则
Structure Guidelines
结构指南
Start with context:
markdown
undefined从上下文开始:
markdown
undefinedProject Name
项目名称
Brief 2-3 sentence overview of what the project is.
**Organize by topic**:
```markdown用2-3句话简要概述项目内容。
**按主题组织**:
```markdownProject Structure
项目结构
Directory layout and key files
目录布局与关键文件说明
Code Standards
代码标准
Language-specific conventions
特定语言的约定
Development Workflow
开发工作流
Build, test, and deployment procedures
**Be specific**:
```markdown
✓ Good:
- Import shared code using workspace names: `@my-app/core/example`
- All functions go in `packages/functions/`
- Use `bun` not `npm` for package management
✗ Too vague:
- Follow best practices
- Use good code style构建、测试与部署流程
**内容要具体**:
```markdown
✓ 示例:
- 使用工作区名称导入共享代码:`@my-app/core/example`
- 所有函数放在`packages/functions/`目录下
- 使用`bun`而非`npm`进行包管理
✗ 避免模糊表述:
- 遵循最佳实践
- 使用良好的代码风格Content Best Practices
内容最佳实践
DO:
- Be concise and actionable
- Use examples and code snippets
- Document project-specific patterns
- Explain "why" for non-obvious decisions
- Keep rules focused on what's unique to your project
DON'T:
- Explain general programming concepts
- Duplicate standard language documentation
- Add time-sensitive information (dates, versions)
- Include secrets or credentials
- Write essays - be brief
建议:
- 简洁且可执行
- 使用示例与代码片段
- 记录项目特定模式
- 对非显而易见的决策说明原因
- 规则聚焦于项目的独特之处
避免:
- 解释通用编程概念
- 重复标准语言文档内容
- 添加时间敏感信息(日期、版本)
- 包含密钥或凭证
- 长篇大论,保持简洁
Example Structure
示例结构
markdown
undefinedmarkdown
undefinedSST v3 Monorepo Project
SST v3 单仓库项目
This is an SST v3 monorepo using TypeScript and bun workspaces.
这是一个使用TypeScript和bun工作区的SST v3单仓库项目。
Project Structure
项目结构
- - Workspace packages (functions, core, web)
packages/ - - Infrastructure split by service (storage.ts, api.ts)
infra/ - - Main SST configuration
sst.config.ts
- - 工作区包(函数、核心、Web应用)
packages/ - - 按服务拆分的基础设施代码(storage.ts、api.ts)
infra/ - - 主SST配置文件
sst.config.ts
Code Standards
代码标准
- TypeScript with strict mode enabled
- Shared code in with proper exports
packages/core/ - Functions in
packages/functions/ - Infrastructure files in
infra/
- 启用严格模式的TypeScript
- 共享代码放在并正确导出
packages/core/ - 函数放在
packages/functions/ - 基础设施文件放在
infra/
Monorepo Conventions
单仓库约定
- Import shared modules:
@my-app/core/example - Use for all package operations
bun - Run tests from root:
bun test
undefined- 导入共享模块:
@my-app/core/example - 所有包操作使用
bun - 从根目录运行测试:
bun test
undefinedInitialization Workflow
初始化工作流
Use the command to auto-generate project rules:
/init- Navigate to project root in OpenCode
- Run command
/init - OpenCode scans the project:
- Analyzes directory structure
- Detects technology stack
- Identifies patterns
- Generates with context
AGENTS.md
- Review and customize the generated file
- Commit to Git to share with team
If already exists, adds to it rather than replacing.
AGENTS.md/init使用命令自动生成项目规则:
/init- 在OpenCode中导航到项目根目录
- 运行命令
/init - OpenCode扫描项目:
- 分析目录结构
- 检测技术栈
- 识别模式
- 生成包含上下文信息的
AGENTS.md
- 查看并自定义生成的文件
- 提交到Git与团队共享
如果已存在,会在现有内容基础上添加新内容,而非替换。
AGENTS.md/initReferencing External Files
引用外部文件
While OpenCode doesn't auto-parse file references in AGENTS.md, you can achieve similar functionality:
虽然OpenCode不会自动解析AGENTS.md中的文件引用,但你可以通过以下方式实现类似功能:
Method 1: opencode.json (Recommended)
方法1:使用opencode.json(推荐)
Use the field to reference files:
instructionsjson
{
"$schema": "https://opencode.ai/config.json",
"instructions": [
"docs/development-standards.md",
"test/testing-guidelines.md",
"packages/*/AGENTS.md"
]
}Benefits:
- Clean and maintainable
- Supports glob patterns
- Works with monorepos
- Automatic loading
使用字段引用文件:
instructionsjson
{
"$schema": "https://opencode.ai/config.json",
"instructions": [
"docs/development-standards.md",
"test/testing-guidelines.md",
"packages/*/AGENTS.md"
]
}优势:
- 清晰且易于维护
- 支持通配符模式
- 适用于单仓库
- 自动加载
Method 2: Manual Instructions in AGENTS.md
方法2:在AGENTS.md中添加手动指令
Teach OpenCode to load files on-demand:
markdown
undefined引导OpenCode按需加载文件:
markdown
undefinedProject Rules
项目规则
External File Loading
外部文件加载说明
CRITICAL: When you encounter a file reference (e.g., @docs/api-standards.md),
use your Read tool to load it when relevant to the current task.
Instructions:
- Load references on need-to-know basis (lazy loading)
- Treat loaded content as mandatory instructions
- Follow references recursively when needed
重要提示:当你遇到文件引用(例如@docs/api-standards.md)时,
在当前任务需要时使用读取工具加载该文件。
指令:
- 按需加载引用文件(延迟加载)
- 将加载的内容视为强制指令
- 必要时递归加载引用内容
Development Guidelines
开发指南
For TypeScript style: @docs/typescript-guidelines.md
For React patterns: @docs/react-patterns.md
For API design: @docs/api-standards.md
TypeScript风格参考:@docs/typescript-guidelines.md
React模式参考:@docs/react-patterns.md
API设计参考:@docs/api-standards.md
General Guidelines
通用指南
Read immediately: @rules/general-guidelines.md
**Use case**: Modular rules, shared standards, keeping AGENTS.md concise.立即读取:@rules/general-guidelines.md
**适用场景**:模块化规则、共享标准、保持AGENTS.md简洁。Claude Code Compatibility
Claude Code兼容性
OpenCode supports Claude Code conventions as fallbacks:
Project rules:
- (used if no
CLAUDE.md)AGENTS.md
Global rules:
- (used if no
~/.claude/CLAUDE.md)~/.config/opencode/AGENTS.md
Disable compatibility via environment variables:
bash
export OPENCODE_DISABLE_CLAUDE_CODE=1 # Disable all .claude support
export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # Disable ~/.claude/CLAUDE.md onlyOpenCode支持Claude Code约定作为备选方案:
项目规则:
- (当没有
CLAUDE.md时使用)AGENTS.md
全局规则:
- (当没有
~/.claude/CLAUDE.md时使用)~/.config/opencode/AGENTS.md
禁用兼容性:通过环境变量禁用
bash
export OPENCODE_DISABLE_CLAUDE_CODE=1 # 禁用所有.claude相关支持
export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # 仅禁用~/.claude/CLAUDE.mdCommon Patterns
常见模式
Monorepo Rules
单仓库规则
markdown
undefinedmarkdown
undefinedMonorepo Project
单仓库项目
Workspace Structure
工作区结构
- - Shared utilities
packages/shared - - Backend service
packages/api - - Frontend application
packages/web
- - 共享工具库
packages/shared - - 后端服务
packages/api - - 前端应用
packages/web
Import Conventions
导入约定
- Use workspace imports:
@myapp/shared/utils - No relative imports across packages
- Run builds from root:
npm run build
undefined- 使用工作区导入:
@myapp/shared/utils - 跨包禁止使用相对导入
- 从根目录运行构建:
npm run build
undefinedTechnology Stack
技术栈说明
markdown
undefinedmarkdown
undefinedStack
技术栈
- Backend: Node.js 20, Express, PostgreSQL
- Frontend: React 18, TypeScript, Vite
- Testing: Vitest, React Testing Library
- CI/CD: GitHub Actions
- 后端:Node.js 20、Express、PostgreSQL
- 前端:React 18、TypeScript、Vite
- 测试:Vitest、React Testing Library
- CI/CD:GitHub Actions
Key Commands
关键命令
- - Start development servers
npm run dev - - Run all tests
npm run test - - Lint and format
npm run lint
undefined- - 启动开发服务器
npm run dev - - 运行所有测试
npm run test - - 代码检查与格式化
npm run lint
undefinedCode Style
代码风格
markdown
undefinedmarkdown
undefinedCode Standards
代码标准
TypeScript
TypeScript
- Use strict mode
- Prefer interfaces over types for objects
- Explicit return types for exported functions
- 启用严格模式
- 对象类型优先使用interface而非type
- 导出函数需显式声明返回类型
React
React
- Use functional components with hooks
- Co-locate styles with components
- Use named exports, not default
- 使用带Hooks的函数式组件
- 样式与组件放在同一目录
- 使用命名导出,避免默认导出
Testing
测试
- Unit tests in directories
__tests__/ - Integration tests in at root
tests/ - Aim for 80% coverage on core logic
undefined- 单元测试放在目录
__tests__/ - 集成测试放在根目录的
tests/ - 核心逻辑覆盖率目标为80%
undefinedAPI Conventions
API约定
markdown
undefinedmarkdown
undefinedAPI Design
API设计
REST Endpoints
REST端点
- Use plural nouns: ,
/users/orders - Version in URL:
/api/v1/users - Standard methods: GET, POST, PUT, DELETE
- 使用复数名词:、
/users/orders - URL中包含版本:
/api/v1/users - 使用标准方法:GET、POST、PUT、DELETE
Error Handling
错误处理
- Return proper HTTP status codes
- JSON error format:
json
{ "error": "Error message", "code": "ERROR_CODE" }
undefined- 返回正确的HTTP状态码
- JSON错误格式:
json
{ "error": "错误信息", "code": "ERROR_CODE" }
undefinedTroubleshooting
故障排除
Rules not applied:
- Check file name is (all caps)
AGENTS.md - Verify file is in project root or
~/.config/opencode/ - Ensure markdown syntax is valid
- Restart OpenCode session
Duplicate rules:
- If both and
AGENTS.mdexist, onlyCLAUDE.mdis usedAGENTS.md - Global takes precedence over
~/.config/opencode/AGENTS.md~/.claude/CLAUDE.md
Instructions not loading:
- Validate JSON syntax in
opencode.json - Check file paths are correct
- Verify glob patterns match intended files
- Check network connectivity for remote URLs
Claude Code compatibility issues:
- Disable with environment variables if conflicts occur
- Migrate to OpenCode conventions for better control
规则未生效:
- 检查文件名是否为(全大写)
AGENTS.md - 验证文件是否在项目根目录或下
~/.config/opencode/ - 确保Markdown语法有效
- 重启OpenCode会话
规则重复:
- 如果同时存在和
AGENTS.md,仅CLAUDE.md会被使用AGENTS.md - 全局规则优先级高于
~/.config/opencode/AGENTS.md~/.claude/CLAUDE.md
指令未加载:
- 验证的JSON语法正确
opencode.json - 检查文件路径是否正确
- 确认通配符模式匹配目标文件
- 检查远程URL的网络连接
Claude Code兼容性问题:
- 若出现冲突,通过环境变量禁用兼容性
- 迁移到OpenCode约定以获得更好的控制
Additional Resources
额外资源
Reference Files
参考文件
For detailed guidance:
- - Complete file location rules and precedence
references/file-locations.md - - In-depth writing best practices
references/writing-guide.md - - Advanced techniques for complex projects
references/advanced-patterns.md
详细指导:
- - 完整的文件位置规则与优先级说明
references/file-locations.md - - 深入的写作最佳实践
references/writing-guide.md - - 复杂项目的高级技巧
references/advanced-patterns.md
Example Files
示例文件
Working examples in :
examples/- - Basic project rules
examples/simple-project.md - - Monorepo with multiple packages
examples/monorepo.md - - Full-stack application
examples/fullstack.md - - Personal global preferences
examples/global-rules.md
examples/- - 基础项目规则
examples/simple-project.md - - 多包单仓库规则
examples/monorepo.md - - 全栈应用规则
examples/fullstack.md - - 个人全局偏好设置
examples/global-rules.md
Quick Reference
快速参考
Create project rules:
bash
undefined创建项目规则:
bash
undefinedAuto-generate
自动生成
/init
/init
Or manual
手动创建
touch AGENTS.md
**Create global rules**:
```bash
mkdir -p ~/.config/opencode
touch ~/.config/opencode/AGENTS.mdReference external files (opencode.json):
json
{
"$schema": "https://opencode.ai/config.json",
"instructions": [
"CONTRIBUTING.md",
"docs/*.md",
"https://example.com/rules.md"
]
}File precedence (first match wins):
- /
AGENTS.md(local)CLAUDE.md - /
~/.config/opencode/AGENTS.md(global)~/.claude/CLAUDE.md - Files from
opencode.jsoninstructions
Disable Claude Code compatibility:
bash
export OPENCODE_DISABLE_CLAUDE_CODE=1touch AGENTS.md
**创建全局规则**:
```bash
mkdir -p ~/.config/opencode
touch ~/.config/opencode/AGENTS.md引用外部文件(opencode.json):
json
{
"$schema": "https://opencode.ai/config.json",
"instructions": [
"CONTRIBUTING.md",
"docs/*.md",
"https://example.com/rules.md"
]
}文件优先级(优先匹配顺序):
- /
AGENTS.md(本地)CLAUDE.md - /
~/.config/opencode/AGENTS.md(全局)~/.claude/CLAUDE.md - 来自中
opencode.json的文件instructions
禁用Claude Code兼容性:
bash
export OPENCODE_DISABLE_CLAUDE_CODE=1