在前面的系列文章中,我们已经掌握了 OpenCode 的安装认证、Provider 选择、命令运行、TUI 交互、Session 管理、Agent 双模式、PR 审查实战、并行工作模式和提示词工程等核心功能。但所有这些功能如果只用默认配置运行,就像买了一辆跑车却只挂 D 挡——能走,但远没发挥出全部潜力。

自定义配置详解 —— settings.json、规则目录与层级加载机制

简介

在前面的系列文章中,我们已经掌握了 OpenCode 的安装认证、Provider 选择、命令运行、TUI 交互、Session 管理、Agent 双模式、PR 审查实战、并行工作模式和提示词工程等核心功能。但所有这些功能如果只用默认配置运行,就像买了一辆跑车却只挂 D 挡——能走,但远没发挥出全部潜力。

自定义配置才是真正让 OpenCode 从"通用工具"变成"你的专属编程助手"的关键。

本文将系统讲解 OpenCode 的配置体系:

  • settings.json:核心配置文件的完整字段与最佳实践
  • 规则目录.opencode/ 目录下的规则组织方式
  • 层级加载机制:全局配置 → 项目配置 → 会话覆盖的优先级链
  • 配置验证与调试:如何确认你的配置正确生效

一、配置体系概览

1.1 三层配置架构

OpenCode 采用三层配置架构,从宏观到微观逐级覆盖:

text
┌─────────────────────────────────────────────────────┐
│  Layer 1: 全局配置 (~/.opencode/settings.json)        │
  - 默认 Provider、模型偏好                            │
  - 通用工具配置、快捷键映射                           │
  - 对所有项目生效                                     │
├─────────────────────────────────────────────────────┤
│  Layer 2: 项目配置 (项目根目录/.opencode/settings.json) │
  - 项目特定的 Provider 和模型                         │
  - 项目规则、文件组、上下文文件                       │
  - 覆盖全局配置                                       │
├─────────────────────────────────────────────────────┤
│  Layer 3: 会话/命令级覆盖                              │
  - 命令行参数 (--model, --provider, --context)        │
  - TUI 中的临时切换                                   │
  - 单次会话内生效                                     │
└─────────────────────────────────────────────────────┘

优先级:会话级 > 项目级 > 全局级

这个设计非常合理:你有全局的默认偏好,每个项目有自己的特定需求,偶尔还有单次任务的临时调整。三层结构让你在不同粒度上精准控制 Agent 的行为。

1.2 配置文件查找顺序

当你启动 OpenCode 时,它会按以下顺序查找配置:

bash
# 1. 首先检查命令行参数
opencode run -m "claude-sonnet-4-20250514" --provider anthropic

# 2. 然后查找项目级配置
# 从当前目录向上查找,直到找到第一个 .opencode/settings.json
./
├── src/
│   └── main.go
├── .opencode/
│   ├── settings.json      ← 项目配置(优先使用)
│   ├── rules/
│   │   ├── coding.md
│   │   └── testing.md
│   └── context/
│       └── project.yaml
└── go.mod

# 3. 最后回退到全局配置
~/.opencode/settings.json  ← 全局默认配置

1.3 .opencode 目录结构

一个完整的 .opencode 目录通常包含以下内容:

text
.opencode/
├── settings.json          # 核心配置文件(必需)
├── rules/                 # 规则文件目录
│   ├── general.md         # 通用规则
│   ├── coding.md          # 编码规范
│   ├── testing.md         # 测试要求
│   └── security.md        # 安全规则
├── context/               # 上下文文件目录
│   ├── project.yaml       # 项目级上下文
│   └── modules/           # 模块化上下文
│       ├── auth.yaml
│       └── api.yaml
├── prompts/               # 自定义提示词模板
│   ├── review.txt
│   └── refactor.txt
└── file-groups.yaml       # 文件组定义

重要settings.json 是唯一必需的文件,其他都是可选的。但合理利用这些目录结构,可以让你的配置既强大又易于维护。

二、settings.json 完整配置详解

2.1 基础配置段

json
{
  "provider": {
    "default": "anthropic",
    "models": {
      "anthropic": {
        "model": "claude-sonnet-4-20250514",
        "temperature": 0.1,
        "max_tokens": 8192,
        "top_p": 0.9
      },
      "openai": {
        "model": "gpt-4.1",
        "temperature": 0.2,
        "max_tokens": 4096
      },
      "openrouter": {
        "model": "anthropic/claude-sonnet-4",
        "temperature": 0.1
      }
    }
  }
}

字段说明:

字段 类型 必填 说明
provider.default string 默认 Provider 标识
models.*.model string 模型 ID
models.*.temperature number 温度参数 (0-1)
models.*.max_tokens number 最大输出 token 数
models.*.top_p number 核采样参数

2.2 Agent 模式配置

json
{
  "agent": {
    "mode": "build",
    "auto_plan_threshold": "complex",
    "plan_review_required": true,
    "max_iterations": 50,
    "sub_agents": {
      "max_concurrent": 3,
      "timeout_seconds": 300
    }
  }
}

Agent 模式详解:

  • mode:默认 Agent 模式,buildplan
  • auto_plan_threshold:自动触发规划模式的任务复杂度阈值
    • simple:所有任务都先规划
    • moderate:中等及以上复杂度触发规划
    • complex:仅复杂任务触发规划
    • never:从不自动触发
  • plan_review_required:规划完成后是否需要用户确认
  • max_iterations:单次会话最大工具调用次数,防止无限循环
  • sub_agents:并行子代理的配置

2.3 规则系统配置

json
{
  "rules": {
    "directory": ".opencode/rules",
    "auto_load": true,
    "files": [
      "general.md",
      "coding.md"
    ],
    "skip_files": [
      "deprecated.md"
    ],
    "priority_order": [
      "security.md",
      "coding.md",
      "testing.md",
      "general.md"
    ]
  }
}

规则加载机制:

  • auto_load: true 时,OpenCode 会自动加载 rules 目录下的所有 .md 文件
  • files 列表指定要加载的规则文件(配合 auto_load: false 使用)
  • skip_files 排除不需要加载的规则
  • priority_order 定义规则的注入顺序,排在前面的规则优先级更高

2.4 上下文文件配置

json
{
  "context": {
    "project_file": ".opencode/context/project.yaml",
    "modules_directory": ".opencode/context/modules",
    "auto_discover": true,
    "max_context_size": 50000,
    "default_contexts": [
      "project.yaml",
      "modules/architecture.yaml"
    ]
  }
}

上下文文件是 OpenCode 独特的功能,它允许你将项目知识结构化地提供给 Agent:

yaml
# .opencode/context/project.yaml
project:
  name: "ecommerce-api"
  description: "基于 Go 的电商后端 API 服务"
  tech_stack:
    - "Go 1.21+"
    - "Gin framework"
    - "PostgreSQL 15"
    - "Redis 7"
  architecture:
    pattern: "Clean Architecture"
    layers:
      - "handlers (HTTP layer)"
      - "services (business logic)"
      - "repositories (data access)"
      - "models (domain entities)"
  conventions:
    error_handling: "使用自定义 error type,不使用 fmt.Errorf"
    logging: "使用 zap logger,JSON 格式"
    testing: "表驱动测试 + mockery 生成 mock"

2.5 工具与命令配置

json
{
  "tools": {
    "allowed": [
      "read",
      "write",
      "edit",
      "terminal",
      "glob",
      "grep"
    ],
    "restricted": {
      "terminal": {
        "blocked_commands": [
          "rm -rf /",
          "format",
          "mkfs",
          "dd if=/dev/zero"
        ],
        "allowed_directories": [
          "./src",
          "./test",
          "./scripts"
        ],
        "require_confirmation": true
      },
      "write": {
        "allowed_extensions": [
          ".go", ".proto", ".yaml", ".json", ".md"
        ],
        "max_file_size_mb": 10
      }
    },
    "custom": {
      "lint": {
        "command": "golangci-lint run {file}",
        "description": "运行 Go 代码检查"
      },
      "test": {
        "command": "go test -v -count=1 ./...",
        "description": "运行全部测试"
      }
    }
  }
}

安全最佳实践:

  1. 明确白名单:只允许需要的工具,而非默认全部开放
  2. 命令黑名单:阻止危险系统命令
  3. 目录限制:限制工具只能操作特定目录
  4. 确认机制:对写操作启用确认提示
  5. 文件类型限制:防止 Agent 意外修改二进制文件

2.6 文件组配置

json
{
  "file_groups": {
    "config_file": ".opencode/file-groups.yaml"
  }
}
yaml
# .opencode/file-groups.yaml
groups:
  api:
    description: "API 层相关文件"
    patterns:
      - "cmd/api/**/*.go"
      - "internal/handler/**/*.go"
      - "api/proto/*.proto"

  business:
    description: "业务逻辑层"
    patterns:
      - "internal/service/**/*.go"
      - "internal/usecase/**/*.go"

  data:
    description: "数据访问层"
    patterns:
      - "internal/repository/**/*.go"
      - "internal/model/**/*.go"
      - "migrations/*.sql"

  tests:
    description: "测试文件"
    patterns:
      - "**/*_test.go"
      - "test/**/*.go"

  all-go:
    description: "所有 Go 源文件"
    patterns:
      - "**/*.go"
    exclude:
      - "vendor/**"
      - "**/*_test.go"

文件组让你可以用一个名称引用一组文件,极大简化了上下文引用的复杂度。

2.7 完整的 settings.json 示例

json
{
  "$schema": "https://opencode.ai/schema/settings.json",
  "provider": {
    "default": "anthropic",
    "models": {
      "anthropic": {
        "model": "claude-sonnet-4-20250514",
        "temperature": 0.1,
        "max_tokens": 8192
      },
      "openai": {
        "model": "gpt-4.1",
        "temperature": 0.2
      }
    }
  },
  "agent": {
    "mode": "build",
    "auto_plan_threshold": "complex",
    "plan_review_required": true,
    "max_iterations": 50,
    "sub_agents": {
      "max_concurrent": 3,
      "timeout_seconds": 300
    }
  },
  "rules": {
    "directory": ".opencode/rules",
    "auto_load": true,
    "priority_order": [
      "security.md",
      "coding.md",
      "testing.md"
    ]
  },
  "context": {
    "project_file": ".opencode/context/project.yaml",
    "modules_directory": ".opencode/context/modules",
    "auto_discover": true,
    "max_context_size": 50000
  },
  "tools": {
    "allowed": ["read", "write", "edit", "terminal", "glob", "grep"],
    "restricted": {
      "terminal": {
        "blocked_commands": ["rm -rf /", "format", "mkfs"],
        "require_confirmation": true
      }
    }
  },
  "file_groups": {
    "config_file": ".opencode/file-groups.yaml"
  },
  "mcp": {
    "servers": {}
  }
}

三、规则目录深度解析

3.1 规则文件格式

规则文件是纯 Markdown 格式,内容会被注入到系统提示词中:

markdown
# .opencode/rules/coding.md

## 代码风格

- 使用 4 空格缩进(Go 项目用 tab)
- 函数名使用 PascalCase,变量名使用 camelCase
- 常量使用 UPPER_SNAKE_CASE

## 错误处理

- 使用自定义错误类型,禁止使用 fmt.Errorf 包裹业务错误
- 所有错误必须在调用栈最上层记录日志
- 错误消息应包含足够的上下文信息

## 测试要求

- 所有公开函数必须有对应的测试
- 使用表驱动测试模式
- 测试覆盖率不低于 80%

## 文档

- 所有公开函数必须有 godoc 注释
- 复杂逻辑必须包含行内注释解释"为什么"而非"做什么"

3.2 规则的组织策略

策略一:按领域分层

text
.opencode/rules/
├── 01-security.md     # 安全规则(最高优先级)
├── 02-coding.md       # 编码规范
├── 03-testing.md      # 测试要求
├── 04-documentation.md # 文档规范
└── 05-deployment.md   # 部署相关

策略二:按团队角色

text
.opencode/rules/
├── backend-rules.md   # 后端团队规则
├── frontend-rules.md  # 前端团队规则
└── devops-rules.md    # 运维团队规则

策略三:按项目阶段

text
.opencode/rules/
├── bootstrap.md       # 项目初始化阶段
├── development.md     # 日常开发阶段
└── release.md         # 发布准备阶段

3.3 规则优先级与合并

当多个规则文件存在时,OpenCode 按以下规则合并:

  1. 配置中的 priority_order 优先:明确指定的顺序
  2. 文件名前缀排序01-xxx.md < 02-xxx.md
  3. 字母序:无前缀时按文件名排序

合并规则:

  • 所有规则内容依次追加到系统提示词
  • 后面的规则不会覆盖前面的,而是追加
  • 因此通用规则应该放在后面,特定规则放在前面

3.4 规则的动态加载

规则不仅可以在启动时加载,还可以在运行时动态添加:

bash
# 添加规则到当前会话
opencode rules add .opencode/rules/new-feature.md

# 查看当前加载的规则
opencode rules list

# 临时禁用某条规则
opencode rules disable testing.md

# 重新加载所有规则
opencode rules reload

四、层级加载机制详解

4.1 配置合并策略

OpenCode 使用深度合并策略来合并多层配置:

text
全局配置 (~/.opencode/settings.json):
{
  "provider": {
    "default": "openai",
    "models": {
      "openai": { "model": "gpt-4.1", "temperature": 0.3 }
    }
  },
  "tools": {
    "allowed": ["read", "write", "terminal"]
  }
}

项目配置 (./myproject/.opencode/settings.json):
{
  "provider": {
    "default": "anthropic",
    "models": {
      "anthropic": { "model": "claude-sonnet-4-20250514" }
    }
  }
}

最终合并结果:
{
  "provider": {
    "default": "anthropic",        ← 项目级覆盖
    "models": {
      "openai": { ... },           ← 全局保留
      "anthropic": { ... }          ← 项目新增
    }
  },
  "tools": {
    "allowed": ["read", "write", "terminal"]  ← 全局保留
  }
}

合并原则:

  • 标量值(字符串、数字、布尔):子层级覆盖父层级
  • 数组:子层级完全替换父层级(不合并)
  • 对象:递归深度合并
  • null:显式删除该字段

4.2 配置查找路径

bash
# OpenCode 启动时的配置查找路径
启动命令: opencode run ./src/main.go "refactor this function"

# 1. 从当前工作目录向上查找
./                     ← 当前目录
├── .opencode/
│   └── settings.json  ← 找到了!停止向上查找

# 如果当前目录没有:
./src/
└── main.go
                      ← 向上到父目录

./                    ← 父目录
├── .opencode/
│   └── settings.json ← 找到了!

# 如果所有父目录都没有,使用全局配置
~/.opencode/settings.json

4.3 版本锁定

OpenCode 支持项目级的版本锁定,确保团队成员使用相同版本的 Agent 行为:

bash
# 在项目根目录创建版本文件
echo "1.2.3" > .opencode-version

# 或使用配置中的 version 字段
# settings.json
{
  "version": "1.2.3"
}

当版本不匹配时,OpenCode 会给出警告:

text
⚠️  OpenCode version mismatch!
   Project requires: 1.2.3
   Current version:  1.3.0
   Some behaviors may differ.

4.4 环境变量覆盖

所有配置项都可以通过环境变量覆盖:

bash
# 覆盖默认 Provider
export OPENCODE_PROVIDER=openai

# 覆盖默认模型
export OPENCODE_MODEL=gpt-4.1

# 覆盖温度参数
export OPENCODE_TEMPERATURE=0.5

# 禁用规则自动加载
export OPENCODE_RULES_AUTO_LOAD=false

# 指定配置目录
export OPENCODE_CONFIG_DIR=/custom/config/path

# 启动时生效
OPENCODE_PROVIDER=anthropic opencode run "add logging"

五、配置验证与调试

5.1 配置验证命令

bash
# 验证配置文件语法
opencode config validate

# 查看当前生效的完整配置(合并后)
opencode config show

# 查看配置来源
opencode config show --with-source

# 输出示例:
# provider.default = "anthropic"     (from: ./myproject/.opencode/settings.json)
# provider.models.openai.model = "gpt-4.1"  (from: ~/.opencode/settings.json)
# rules.auto_load = true             (from: ./myproject/.opencode/settings.json)

5.2 调试模式

bash
# 启动调试模式,输出配置加载详情
opencode run --verbose "test this"

# 或设置环境变量
OPENCODE_DEBUG=config opencode run "test this"

调试输出示例:

text
[config] Loading global config from /home/user/.opencode/settings.json[config] Loading project config from /project/.opencode/settings.json[config] Merging configurations (depth: 3)
[config] Resolved provider: anthropic (from project config)
[config] Resolved model: claude-sonnet-4-20250514
[config] Loading rules from .opencode/rules/
[config]   → security.md (priority: 1)
[config]   → coding.md (priority: 2)
[config]   → testing.md (priority: 3)
[config] Loading context from .opencode/context/project.yaml[config] Loading file groups from .opencode/file-groups.yaml[config] Configuration loaded successfully (47ms)

5.3 常见问题排查

问题 1:配置不生效

bash
# 检查配置文件路径是否正确
ls -la .opencode/settings.json

# 检查 JSON 语法
python3 -m json.tool .opencode/settings.json

# 查看配置来源
opencode config show --with-source

问题 2:规则文件未被加载

bash
# 检查 auto_load 是否开启
opencode config show | grep rules

# 手动列出规则文件
ls -la .opencode/rules/

# 验证规则文件编码(必须是 UTF-8)
file .opencode/rules/coding.md

问题 3:层级配置冲突

bash
# 查看完整的合并树
opencode config show --tree

# 输出示例:
# provider.default
# ├── ~/.opencode/settings.json: "openai"
# └── ./.opencode/settings.json: "anthropic" ← WINNER

六、实战:从零配置一个项目

6.1 场景:新 Go 微服务项目

bash
# 1. 创建项目结构
mkdir -p myservice/.opencode/{rules,context,modules}
cd myservice

# 2. 初始化 settings.json
cat > .opencode/settings.json << 'EOF'
{
  "provider": {
    "default": "anthropic",
    "models": {
      "anthropic": {
        "model": "claude-sonnet-4-20250514",
        "temperature": 0.1,
        "max_tokens": 8192
      }
    }
  },
  "agent": {
    "mode": "build",
    "auto_plan_threshold": "complex",
    "plan_review_required": true
  },
  "rules": {
    "auto_load": true,
    "directory": ".opencode/rules"
  },
  "context": {
    "project_file": ".opencode/context/project.yaml"
  }
}
EOF

# 3. 创建编码规则
cat > .opencode/rules/coding.md << 'EOF'
## Go 编码规范
- 遵循 Effective Go 和 Go Code Review Comments
- 使用 gofmt 格式化
- 接口定义放在使用方而非实现方
- 错误处理使用 errors.Is 和 errors.As
- 并发安全:共享数据必须加锁或使用 channel
EOF

# 4. 创建项目上下文
cat > .opencode/context/project.yaml << 'EOF'
project:
  name: "myservice"
  description: "用户管理服务微服务"
  tech_stack:
    - "Go 1.21"
    - "Gin"
    - "PostgreSQL"
  architecture: "Clean Architecture"
EOF

# 5. 验证配置
opencode config validate
opencode config show

# 6. 启动测试
opencode run "scaffold the project structure"

6.2 场景:多语言 Monorepo

bash
# monorepo/.opencode/settings.json
{
  "provider": {
    "default": "openai",
    "models": {
      "openai": {
        "model": "gpt-4.1",
        "temperature": 0.2
      }
    }
  },
  "rules": {
    "auto_load": true,
    "directory": ".opencode/rules"
  }
}

# monorepo/frontend/.opencode/settings.json (覆盖)
{
  "provider": {
    "models": {
      "openai": {
        "model": "gpt-4.1",
        "temperature": 0.3
      }
    }
  },
  "rules": {
    "files": ["frontend-rules.md"]
  }
}

# monorepo/backend/.opencode/settings.json (覆盖)
{
  "provider": {
    "default": "anthropic",
    "models": {
      "anthropic": {
        "model": "claude-sonnet-4-20250514"
      }
    }
  },
  "rules": {
    "files": ["backend-rules.md", "api-conventions.md"]
  }
}

这样,根目录的配置提供通用规则,各子项目根据自身语言特点覆盖模型和规则。

七、配置最佳实践

7.1 全局配置建议

json
// ~/.opencode/settings.json - 你的个人偏好
{
  "provider": {
    "default": "anthropic",
    "models": {
      "anthropic": {
        "model": "claude-sonnet-4-20250514",
        "temperature": 0.1
      }
    }
  },
  "tools": {
    "allowed": ["read", "write", "edit", "terminal", "glob", "grep"]
  }
}

7.2 项目配置建议

json
// 项目 settings.json - 团队约定
{
  "$schema": "https://opencode.ai/schema/settings.json",
  "provider": {
    "models": {
      "anthropic": {
        "model": "claude-sonnet-4-20250514"
      }
    }
  },
  "agent": {
    "max_iterations": 30,
    "plan_review_required": true
  },
  "rules": {
    "auto_load": true,
    "priority_order": ["security.md", "coding.md", "testing.md"]
  },
  "tools": {
    "restricted": {
      "terminal": {
        "require_confirmation": true
      }
    }
  }
}

7.3 配置管理 Checklist

  • .opencode/settings.json 提交到版本控制
  • .gitignore 中排除本地临时配置
  • 使用 $schema 字段启用 IDE 自动补全
  • 定期运行 opencode config validate 检查配置
  • 在 CI 中验证配置的合法性
  • 文档化项目规则文件的内容
  • 团队成员评审规则文件的变更

总结

本文系统讲解了 OpenCode 的自定义配置体系:

  1. 三层配置架构:全局 → 项目 → 会话,逐层覆盖,灵活可控
  2. settings.json 完整配置:从 Provider、Agent、规则、上下文到工具限制的全字段详解
  3. 规则目录组织:多种策略组织规则文件,支持优先级排序和动态加载
  4. 层级加载机制:深度合并策略、查找路径、版本锁定、环境变量覆盖
  5. 配置验证与调试:validate、show、verbose 等调试命令
  6. 实战场景:从单语言项目到多语言 Monorepo 的配置实践

掌握自定义配置,你的 OpenCode 将从一个通用工具变成真正理解你的项目、遵守你的规范、适应你的工作流的专属编程助手。

核心心法:

  • 全局配偏好,项目配规范,会话配临时
  • 规则文件按优先级排序,安全规则永远放最前
  • 工具权限宁严勿宽,写操作永远要求确认
  • 配置进版本控制,团队约定可追溯