rules-creation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rules 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
AGENTS.md
files that OpenCode includes in the LLM's context. They allow you to:
  • 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.
规则是定义在
AGENTS.md
文件中的自定义指令,OpenCode会将其纳入LLM的上下文。它们允许你:
  • 定义项目约定 - 代码标准、架构模式、命名规范
  • 指定工作流 - 构建流程、部署步骤、测试方法
  • 记录上下文信息 - 项目结构、技术栈、团队实践
  • 设置偏好选项 - 个人编码风格、沟通偏好
无需修改配置,规则即可自定义OpenCode的工作方式。

Quick Start

快速开始

Create rules in three steps:
  1. Run the
    /init
    command
    in OpenCode to auto-generate project rules:
    /init
    This scans your project and creates
    AGENTS.md
    with project-specific context.
  2. Or create manually:
    bash
    # Project rules
    touch AGENTS.md
    
    # Global rules
    mkdir -p ~/.config/opencode
    touch ~/.config/opencode/AGENTS.md
  3. 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
分三步创建规则:
  1. 在OpenCode中运行
    /init
    命令
    自动生成项目规则:
    /init
    该命令会扫描你的项目并创建包含项目特定上下文的
    AGENTS.md
    文件。
  2. 或者手动创建
    bash
    # 项目规则
    touch AGENTS.md
    
    # 全局规则
    mkdir -p ~/.config/opencode
    touch ~/.config/opencode/AGENTS.md
  3. 使用Markdown添加指令
    markdown
    # 项目名称
    项目的简短描述。
    
    ## 代码标准
    - 使用严格模式的TypeScript
    - 遵循函数式编程模式
    
    ## 项目结构
    - src/ - 源代码
    - tests/ - 测试文件

Rule Types

规则类型

Project Rules

项目规则

Place
AGENTS.md
in your project root for project-specific instructions that apply when working in that directory or subdirectories.
Use 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.json

Global Rules

全局规则

Create
~/.config/opencode/AGENTS.md
for personal rules that apply to all OpenCode sessions.
Use 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.
创建
~/.config/opencode/AGENTS.md
作为适用于所有OpenCode会话的个人规则。
全局规则适用于
  • 个人编码偏好
  • 沟通风格
  • 工具偏好
  • 跨项目约定
仅个人使用 - 全局规则无需提交到Git,仅保存在你的本地机器上。

Custom Instructions via opencode.json

通过opencode.json配置自定义指令

Reference existing documentation files as instructions using the
instructions
field:
Project configuration (
opencode.json
):
json
{
  "$schema": "https://opencode.ai/config.json",
  "instructions": [
    "CONTRIBUTING.md",
    "docs/guidelines.md",
    ".cursor/rules/*.md"
  ]
}
Global configuration (
~/.config/opencode/opencode.json
):
json
{
  "$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.json
):
json
{
  "$schema": "https://opencode.ai/config.json",
  "instructions": [
    "CONTRIBUTING.md",
    "docs/guidelines.md",
    ".cursor/rules/*.md"
  ]
}
全局配置 (
~/.config/opencode/opencode.json
):
json
{
  "$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):
  • AGENTS.md
    (OpenCode standard)
  • CLAUDE.md
    (Claude Code compatibility)
2. Global file:
  • ~/.config/opencode/AGENTS.md
  • ~/.claude/CLAUDE.md
    (unless disabled)
3. Custom instructions:
  • Files from
    opencode.json
    instructions
    field
All matched files combine together in final context.
OpenCode按以下顺序加载规则(每个类别中匹配到的第一个规则优先):
1. 本地文件(从当前目录向上搜索):
  • AGENTS.md
    (OpenCode标准)
  • CLAUDE.md
    (兼容Claude Code)
2. 全局文件
  • ~/.config/opencode/AGENTS.md
  • ~/.claude/CLAUDE.md
    (可禁用)
3. 自定义指令
  • 来自
    opencode.json
    instructions
    字段的文件
所有匹配到的文件内容会合并到最终上下文中。

Writing Effective Rules

编写有效规则

Structure Guidelines

结构指南

Start with context:
markdown
undefined
从上下文开始
markdown
undefined

Project Name

项目名称

Brief 2-3 sentence overview of what the project is.

**Organize by topic**:
```markdown
用2-3句话简要概述项目内容。

**按主题组织**:
```markdown

Project 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
undefined
markdown
undefined

SST v3 Monorepo Project

SST v3 单仓库项目

This is an SST v3 monorepo using TypeScript and bun workspaces.
这是一个使用TypeScript和bun工作区的SST v3单仓库项目。

Project Structure

项目结构

  • packages/
    - Workspace packages (functions, core, web)
  • infra/
    - Infrastructure split by service (storage.ts, api.ts)
  • sst.config.ts
    - Main SST configuration
  • packages/
    - 工作区包(函数、核心、Web应用)
  • infra/
    - 按服务拆分的基础设施代码(storage.ts、api.ts)
  • sst.config.ts
    - 主SST配置文件

Code Standards

代码标准

  • TypeScript with strict mode enabled
  • Shared code in
    packages/core/
    with proper exports
  • Functions in
    packages/functions/
  • Infrastructure files in
    infra/
  • 启用严格模式的TypeScript
  • 共享代码放在
    packages/core/
    并正确导出
  • 函数放在
    packages/functions/
  • 基础设施文件放在
    infra/

Monorepo Conventions

单仓库约定

  • Import shared modules:
    @my-app/core/example
  • Use
    bun
    for all package operations
  • Run tests from root:
    bun test
undefined
  • 导入共享模块:
    @my-app/core/example
  • 所有包操作使用
    bun
  • 从根目录运行测试:
    bun test
undefined

Initialization Workflow

初始化工作流

Use the
/init
command to auto-generate project rules:
  1. Navigate to project root in OpenCode
  2. Run
    /init
    command
  3. OpenCode scans the project:
    • Analyzes directory structure
    • Detects technology stack
    • Identifies patterns
    • Generates
      AGENTS.md
      with context
  4. Review and customize the generated file
  5. Commit to Git to share with team
If
AGENTS.md
already exists,
/init
adds to it rather than replacing.
使用
/init
命令自动生成项目规则:
  1. 在OpenCode中导航到项目根目录
  2. 运行
    /init
    命令
  3. OpenCode扫描项目
    • 分析目录结构
    • 检测技术栈
    • 识别模式
    • 生成包含上下文信息的
      AGENTS.md
  4. 查看并自定义生成的文件
  5. 提交到Git与团队共享
如果
AGENTS.md
已存在,
/init
会在现有内容基础上添加新内容,而非替换。

Referencing 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
instructions
field to reference files:
json
{
  "$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
使用
instructions
字段引用文件:
json
{
  "$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
undefined

Project 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:
  • CLAUDE.md
    (used if no
    AGENTS.md
    )
Global rules:
  • ~/.claude/CLAUDE.md
    (used if no
    ~/.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 only
OpenCode支持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.md

Common Patterns

常见模式

Monorepo Rules

单仓库规则

markdown
undefined
markdown
undefined

Monorepo Project

单仓库项目

Workspace Structure

工作区结构

  • packages/shared
    - Shared utilities
  • packages/api
    - Backend service
  • packages/web
    - Frontend application
  • 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
undefined

Technology Stack

技术栈说明

markdown
undefined
markdown
undefined

Stack

技术栈

  • 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

关键命令

  • npm run dev
    - Start development servers
  • npm run test
    - Run all tests
  • npm run lint
    - Lint and format
undefined
  • npm run dev
    - 启动开发服务器
  • npm run test
    - 运行所有测试
  • npm run lint
    - 代码检查与格式化
undefined

Code Style

代码风格

markdown
undefined
markdown
undefined

Code 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
    __tests__/
    directories
  • Integration tests in
    tests/
    at root
  • Aim for 80% coverage on core logic
undefined
  • 单元测试放在
    __tests__/
    目录
  • 集成测试放在根目录的
    tests/
  • 核心逻辑覆盖率目标为80%
undefined

API Conventions

API约定

markdown
undefined
markdown
undefined

API 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"
    }
undefined

Troubleshooting

故障排除

Rules not applied:
  1. Check file name is
    AGENTS.md
    (all caps)
  2. Verify file is in project root or
    ~/.config/opencode/
  3. Ensure markdown syntax is valid
  4. Restart OpenCode session
Duplicate rules:
  • If both
    AGENTS.md
    and
    CLAUDE.md
    exist, only
    AGENTS.md
    is used
  • Global
    ~/.config/opencode/AGENTS.md
    takes precedence over
    ~/.claude/CLAUDE.md
Instructions not loading:
  1. Validate JSON syntax in
    opencode.json
  2. Check file paths are correct
  3. Verify glob patterns match intended files
  4. Check network connectivity for remote URLs
Claude Code compatibility issues:
  • Disable with environment variables if conflicts occur
  • Migrate to OpenCode conventions for better control
规则未生效
  1. 检查文件名是否为
    AGENTS.md
    (全大写)
  2. 验证文件是否在项目根目录或
    ~/.config/opencode/
  3. 确保Markdown语法有效
  4. 重启OpenCode会话
规则重复
  • 如果同时存在
    AGENTS.md
    CLAUDE.md
    ,仅
    AGENTS.md
    会被使用
  • 全局规则
    ~/.config/opencode/AGENTS.md
    优先级高于
    ~/.claude/CLAUDE.md
指令未加载
  1. 验证
    opencode.json
    的JSON语法正确
  2. 检查文件路径是否正确
  3. 确认通配符模式匹配目标文件
  4. 检查远程URL的网络连接
Claude Code兼容性问题
  • 若出现冲突,通过环境变量禁用兼容性
  • 迁移到OpenCode约定以获得更好的控制

Additional Resources

额外资源

Reference Files

参考文件

For detailed guidance:
  • references/file-locations.md
    - Complete file location rules and precedence
  • references/writing-guide.md
    - In-depth writing best practices
  • references/advanced-patterns.md
    - Advanced techniques for complex projects
详细指导:
  • references/file-locations.md
    - 完整的文件位置规则与优先级说明
  • references/writing-guide.md
    - 深入的写作最佳实践
  • references/advanced-patterns.md
    - 复杂项目的高级技巧

Example Files

示例文件

Working examples in
examples/
:
  • examples/simple-project.md
    - Basic project rules
  • examples/monorepo.md
    - Monorepo with multiple packages
  • examples/fullstack.md
    - Full-stack application
  • examples/global-rules.md
    - Personal global preferences
examples/
目录下的可用示例:
  • examples/simple-project.md
    - 基础项目规则
  • examples/monorepo.md
    - 多包单仓库规则
  • examples/fullstack.md
    - 全栈应用规则
  • examples/global-rules.md
    - 个人全局偏好设置

Quick Reference

快速参考

Create project rules:
bash
undefined
创建项目规则
bash
undefined

Auto-generate

自动生成

/init
/init

Or manual

手动创建

touch AGENTS.md

**Create global rules**:
```bash
mkdir -p ~/.config/opencode
touch ~/.config/opencode/AGENTS.md
Reference 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):
  1. AGENTS.md
    /
    CLAUDE.md
    (local)
  2. ~/.config/opencode/AGENTS.md
    /
    ~/.claude/CLAUDE.md
    (global)
  3. Files from
    opencode.json
    instructions
Disable Claude Code compatibility:
bash
export OPENCODE_DISABLE_CLAUDE_CODE=1
touch 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"
  ]
}
文件优先级(优先匹配顺序):
  1. AGENTS.md
    /
    CLAUDE.md
    (本地)
  2. ~/.config/opencode/AGENTS.md
    /
    ~/.claude/CLAUDE.md
    (全局)
  3. 来自
    opencode.json
    instructions
    的文件
禁用Claude Code兼容性
bash
export OPENCODE_DISABLE_CLAUDE_CODE=1