<!-- title: Claude Code配置体系全解析：五层优先级到沙箱实战 -->

# Claude Code配置体系全解析：五层优先级到权限沙箱实战

## 概述

Claude Code的配置体系是一个五层优先级的精密系统，决定了AI助手"能做什么"和"怎么做"。本教程从`settings.json`的完整字段解析出发，深入权限系统的`allow/ask/deny`三层规则引擎、沙箱隔离机制、Hooks生命周期钩子，直到企业级部署的MDM推送策略。适合已安装Claude Code但希望系统掌握配置治理的开发者和团队负责人。

## 前置条件

- Claude Code已安装（`npm install -g @anthropic-ai/claude-code`）
- 基本终端操作能力
- 了解JSON格式
- 一个已初始化Git的项目（用于实践项目级配置）

---

## 第一章：五层配置优先级——谁说了算？

### 1.1 配置层次架构

Claude Code的配置不是单一文件，而是五层堆叠的优先级体系。理解这五层，是掌控Claude Code行为的基石。

```mermaid
graph TB
    subgraph "配置优先级（从高到低）"
        A["🔒 Managed<br/>企业托管配置<br/>无法被任何层级覆盖"]
        B["⌨️ CLI Arguments<br/>命令行参数<br/>临时会话覆盖"]
        C["🏠 Local<br/>~/.claude/settings.local.json<br/>项目级个人覆盖"]
        D["📂 Project<br/>项目级共享配置<br/>团队统一规范"]
        E["👤 User<br/>用户级全局配置<br/>跨项目个人偏好"]
    end
    A --> B --> C --> D --> E
    style A fill:#ff6b6b,color:#fff
    style B fill:#ffd93d,color:#333
    style C fill:#6bcb77,color:#fff
    style D fill:#4d96ff,color:#fff
    style E fill:#9b59b6,color:#fff
```

每一层的存储位置与作用域如下表：

| 层级 | 文件位置 | 影响范围 | 是否共享 |
|------|---------|---------|---------|
| **Managed** | 系统级（macOS: plist，Windows: registry）或 `managed-settings.json` | 本机所有用户 | IT部署 |
| **CLI Arguments** | `--permission-mode`、`--settings` 等 | 当前会话 | 否 |
| **Local** | 项目根目录 `.claude/settings.local.json` | 当前项目、仅自己 | 否（gitignored） |
| **Project** | 项目根目录 `.claude/settings.json` | 当前项目、所有协作者 | 是（提交到git） |
| **User** | `~/.claude/settings.json` | 所有项目、仅自己 | 否 |

### 1.2 关键规则：覆盖与合并

**常规设置**采用覆盖策略——高优先级的值直接替换低优先级的值。例如User层设置 `spinnerTipsEnabled: true`，Project层设置 `spinnerTipsEnabled: false`，最终结果为 `false`。

**权限规则**采用合并策略——所有层级的 `allow`、`ask`、`deny` 规则会被合并在一起，但按 `deny → ask → allow` 的顺序评估，第一条匹配的规则胜出。这意味着Managed层的deny规则在任何情况下都无法被低层级的allow规则绕过。

### 1.3 实战：验证当前生效配置

在Claude Code交互会话中运行：

```bash
# 查看当前所有权限规则及其来源
/permissions

# 在终端中直接检查配置
cat ~/.claude/settings.json         # 用户级
cat .claude/settings.json           # 项目级
cat .claude/settings.local.json     # 本地覆盖
```

**常见问题**：修改了`settings.json`但行为没变？检查是否有更高优先级的层级在覆盖。

---

## 第二章：settings.json完全字段解析

### 2.1 核心配置结构

`settings.json` 是一个JSON文件，包含以下主要字段：

```json
{
  "permissions": {
    "allow": [],
    "deny": [],
    "ask": [],
    "defaultMode": "default"
  },
  "hooks": {},
  "env": {},
  "model": "claude-sonnet-4-6",
  "sandbox": {
    "enabled": false
  },
  "outputStyle": "default",
  "spinnerTipsEnabled": true,
  "additionalDirectories": [],
  "enabledPlugins": [],
  "strictKnownMarketplaces": [],
  "allowManagedPermissionRulesOnly": false,
  "allowManagedHooksOnly": false
}
```

### 2.2 逐字段详解

#### permissions——权限控制引擎

```json
{
  "permissions": {
    "defaultMode": "default",
    "allow": [
      "Bash(npm test *)",
      "Bash(git status)",
      "Read",
      "Grep",
      "Glob"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "WebSearch"
    ],
    "ask": [
      "Bash(*)"
    ],
    "disableBypassPermissionsMode": "disable",
    "disableAutoMode": "disable"
  }
}
```

**字段说明**：

| 字段 | 作用 | 示例 |
|------|------|------|
| `defaultMode` | 默认权限模式 | `default` / `acceptEdits` / `plan` / `auto` / `bypassPermissions` |
| `allow` | 无需确认直接执行 | `"Bash(npm test *)"` 允许所有npm test命令 |
| `deny` | 完全禁止 | `"Bash(rm -rf *)"` 阻止危险删除 |
| `ask` | 每次需要确认 | `"Bash(*)"` 所有Bash命令需确认 |
| `disableBypassPermissionsMode` | 禁用bypass模式 | `"disable"` 阻止使用 `--dangerously-skip-permissions` |
| `disableAutoMode` | 禁用auto模式 | `"disable"` 阻止自动批准模式 |

**七种权限模式详解**：

```mermaid
graph LR
    subgraph "权限模式光谱"
        A["plan<br/>只读探索<br/>最安全"] --> B["default<br/>标准确认"]
        B --> C["acceptEdits<br/>自动编辑"]
        C --> D["auto<br/>后台安全检查"]
        D --> E["dontAsk<br/>拒绝未预批准"]
        E --> F["bypassPermissions<br/>跳过所有提示<br/>最危险"]
    end
    style A fill:#27ae60,color:#fff
    style F fill:#e74c3c,color:#fff
```

| 模式 | 行为 | 适用场景 |
|------|------|---------|
| `plan` | 只读探索，不可编辑文件 | 代码审查、架构分析 |
| `default` | 首次使用工具需确认 | 日常开发 |
| `acceptEdits` | 自动接受文件编辑和常见文件操作 | 频繁修改场景 |
| `auto` | 后台安全检查后自动批准 | 高信任环境（研究预览） |
| `dontAsk` | 拒绝未预批准的工具调用 | CI/CD流水线 |
| `bypassPermissions` | 跳过所有权限提示 | 隔离容器/VM |

#### env——环境变量注入

```json
{
  "env": {
    "ANTHROPIC_API_KEY": "",
    "NODE_ENV": "development",
    "CUSTOM_CONFIG_PATH": "/path/to/config"
  }
}
```

通过`env`字段注入的环境变量会在Claude Code启动时加载，优先级低于系统环境变量。API Key等敏感信息建议通过系统环境变量设置，而非硬编码到`settings.json`。

#### model——模型选择

```json
{
  "model": "claude-sonnet-4-6"
}
```

可选值包括：
- `claude-opus-4-6` — 最强推理能力
- `claude-sonnet-4-6` — 性能与成本平衡（默认）
- `claude-haiku-4-5` — 最快响应速度

#### hooks——生命周期钩子

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write $CLAUDE_FILE_PATH"
          }
        ]
      }
    ]
  }
}
```

Hooks将在第四章详细讲解。

#### sandbox——沙箱隔离

```json
{
  "sandbox": {
    "enabled": true,
    "autoAllowBashIfSandboxed": true,
    "allowUnsandboxedCommands": false,
    "excludedCommands": ["git"],
    "network": {
      "allowLocalBinding": false,
      "allowedDomains": ["registry.npmjs.org", "github.com"],
      "allowAllUnixSockets": false,
      "allowUnixSockets": []
    },
    "enableWeakerNestedSandbox": false
  }
}
```

沙箱配置将在第三章详细讲解。

### 2.3 完整配置模板

以下是一个适合中型团队的项目级`settings.json`模板：

```json
{
  "permissions": {
    "defaultMode": "acceptEdits",
    "allow": [
      "Bash(npm run *)",
      "Bash(npx *)",
      "Bash(git *)",
      "Bash(node *)",
      "Bash(cat *)",
      "Bash(ls *)",
      "Bash(pwd)",
      "Read",
      "Grep",
      "Glob",
      "WebFetch"
    ],
    "deny": [
      "Bash(rm -rf /)",
      "Bash(rm -rf ~)",
      "Bash(sudo *)",
      "Bash(chmod 777 *)"
    ],
    "ask": [
      "Bash(*)"
    ]
  },
  "env": {
    "NODE_ENV": "development"
  },
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write $CLAUDE_FILE_PATH 2>/dev/null || true"
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "npm test 2>&1 | tail -20"
          }
        ]
      }
    ]
  },
  "additionalDirectories": ["../shared-lib"],
  "spinnerTipsEnabled": false
}
```

**常见问题**：`settings.json`格式错误导致Claude Code无法启动？用 `cat settings.json | python3 -m json.tool` 验证JSON格式。

---

## 第三章：权限系统与沙箱隔离

### 3.1 权限规则语法

权限规则的核心是**工具名 + 模式匹配**的语法：

```
ToolName(pattern)
```

**基础语法规则**：

| 规则 | 含义 |
|------|------|
| `"Read"` | 允许/禁止所有文件读取 |
| `"Bash"` | 允许/禁止所有Bash命令 |
| `"Bash(npm test *)"` | 匹配以`npm test`开头的命令 |
| `"Bash(git *)"` | 匹配所有git命令 |
| `"Edit"` | 允许/禁止所有文件编辑 |
| `"MCP"` | 允许/禁止所有MCP工具调用 |

**通配符规则**：
- `*` 匹配任意字符序列
- 多个模式用 `|` 分隔：`"Edit|Write"` 同时匹配两种工具
- 模式区分大小写

**评估顺序**：`deny → ask → allow`。第一条匹配的规则生效。

```mermaid
flowchart TD
    A["工具调用请求"] --> B{"匹配deny规则?"}
    B -->|是| C["❌ 拒绝执行"]
    B -->|否| D{"匹配ask规则?"}
    D -->|是| E["🔔 弹出确认对话框"]
    D -->|否| F{"匹配allow规则?"}
    F -->|是| G["✅ 自动执行"]
    F -->|否| H{"权限模式?"}
    H -->|default| E
    H -->|bypassPermissions| G
    H -->|plan| I["❌ 拒绝（plan模式不可写入）"]
    style C fill:#e74c3c,color:#fff
    style G fill:#27ae60,color:#fff
    style E fill:#f39c12,color:#fff
```

### 3.2 工具特定权限规则

不同的工具有不同的权限语法：

#### Bash工具

```json
{
  "allow": [
    "Bash(npm run lint)",
    "Bash(npm test *)",
    "Bash(git status)",
    "Bash(git diff *)",
    "Bash(git log *)",
    "Bash(python3 *)"
  ],
  "deny": [
    "Bash(rm -rf *)",
    "Bash(sudo *)",
    "Bash(curl * | bash)",
    "Bash(wget * -O * | bash)"
  ]
}
```

**进阶技巧**：Bash规则支持复合命令检测。`Bash(git *)` 会匹配 `git status && git diff`，因为命令以 `git` 开头。

#### 文件操作工具

```json
{
  "allow": [
    "Read",
    "Glob",
    "Grep"
  ],
  "deny": [
    "Write(.env*)",
    "Edit(.env*)",
    "Write(*credentials*)",
    "Write(*secret*)"
  ]
}
```

#### MCP工具

```json
{
  "allow": [
    "mcp__github__*",
    "mcp__database__query"
  ],
  "deny": [
    "mcp__database__drop*"
  ]
}
```

### 3.3 沙箱隔离机制

沙箱是Claude Code最强大的安全防线。启用后，所有Bash命令在受限环境中执行：

**Docker沙箱**（推荐用于生产环境）：

```json
{
  "sandbox": {
    "enabled": true,
    "autoAllowBashIfSandboxed": true,
    "network": {
      "allowedDomains": [
        "registry.npmjs.org",
        "github.com",
        "api.github.com"
      ],
      "allowLocalBinding": false
    }
  }
}
```

**沙箱配置字段详解**：

| 字段 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `enabled` | boolean | false | 是否启用沙箱 |
| `autoAllowBashIfSandboxed` | boolean | false | 沙箱内Bash命令自动批准 |
| `allowUnsandboxedCommands` | boolean | false | 允许部分命令在沙箱外运行 |
| `excludedCommands` | array | [] | 不受沙箱限制的命令列表 |
| `network.allowedDomains` | array | [] | 允许访问的域名白名单 |
| `network.allowLocalBinding` | boolean | false | 允许本地端口绑定 |
| `network.allowUnixSockets` | array | [] | 允许的Unix socket路径 |
| `network.allowAllUnixSockets` | boolean | false | 允许所有Unix socket |
| `network.httpProxyPort` | number | null | HTTP代理端口 |
| `network.socksProxyPort` | number | null | SOCKS代理端口 |
| `enableWeakerNestedSandbox` | boolean | false | 允许在已有沙箱内使用更弱的沙箱 |

**三种安全级别配置对比**：

```mermaid
graph TB
    subgraph "Lax - 宽松模式"
        L1["✅ Bash命令自由执行"]
        L2["✅ 无沙箱限制"]
        L3["✅ 仅禁止bypass模式"]
    end
    subgraph "Strict - 严格模式"
        S1["🔔 所有Bash需确认"]
        S2["❌ 禁止WebSearch/WebFetch"]
        S3["❌ 禁止用户自定义hooks"]
        S4["❌ 禁止用户自定义权限规则"]
    end
    subgraph "Sandbox - 沙箱模式"
        X1["🔒 Bash在沙箱内执行"]
        X2["🔒 网络白名单限制"]
        X3["❌ 禁止用户自定义权限规则"]
    end
    L1 --- L2 --- L3
    S1 --- S2 --- S3 --- S4
    X1 --- X2 --- X3
```

Anthropic官方提供的三种预设配置：

**宽松配置** (`settings-lax.json`)：
```json
{
  "permissions": {
    "disableBypassPermissionsMode": "disable"
  },
  "strictKnownMarketplaces": []
}
```

**严格配置** (`settings-strict.json`)：
```json
{
  "permissions": {
    "disableBypassPermissionsMode": "disable",
    "ask": ["Bash"],
    "deny": ["WebSearch", "WebFetch"]
  },
  "allowManagedPermissionRulesOnly": true,
  "allowManagedHooksOnly": true,
  "strictKnownMarketplaces": []
}
```

**沙箱配置** (`settings-bash-sandbox.json`)：
```json
{
  "allowManagedPermissionRulesOnly": true,
  "sandbox": {
    "enabled": true,
    "autoAllowBashIfSandboxed": false,
    "allowUnsandboxedCommands": false,
    "network": {
      "allowLocalBinding": false,
      "allowedDomains": []
    }
  }
}
```

### 3.4 /permissions命令交互式管理

在Claude Code交互会话中，`/permissions` 命令提供了一个可视化界面来管理权限：

```
> /permissions

Permission Rules (from settings.json)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ ALLOW  Bash(npm test *)          — project settings
✅ ALLOW  Bash(git *)               — project settings
✅ ALLOW  Read                      — user settings
🔔 ASK    Bash(*)                   — project settings
❌ DENY   Bash(rm -rf *)            — project settings
❌ DENY   Bash(sudo *)              — managed settings
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

每条规则右侧标注了来源层级，方便排查冲突。

---

## 第四章：Hooks——生命周期自动化引擎

### 4.1 Hooks事件体系

Hooks是Claude Code的自动化核心，支持在30+个生命周期节点触发自定义逻辑：

```mermaid
flowchart LR
    subgraph "会话生命周期"
        A["SessionStart"] --> B["InstructionsLoaded"]
        B --> C["UserPromptSubmit"]
        C --> D["PreToolUse"]
        D --> E["PostToolUse"]
        E --> F["PostToolBatch"]
        F --> G["Stop"]
        G --> C
    end

    subgraph "特殊事件"
        H["PermissionRequest"]
        I["PermissionDenied"]
        J["Notification"]
        K["SubagentStart"]
        L["SubagentStop"]
        M["SessionEnd"]
    end

    style A fill:#3498db,color:#fff
    style G fill:#e74c3c,color:#fff
    style M fill:#2c3e50,color:#fff
```

**最常用的六大Hook事件**：

| 事件 | 触发时机 | 典型用途 |
|------|---------|---------|
| `SessionStart` | 会话开始 | 环境变量设置、依赖检查 |
| `PreToolUse` | 工具调用前 | 拦截危险操作、注入上下文 |
| `PostToolUse` | 工具调用后 | 自动格式化、代码检查 |
| `PostToolBatch` | 批量工具调用完成 | 批量验证 |
| `Stop` | Claude完成响应 | 运行测试套件 |
| `Notification` | 发送通知时 | 集成Slack/Discord |

### 4.2 Hook配置语法

```json
{
  "hooks": {
    "<EventName>": [
      {
        "matcher": "<ToolPattern>",
        "hooks": [
          {
            "type": "command",
            "command": "your-shell-command"
          }
        ]
      }
    ]
  }
}
```

- **matcher**：匹配工具名的正则表达式，空字符串匹配所有工具
- **type**：`command`（Shell命令）、`http`（HTTP请求）、`prompt`（LLM提示）
- **command**：要执行的Shell命令

### 4.3 六大实战Hook配置

#### Hook 1：自动格式化（PostToolUse）

文件被编辑后自动运行Prettier：

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}
```

**预期行为**：Claude每次编辑文件后，Prettier自动格式化该文件。`$CLAUDE_FILE_PATH` 是Claude Code注入的环境变量，指向被操作的文件。

#### Hook 2：自动Lint检查（PostToolUse）

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "npx eslint \"$CLAUDE_FILE_PATH\" --fix 2>&1 | head -30"
          }
        ]
      }
    ]
  }
}
```

#### Hook 3：响应完成后自动测试（Stop）

```json
{
  "hooks": {
    "Stop": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "cd $PROJECT_DIR && npm test 2>&1 | tail -30"
          }
        ]
      }
    ]
  }
}
```

**注意**：Stop hook在每次Claude完成响应时触发。如果你的测试套件很慢，考虑只在关键修改后手动运行测试。

#### Hook 4：敏感文件保护（PreToolUse）

阻止Claude写入敏感文件：

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "FILE=\"$CLAUDE_FILE_PATH\"; if echo \"$FILE\" | grep -qE '\\.(env|key|pem|p12)$|credentials|secret'; then echo 'BLOCK: Sensitive file detected' >&2; exit 2; fi"
          }
        ]
      }
    ]
  }
}
```

**关键机制**：Hook返回exit code 2会**阻止**工具调用执行，并向Claude传递拒绝原因。exit code 0允许执行，exit code 1允许执行但输出会作为上下文传给Claude。

#### Hook 5：Git自动暂存（PostToolUse）

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "git add \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}
```

#### Hook 6：Slack通知（Notification）

```json
{
  "hooks": {
    "Notification": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "curl -s -X POST \"$SLACK_WEBHOOK_URL\" -H 'Content-type: application/json' --data '{\"text\":\"Claude Code: $CLAUDE_NOTIFICATION\"}'"
          }
        ]
      }
    ]
  }
}
```

### 4.4 Hook高级特性

#### HTTP Hook

除了Shell命令，Hook还支持HTTP请求：

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "http",
            "url": "http://localhost:8080/validate",
            "headers": {
              "Authorization": "Bearer $VALIDATION_TOKEN"
            }
          }
        ]
      }
    ]
  }
}
```

#### 异步Hook

长时间运行的任务可以配置为异步执行：

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "npm run build 2>&1 | tail -10",
            "async": true
          }
        ]
      }
    ]
  }
}
```

异步Hook不会阻塞Claude的响应，结果会在后台收集。

**常见问题**：Hook中引用的环境变量 `$CLAUDE_FILE_PATH` 为空？确保你的匹配器正确——只有在工具确实操作了文件时才会注入此变量。

---

## 第五章：.claude目录与CLAUDE.md完整结构

### 5.1 .claude目录全景图

```
project-root/
├── .claude/
│   ├── settings.json          # 项目级共享配置
│   ├── settings.local.json    # 项目级个人覆盖（gitignored）
│   ├── CLAUDE.md              # 项目级指令（备选位置）
│   ├── rules/                 # 条件加载的规则文件
│   │   ├── typescript.md      # TypeScript相关规则
│   │   ├── react.md           # React相关规则
│   │   └── database.md        # 数据库相关规则
│   ├── agents/                # 自定义子Agent
│   │   ├── reviewer.md        # 代码审查Agent
│   │   └── architect.md       # 架构设计Agent
│   ├── skills/                # 自定义Skills
│   │   └── deploy/
│   │       └── SKILL.md
│   ├── commands/              # 自定义斜杠命令
│   │   └── check.md
│   ├── output-styles/         # 自定义输出样式
│   │   └── concise.md
│   └── auto.md                # 自动记忆存储
├── CLAUDE.md                  # 项目指令（主位置）
├── CLAUDE.local.md            # 个人项目指令（gitignored）
└── .mcp.json                  # MCP服务器配置
```

### 5.2 CLAUDE.md加载层级

CLAUDE.md同样遵循多层加载：

| 文件 | 位置 | 作用域 | Git |
|------|------|--------|-----|
| `~/.claude/CLAUDE.md` | 用户主目录 | 所有项目 | 否 |
| `CLAUDE.md` | 项目根目录 | 当前项目 | 是 |
| `.claude/CLAUDE.md` | .claude目录 | 当前项目 | 是 |
| `CLAUDE.local.md` | 项目根目录 | 当前项目、仅自己 | 否 |

所有层级的CLAUDE.md都会被加载（不是覆盖），内容会**合并**到Claude的系统提示中。

### 5.3 rules/目录的条件加载

`.claude/rules/` 中的文件可以按条件加载——只有当操作涉及特定路径时才激活：

```markdown
<!-- .claude/rules/typescript.md -->
---
description: TypeScript项目规则
globs: ["**/*.ts", "**/*.tsx"]
---

# TypeScript 规范
- 使用严格模式
- 优先使用 interface 而非 type
- 禁止使用 any
- 导出函数必须有JSDoc注释
```

`globs` 字段定义了触发条件，只有Claude操作匹配这些glob模式的文件时，规则才会被注入到上下文。

### 5.4 MCP服务器配置

MCP服务器通过 `.mcp.json` 配置（项目级）或 `~/.claude.json`（用户级）：

```json
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "database": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "${DATABASE_URL}"
      }
    }
  }
}
```

---

## 第六章：实战案例——从零配置一个生产级项目

### 6.1 场景描述

假设你是一个5人前端团队的负责人，项目是一个Next.js + TypeScript的应用。需要配置Claude Code使得：

1. 团队成员有统一的开发体验
2. 代码质量和格式一致
3. 敏感文件受保护
4. CI/CD流程与Claude Code集成

### 6.2 Step 1：创建项目级CLAUDE.md

```markdown
# 项目：Next.js电商平台

## 技术栈
- Next.js 15 (App Router)
- TypeScript 5.x
- Tailwind CSS 4
- Prisma ORM
- PostgreSQL

## 代码规范
- 使用函数组件和hooks
- 文件命名：kebab-case
- 组件目录：src/components/
- API路由：src/app/api/
- 数据库操作：src/lib/db.ts
- 禁止直接使用fetch，使用 src/lib/api-client.ts

## 测试
- 测试框架：Vitest + Testing Library
- 运行命令：npm test
- 所有新功能必须有测试

## Git
- 分支命名：feat/xxx, fix/xxx, chore/xxx
- Commit message：Conventional Commits
- 不自动commit，需要手动确认
```

### 6.3 Step 2：创建项目级settings.json

```json
{
  "permissions": {
    "defaultMode": "acceptEdits",
    "allow": [
      "Bash(npm run *)",
      "Bash(npx *)",
      "Bash(git status)",
      "Bash(git diff *)",
      "Bash(git log *)",
      "Bash(node *)",
      "Read",
      "Grep",
      "Glob"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(sudo *)",
      "Write(.env*)",
      "Write(*credentials*)",
      "Write(*secret*)"
    ],
    "ask": [
      "Bash(*)"
    ]
  },
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
          },
          {
            "type": "command",
            "command": "npx eslint \"$CLAUDE_FILE_PATH\" --fix 2>&1 | tail -5"
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "npm run typecheck 2>&1 | tail -10"
          }
        ]
      }
    ]
  },
  "additionalDirectories": [],
  "spinnerTipsEnabled": false
}
```

### 6.4 Step 3：创建条件规则文件

```markdown
<!-- .claude/rules/api-routes.md -->
---
description: API路由开发规则
globs: ["src/app/api/**/*.ts"]
---

# API路由规则
- 所有API路由必须有输入验证（使用zod）
- 错误处理使用统一的 errorResponse 函数
- 响应格式：{ success: boolean, data?: T, error?: string }
- 必须认证的路由使用 withAuth 中间件包装
```

```markdown
<!-- .claude/rules/components.md -->
---
description: React组件开发规则
globs: ["src/components/**/*.tsx"]
---

# 组件规则
- 使用 "use client" 标记客户端组件
- Props使用 interface 定义
- 事件处理函数使用 handle 前缀
- 状态管理优先使用 useState，复杂场景用 zustand
- 每个组件对应一个 .test.tsx 测试文件
```

### 6.5 Step 4：个人覆盖配置

每个开发者可以在 `.claude/settings.local.json` 中添加个人偏好：

```json
{
  "model": "claude-opus-4-6",
  "outputStyle": "concise",
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"File: $CLAUDE_FILE_PATH\" with title \"Claude Code\"' 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}
```

### 6.6 Step 5：CI/CD集成配置

在CI环境中使用Claude Code，需要特殊配置：

```yaml
# .github/workflows/claude-review.yml
name: Claude Code Review
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          permission_mode: "plan"
          settings: |
            {
              "permissions": {
                "defaultMode": "plan",
                "deny": ["Bash", "Write", "Edit"]
              }
            }
```

CI中使用 `plan` 模式确保Claude Code只能读取和分析代码，不会做出任何修改。

### 6.7 最终目录结构验证

```bash
# 验证配置文件存在且格式正确
find . -name "settings*.json" -o -name "CLAUDE*.md" -o -name "*.mcp.json" | \
  while read f; do
    echo "=== $f ==="
    if [[ "$f" == *.json ]]; then
      python3 -m json.tool "$f" > /dev/null && echo "✅ Valid JSON" || echo "❌ Invalid JSON"
    else
      head -3 "$f"
    fi
  done
```

**预期输出**：
```
=== ./CLAUDE.md ===
# 项目：Next.js电商平台
=== ./CLAUDE.local.md ===
# 个人项目偏好
=== .claude/settings.json ===
✅ Valid JSON
=== .claude/settings.local.json ===
✅ Valid JSON
```

---

## 第七章：企业级部署——MDM与托管配置

### 7.1 托管配置机制

企业环境中，IT管理员可以通过MDM（移动设备管理）系统将配置推送到所有开发者的机器上：

| 平台 | 配置位置 | 部署方式 |
|------|---------|---------|
| macOS | `~/Library/Preferences/com.anthropic.claude-code.plist` | Jamf / Kandji / MDM配置文件 |
| Windows | Registry: `HKLM\SOFTWARE\Anthropic\Claude Code` | Intune / Group Policy |
| Linux | `/etc/claude-code/managed-settings.json` | 配置管理工具 |

### 7.2 企业级安全配置

```json
{
  "permissions": {
    "disableBypassPermissionsMode": "disable",
    "disableAutoMode": "disable",
    "deny": [
      "WebSearch",
      "WebFetch",
      "Bash(curl * | *)",
      "Bash(wget * | *)"
    ],
    "ask": [
      "Bash(*)"
    ]
  },
  "allowManagedPermissionRulesOnly": true,
  "allowManagedHooksOnly": true,
  "strictKnownMarketplaces": ["https://marketplace.example.com"],
  "sandbox": {
    "enabled": true,
    "autoAllowBashIfSandboxed": false,
    "allowUnsandboxedCommands": false,
    "network": {
      "allowedDomains": [
        "registry.npmjs.org",
        "github.com",
        "internal-npm.company.com"
      ],
      "allowLocalBinding": false
    }
  }
}
```

此配置确保：
- `bypassPermissions` 和 `auto` 模式被禁用
- 用户无法覆盖权限规则和Hooks
- 只允许安装来自指定市场的插件
- 所有Bash命令在沙箱内执行
- 网络访问限制为公司内部和必要的外部域名

### 7.3 验证托管配置是否生效

```bash
# macOS
defaults read com.anthropic.claude-code

# 在Claude Code中
/config
# 查看 "Managed Settings" 标签页
```

---

## 第八章：配置排错指南

### 8.1 常见问题速查表

| 问题 | 原因 | 解决方案 |
|------|------|---------|
| 修改settings.json后行为未变 | 更高层级在覆盖 | 检查 `/permissions` 查看来源 |
| Hook未触发 | matcher不匹配 | 确认工具名大小写 |
| JSON解析失败 | 格式错误 | `python3 -m json.tool settings.json` |
| 权限拒绝但已配置allow | deny规则优先级更高 | 检查是否有deny规则匹配 |
| MCP服务器连接失败 | 命令路径问题 | 使用绝对路径 |
| 环境变量未生效 | settings中env优先级较低 | 使用系统环境变量 |

### 8.2 调试配置加载

```bash
# 查看Claude Code实际加载的配置（需要开启verbose模式）
claude --verbose "check config"

# 检查各层级配置文件是否存在
echo "=== User Level ===" && cat ~/.claude/settings.json 2>/dev/null || echo "Not found"
echo "=== Project Level ===" && cat .claude/settings.json 2>/dev/null || echo "Not found"
echo "=== Local Override ===" && cat .claude/settings.local.json 2>/dev/null || echo "Not found"
```

### 8.3 配置冲突解决流程

```mermaid
flowchart TD
    A["配置行为异常"] --> B{"是权限问题?"}
    B -->|是| C["运行 /permissions"]
    C --> D["检查规则来源层级"]
    D --> E["调整对应层级配置"]
    B -->|否| F{"是Hook问题?"}
    F -->|是| G["检查 /hooks 菜单"]
    G --> H["验证matcher和命令"]
    H --> I["手动运行Hook命令测试"]
    F -->|否| J{"是环境变量?"}
    J -->|是| K["检查 settings.json env 字段"]
    K --> L["对比系统环境变量"]
    J -->|否| M["检查CLAUDE.md加载"]
    M --> N["确认文件位置和格式"]
```

---

## 总结：配置体系全景

Claude Code的配置体系可以用一个矩阵来总结：

| 维度 | 机制 | 核心文件 |
|------|------|---------|
| **指令** | CLAUDE.md多层合并 | `CLAUDE.md`, `.claude/rules/*.md` |
| **权限** | deny→ask→allow规则链 | `settings.json` permissions字段 |
| **安全** | 沙箱隔离+网络白名单 | `settings.json` sandbox字段 |
| **自动化** | 30+生命周期事件钩子 | `settings.json` hooks字段 |
| **扩展** | MCP协议连接外部工具 | `.mcp.json` |
| **治理** | 五层优先级+托管配置 | `managed-settings.json` |

配置Claude Code不是一次性工作，而是随着团队成熟度逐步演进的过程：

1. **第一周**：配置基本CLAUDE.md + 简单权限
2. **第一个月**：添加Hooks自动化 + 条件规则
3. **团队扩展时**：引入沙箱 + 托管配置
4. **企业部署时**：MDM推送 + 插件市场管控

## 参考来源

1. [Claude Code Settings - 官方文档](https://code.claude.com/docs/en/settings) — 五层配置优先级、settings.json字段完整说明
2. [Configure Permissions - 官方文档](https://code.claude.com/docs/en/permissions) — 权限规则语法、七种模式、沙箱配置
3. [Hooks Reference - 官方文档](https://code.claude.com/docs/en/hooks) — 30+生命周期事件、JSON输入输出格式
4. [Explore the .claude directory - 官方文档](https://code.claude.com/docs/en/claude-directory) — 目录结构、文件用途、加载顺序
5. [Claude Code Settings Examples - GitHub](https://github.com/anthropics/claude-code/tree/main/examples/settings) — Anthropic官方三种预设配置模板

> [!tip] 51学通信知识星球
> **星主：爱卫生**（微信：gprshome201101）——公众号「51学通信」创办者，19 年通信行业运维与讲师经验，著有《GPRS网络信令实例详解》《EPC原理与实践》《5G核心网原理与实践》三本纸质书（各大电商平台有售）。
> **星球定位**：深耕 5G 核心网、IMS、NFV/AI、云原生等 ICT 领域，主打运维岗位与信令分析。
> **当前规模**：5200 篇主题 / 990 个回答，198 元/年。
> **加入福利**：加入星球后请加爱卫生微信，拉您进知识星球年度陪伴与答疑群——不限量回复您的各种问题，另有群内分享。
> **AI 加持**：51学通信知识星球已作为 skill 接入 WorkBuddy，使用 deepseek-4-flash 在海量星球帖子中精准找贴、找视频、找 FAQ 和案例，做总结、找文档和 PPT 等场景全覆盖。

![51学通信知识星球海报-扫码加入](https://wiki.500nian.com/images/zhixingqiu_qrcode.png)
