Claude Code 专业教学文档

基于模型的智能化终端编程工具系统


目录

  1. 系统概述
  2. 安装与配置
  3. 核心概念体系
  4. 基础操作实践
  5. 插件系统架构
  6. 高级特性
  7. 工作流优化
  8. 性能调优
  9. 故障诊断
  10. 最佳实践规范

1. 系统概述

1.1 定义与定位

Claude Code 是基于 Anthropic Claude 模型的智能化终端编程工具系统,其核心定位在于将自然语言处理能力与代码执行环境深度耦合,实现意图到执行的直接转换。

1.1.1 核心特性
特性维度 技术实现 业务价值
意图解析 Claude API + 上下文窗口管理 消除编程语言与用户意图之间的表达鸿沟
环境感知 LSP 集成 + 符号索引 具备代码库深度理解能力
工具扩展 MCP 协议 + 插件系统 可扩展至任意开发任务域
自主执行 Agent 子进程 + 事件循环 处理复杂多步骤任务
安全防护 多层 Hook 拦截 + 沙箱机制 保障操作可逆性与系统安全
1.1.2 架构范式

Claude Code 采用 Agent-First 架构模式,区别于传统工具链的函数调用模型,其执行单元为具备自主决策能力的智能体:

复制代码
输入 → [意图识别层] → [Agent 调度层] → [工具执行层] → [结果聚合层] → 输出
                ↓              ↓              ↓              ↓
        Skills 触发      Agents 并行      MCP 调用      上下文更新

1.2 技术栈与依赖

yaml 复制代码
runtime:
  node: ">=18.0.0"
  npm: ">=8.0.0"

api:
  anthropic:
    endpoint: "https://api.anthropic.com/v1/messages"
    models: ["claude-sonnet-4-5-20250401", "claude-opus-4.5-20251101"]
    max_tokens: 200000

protocols:
  tool_invocation: "MCP (Model Context Protocol)"
  language_server: "LSP 3.17"
  process_communication: "JSON-RPC over stdio"

storage:
  local_config: "~/.claude/"
  project_state: "./.claude/"
  cache: "~/.claude/cache/"

1.3 系统边界

在系统边界内:

  • 自然语言到工具调用的转换
  • 代码库符号索引与检索
  • 多 Agent 协同任务执行
  • 插件生命周期管理
  • Hook 事件拦截与修改
  • 上下文窗口智能管理

在系统边界外:

  • 模型训练与微调(Anthropic 服务)
  • 底层文件系统 API(Node.js fs)
  • 网络协议实现(操作系统层)
  • 进程调度(OS 调度器)

2. 安装与配置

2.1 安装流程

bash 复制代码
# 方案 A: 通过安装脚本(推荐)
# macOS/Linux
curl -fsSL https://claude.ai/install.sh | bash

# Windows (PowerShell)
irm https://claude.ai/install.ps1 | iex

# 方案 B: NPM 全局安装
npm install -g @anthropic-ai/claude-code

# 方案 C: 本地安装(开发)
git clone https://github.com/anthropics/claude-code.git
cd claude-code
npm install
npm link

验证安装:

bash 复制代码
claude --version
# 输出: 1.0.0

claude --help
# 显示可用选项和命令

2.2 身份认证

bash 复制代码
# 设置 API 密钥(必需)
export ANTHROPIC_API_KEY="sk-ant-API-KEY-HERE"

# 建议添加到 shell profile 以实现持久化
echo 'export ANTHROPIC_API_KEY="sk-ant-..."' >> ~/.zshrc  # 或 ~/.bashrc

# 验证密钥有效性
claude --validate-key
# 输出: API key is valid

密钥权限要求:

  • 标准 API 访问: 必需
  • 工具调用: 必需
  • 文件系统访问: 必需(本地)

2.3 配置体系

Claude Code 采用层次化配置覆盖模型

复制代码
┌────────────────────────────────┐
│  命令行参数                    │ ← 最高优先级
│  (--model, --plugin-dir)      │
├────────────────────────────────┤
│  环境变量                      │
│  (ANTHROPIC_API_KEY)          │
├────────────────────────────────┤
│  项目配置                      │
│  (./.claude/settings.json)    │
├────────────────────────────────┤
│  全局配置                      │
│  (~/.claude/settings.json)    │
├────────────────────────────────┤
│  系统默认值                    │ ← 最低优先级
└────────────────────────────────┘
2.3.1 全局配置模板
json5 复制代码
// ~/.claude/settings.json
{
  // 模型配置
  "model": {
    "default": "claude-sonnet-4.5-20250401",
    "commands": "claude-sonnet-4.5-20250401",
    "agents": "claude-sonnet-4.5-20250401",
    "maxTokens": 200000,
    "temperature": 0.0  // 代码任务保持确定性
  },

  // 插件系统
  "plugins": {
    "enabled": true,
    "autoLoad": true,
    "directories": ["~/.claude/plugins"],
    "marketplaceRepos": ["https://github.com/anthropics/claude-code-plugins"]
  },

  // 安全策略
  "security": {
    "enableHooks": true,
    "confirmDangerousCommands": true,
    "allowedCommands": ["git", "npm", "pnpm", "yarn"],
    "maxFileSize": "10MB",
    "blockedPaths": ["**/node_modules/**", "**/.git/**", "**/dist/**"]
  },

  // 上下文窗口
  "context": {
    "maxWindowSize": 200000,
    "sessionTimeout": 3600000,
    "messageHistoryLimit": 100,
    "autoTruncate": true,
    "summarizeThreshold": 0.8
  },

  // 缓存策略
  "cache": {
    "enabled": true,
    "ttl": 3600000,  // 1小时
    "maxSize": "100MB"
  }
}
2.3.2 项目级配置
json5 复制代码
// ./.claude/settings.json
{
  // 继承全局配置并覆盖
  "model": {
    "default": "claude-opus-4.5-20251101"  // 项目使用更强大的模型
  },

  // 项目专用插件
  "plugins": {
    "enabled": [
      "security-guidance",
      "code-review",
      "frontend-design"
    ]
  },

  // 项目 Hooks
  "hooks": {
    "local": {
      "require-tests": {
        "enabled": true,
        "pattern": "src/**/*.test.ts",
        "action": "block"
      }
    }
  },

  // 项目上下文
  "context": {
    "architecture": "monorepo",
    "framework": "React + TypeScript",
    "codingStandards": "./docs/coding-standards.md"
  }
}

2.4 初始化项目

首次使用时,Claude Code 执行环境扫描:

bash 复制代码
# 在项目根目录启动
claude

# Claude Code 自动执行以下检测:
# 1. 识别项目类型(React, Node.js, Python, etc.)
# 2. 扫描文件结构(建立符号索引)
# 3. 加载项目配置(.claude/settings.json)
# 4. 初始化插件(按 dependencies 自动加载)
# 5. 生成上下文摘要(加载相关 Skills)

3. 核心概念体系

3.1 Agent-First 执行范式

3.1.1 执行循环模型
复制代码
用户输入 → Claude API 决策 → 工具调用序列 → 结果聚合 → 响应生成
      ↑______________________________________________↓

关键特性:

  • 持续性: 单次会话维持完整上下文
  • 递归性: 工具结果反馈至决策层
  • 状态累积: 对话历史增量式增长
  • 自主终止: 模型自主判断任务完备性
3.1.2 事件驱动结构

Claude Code 主循环伪代码:

typescript 复制代码
interface MainLoop {
  async run(userInput: string): Promise<ExecutionResult> {
    // 初始化上下文
    const context = await this.initializeContext(userInput);

    // 执行循环
    while (!context.isComplete) {
      // 构建消息(含历史、工具定义)
      const messages = this.buildMessagePayload(context);

      // 调用 Claude API
      const response = await this.claude.createMessage(
        messages,
        this.getToolDefinitions()
      );

      // 处理响应类型
      if (response.type === 'text') {
        // 任务完成
        context.addResult(response.content);
        context.markComplete();
      } else if (response.type === 'tool_use') {
        // 执行工具链
        const toolResult = await this.executeTool(
          response.toolName,
          response.toolInput
        );

        // 追加结果至上下文
        context.addToolResult(toolResult);
      }

      // 上下文窗口管理
      if (context.exceedsTokenLimit()) {
        await context.truncateOldestMessages();
      }
    }

    return context.getResult();
  }
}

3.2 插件系统四元组

3.2.1 Commands(命令)

触发机制 : 显式调用,格式 /command [args]

执行流程:

复制代码
用户输入: /commit "fix: button alignment"
   ↓
词法分析 → 提取 command + arguments
   ↓
命令解析 → 在注册表中查找匹配项
   ↓
文档加载 → 读取 command.md 定义
   ↓
依赖注入 → 绑定工具集与上下文
   ↓
执行引擎 → 按步骤执行工具链
   ↓
结果格式化 → 返回用户界面

结构定义:

yaml 复制代码
# .claude-plugin/commands/commit.md
---
name: commit
type: command               # 必需
aliases: ["c"]              # 可选别名
parameters:                 # 参数规范
  message:
    type: string
    required: true
  amend:
    type: boolean
    default: false
requires: ["git"]          # 依赖工具
---

实现规范...
3.2.2 Agents(智能体)

核心属性:

  • 自主性: 独立执行决策循环
  • 隔离性: 独立进程与内存空间
  • 专用性: 特定领域系统提示
  • 可恢复: 会话级状态持久化

Agent 生命周期:

复制代码
用户请求 → Agent 识别 → 子进程创建 → 环境初始化 →
  ↓
任务执行 → [工具调用 <-> 决策] → 结果生成 →
  ↓
子进程终止 → 资源回收 → 状态序列化 → 结果集成

Agent 与 Skill 的关键区别:

维度 Agent Skill
调用方式 显式触发(Task 工具) 关键词自动匹配
执行模型 独立子进程 上下文注入
状态管理 进程级隔离 会话级共享
适用场景 复杂多步骤任务 知识增强
资源开销 高(独立进程) 低(文本注入)
典型示例 code-review, feature-dev coding-standards, security-audit
3.2.3 Skills(技能)

触发机制: 描述字段关键词匹配

yaml 复制代码
# 技能元数据设计模式
description: "This skill should be used when the user asks to [action] [subject].
              Include specific trigger phrases [phrase1], [phrase2], [phrase3]."

加载策略:

复制代码
Level 1: Metadata (100 tokens)    ← 始终加载
Level 2: SKILL.md (5k tokens)     ← 触发时加载
Level 3: References (unlimited)   ← 按需加载

模式示例:

复制代码
用户: "create a React component"
匹配: frontend-design (score 0.92)
用户: "optimize SQL query"
匹配: sql-optimization (score 0.95)
用户: "review this code"
匹配: code-review-guide (score 0.88) + security-audit (score 0.76)
3.2.4 Hooks(钩子)

事件类型与执行顺序:

复制代码
用户输入 → UserPromptSubmit (All hooks) → 主循环
   ↓
工具调用 → PreToolUse (Parallel, blocking) → 工具执行 → PostToolUse (Parallel, non-blocking)
   ↓
会话终止 → Stop (Sequential, blocking) → 进程退出

Hook 执行语义:

Hook 类型 执行顺序 阻塞性 退出码 返回值
UserPromptSubmit 并行 非阻塞 0=继续, 2=阻止 可选 systemMessage
PreToolUse 并行 硬阻塞 0=允许, 2=拒绝 必须 JSON
PostToolUse 并行 非阻塞 仅 0 可忽略
Stop 串行 软阻塞 0=退出, 2=延续 可选 reason

3.3 MCP(Model Context Protocol)

3.3.1 工具定义规范

MCP 工具定义数据结构:

typescript 复制代码
interface ToolDefinition {
  name: string;                          // 工具标识符
  description: string;                   // 自然语言描述
  input_schema: JSONSchema;             // 输入验证模式
}

interface JSONSchema {
  type: "object";
  properties: Record<string, {
    type: "string" | "number" | "boolean" | "array" | "object";
    description: string;
    enum?: any[];
    items?: JSONSchema;
    properties?: Record<string, JSONSchema>;
  }>;
  required: string[];
  additionalProperties?: boolean;
}

示例:Bash 工具定义

json 复制代码
{
  "name": "Bash",
  "description": "Execute shell commands with safety controls",
  "input_schema": {
    "type": "object",
    "properties": {
      "command": {
        "type": "string",
        "description": "Shell command to execute"
      },
      "timeout": {
        "type": "number",
        "description": "Timeout in milliseconds",
        "default": 120000
      }
    },
    "required": ["command"],
    "additionalProperties": false
  }
}
3.3.2 工具调用序列
复制代码
Claude API Response
  ↓
{ type: "tool_use", name: "Bash", input: { command: "npm test" } }
  ↓
工具识别 → ToolRegistry.get("Bash")
  ↓
输入验证 → JSONSchema.validate(input)
  ↓
Hook 拦截 → PreToolUse Hooks (可选阻止)
  ↓
执行操作 → child_process.spawn()
  ↓
结果格式化 → { exit_code, stdout, stderr }
  ↓
封装为 tool_result
  ↓
追加至对话历史
  ↓
下一轮决策

3.4 上下文窗口管理

3.4.1 Token 分配策略

Total: 200,000 tokens

复制代码
┌─────────────────────────────────────────┐
│ System prompt: 2,000 tokens (1%)        │
├─────────────────────────────────────────┤
│ Tools definitions: 5,000 tokens (2.5%)  │
├─────────────────────────────────────────┤
│ Conversation history: 173,000 (86.5%)   │
│   ├─ User messages                    │
│   ├─ Assistant reasoning              │
│   ├─ Tool calls                       │
│   └─ Tool results                     │
├─────────────────────────────────────────┤
│ Current request: 20,000 tokens (10%)   │
└─────────────────────────────────────────┘
3.4.2 智能截断算法
typescript 复制代码
class ContextTruncator {
  truncate(messages: Message[], maxTokens: number): Message[] {
    const systemMessages = messages.filter(m => m.type === 'system');
    const toolDefinitions = messages.filter(m => m.type === 'tool_definition');

    let remaining = maxTokens -
      this.tokenCount(systemMessages) -
      this.tokenCount(toolDefinitions);

    const conversation = messages.filter(m =>
      m.type === 'user' || m.type === 'assistant'
    );

    // 反向遍历(保留最新信息)
    const kept: Message[] = [];
    for (let i = conversation.length - 1; i >= 0; i--) {
      const msg = conversation[i];
      const tokenCount = this.tokenCount(msg);

      if (tokenCount > remaining) {
        // 截断旧消息,插入摘要
        const summary = this.summarize(conversation.slice(0, i));
        kept.unshift({
          type: 'user',
          content: `[Summary older ${i} messages]\n\n${summary}`
        });
        break;
      }

      kept.unshift(msg);
      remaining -= tokenCount;
    }

    return [...systemMessages, ...toolDefinitions, ...kept];
  }

  summarize(messages: Message[]): string {
    return "Key actions: " + messages
      .map(m => m.type === 'tool_result' ? m.toolName : m.type)
      .join(', ');
  }
}

4. 基础操作实践

4.1 文件系统操作

4.1.1 文件读取

命令格式:

复制代码
用户输入: "read package.json"

内部调用序列:

typescript 复制代码
// 1. Claude 决策 Read 工具
{
  "tool_use": {
    "name": "Read",
    "input": {
      "file_path": "/absolute/path/package.json"
    }
  }
}

// 2. 工具执行
class ReadTool {
  async execute(input: ReadInput): Promise<ReadResult> {
    const content = await fs.readFile(input.file_path, 'utf8');
    return {
      success: true,
      content: this.truncateIfNeeded(content, MAX_OUTPUT_SIZE)
    };
  }

  private truncateIfNeeded(content: string, limit: number): string {
    return content.length > limit
      ? content.substring(0, limit) + `\n...[${content.length - limit} more chars]`
      : content;
  }
}

// 3. 结果展示至用户界面

高级用法:

复制代码
"read src/main.js line 10-30"
 → 设置 offset: 10, limit: 21

"read large.log format:json"
 → 按 JSON 格式解析并展示结构

"read src/**/*.ts"
 → 触发 Glob 工具,返回匹配文件列表
4.1.2 文件编辑

原子编辑策略:

Claude Code 采用 三层验证 + 原子写入 机制:

typescript 复制代码
class EditTool {
  async execute(input: EditInput): Promise<EditResult> {
    // L1: 前置读取验证
    const original = await fs.readFile(input.file_path, 'utf8');

    // L2: 匹配验证
    const match = this.findMatch(original, input.old_string);
    if (!match) {
      throw new ValidationError(`Cannot find match in ${input.file_path}`);
    }

    // L3: Hook 拦截验证
    await this.pluginManager.executeHooks('PreToolUse', {
      tool_name: 'Edit',
      tool_input: input
    });

    // 应用修改
    const modified = input.replace_all
      ? original.replaceAll(input.old_string, input.new_string)
      : original.replace(input.old_string, input.new_string);

    // 原子写入
    await this.atomicWrite(input.file_path, modified);

    return {
      success: true,
      diff: this.generateDiff(original, modified)
    };
  }

  private async atomicWrite(path: string, content: string): Promise<void> {
    const temp = `${path}.claude-tmp-${Date.now()}`;
    await fs.writeFile(temp, content);
    await fs.fsync(temp);  // 确保持久化
    await fs.rename(temp, path);  // 原子替换
  }
}

最佳实践:

复制代码
✅ 推荐: 小范围精确修改
"replace console.log with logger.debug in src/utils/logger.js"

⚠️ 谨慎: 大范围批量替换
"replace all var with const in src/"
  → 建议先使用 Glob 确认范围
  → 配合 Git 提交以便回滚

✅ 推荐: 使用 replace_all 避免多次触发
"find all TODO comments and replace with FIXME"
  → replace_all=true

⚠️ 警告: 同时编辑多个文件
"edit multiple files containing API_KEY"
  → 建议逐个处理,确保每个修改正确

4.2 Shell 命令执行

4.2.1 命令安全分级

Claude Code 实施 三级安全策略

Level 1: 高危命令(强制确认)

bash 复制代码
rm -rf /
dd if=/dev/zero of=/dev/sda
:(){ :|:& };:  # Fork bomb

触发流程:

复制代码
用户请求 → 模式匹配 → 安全警告 → 强制确认 → 记录审计日志 → 执行

Level 2: 中危命令(可配置白名单)

bash 复制代码
sudo npm install -g package
git reset --hard HEAD^
npm unpublish package@version

白名单配置:

json 复制代码
{
  "security": {
    "commandWhitelist": [
      "sudo npm install",
      "git reset --hard HEAD"
    ]
  }
}

Level 3: 安全命令(直接执行)

bash 复制代码
ls -la
cat package.json
npm test
grep -r "function" src/
4.2.2 命令执行流程
typescript 复制代码
class BashTool {
  async execute(input: BashInput): Promise<BashResult> {
    // 1. 模式匹配
    const riskLevel = this.assessRisk(input.command);

    // 2. 用户确认(Level 1 & 2)
    if (riskLevel >= 2) {
      const confirmed = await this.getUserConfirmation(input.command);
      if (!confirmed) throw new UserCancelledError();
    }

    // 3. Hook 拦截
    const hookResult = await this.pluginManager.executeHooks('PreToolUse', {
      tool_name: 'Bash',
      tool_input: input
    });

    if (hookResult.blocked) throw new SecurityError(hookResult.message);

    // 4. 执行命令
    const result = await this.spawnProcess(input);

    // 5. 审计日志
    await this.auditLog.logCommand(input.command, result);

    return result;
  }
}
4.2.3 复杂命令构造

管道操作:

bash 复制代码
"execute: grep -r 'TODO' src/ | head -20"

Claude Code 正确实现:

typescript 复制代码
{
  "command": "bash -c 'grep -r \"TODO\" src/ | head -20'"
}

多命令序列:

bash 复制代码
"run: cd api && npm install && npm test && cd ../web && npm start"

重定向:

bash 复制代码
"execute: find . -name '*.log' -type f -mtime +7 -delete 2>&1"

4.3 搜索与导航

4.3.1 文件模式匹配(Glob)

Glob 语法支持:

复制代码
*.ts              # 当前目录 TypeScript 文件
**/*.js           # 递归所有 JavaScript 文件
src/{components,hooks}/*.tsx  # 多个目录
!**/*.test.ts     # 排除测试文件
**/*.{ts,tsx}     # 多扩展名

性能优化:

typescript 复制代码
// 使用 .gitignore 优化搜索
const ignore = parseGitignore('.gitignore');
const files = await fastGlob(pattern, { ignore });
4.3.2 内容搜索(Grep)

高级模式:

bash 复制代码
# 查找函数定义
grep -E "^function\s+\w+" src/

# 查找 React 组件
grep -B2 -A10 "export default function.*Component" src/

# 查找所有 TODO 并显示文件名
grep -l "TODO|FIXME|HACK" src/**/*.ts

# 排除 node_modules
grep -r "fetch(" src/ --glob="!node_modules/**"

5. 插件系统架构

5.1 插件类型与调用矩阵

调用方式 Agent Command Skill Hook
显式调用 ✅ Task() ✅ Slash 命令
关键词触发 ✅ 自动匹配
事件监听 ✅ Hook 事件
子进程 ✅ 是 ❌ 否 ❌ 否 ✅ 是
阻塞性 N/A N/A N/A ✅ 可阻塞
资源开销 极低

5.2 插件开发框架

5.2.1 脚手架创建
bash 复制代码
# 使用 plugin-dev 插件创建新插件
claude
> /plugin-dev:create-plugin "My Custom Plugin"

生成的目录结构:

复制代码
my-plugin/
├── .claude-plugin/
│   └── plugin.json
├── commands/
│   └── my-command.md
├── agents/
│   └── my-agent.md
├── skills/
│   └── my-skill/
│       └── SKILL.md
├── hooks/
│   └── pretooluse.py
└── README.md
5.2.2 Plugin Manifest 规范
json5 复制代码
// my-plugin/.claude-plugin/plugin.json
{
  "$schema": "https://anthropic.com/claude-code/plugin.schema.json",
  "name": "my-custom-plugin",
  "version": "1.0.0",
  "description": "Custom plugin for project-specific workflows",
  "author": {
    "name": "Engineering Team",
    "email": "eng@company.com"
  },
  "main": "./index.js",        // 可选:可执行入口
  "dependencies": [
    "plugin-dev",
    "security-guidance"
  ],
  "hooks": [                   // Hook 注册
    { "event": "PreToolUse", "script": "./hooks/security.py" }
  ],
  "commands": [                // 命令注册
    { "name": "deploy-staging", "path": "./commands/deploy.md" }
  ],
  "agents": [                  // Agent 注册
    { "name": "migration-guru", "path": "./agents/migration.md" }
  ]
}

5.3 Commands 开发详解

5.3.1 Command 文档结构
markdown 复制代码
// commands/deploy-staging.md
---
name: deploy-staging
category: deployment
type: command
aliases: ["deploy-stg"]
parameters:
  environment:
    type: choice
    choices: ["staging", "production"]
    default: "staging"
  skip-tests:
    type: boolean
    default: false
requires: ["Bash", "Read"]
git:
  requireClean: true
  branch: ["main", "develop"]
---

# Deploy Staging Command

Deploys application to staging environment with comprehensive checks.

## Implementation

1. Run pre-deployment checks:
   ```bash
   npm run lint
   npm run test:ci
  1. Verify environment variables:

    bash 复制代码
    cat .env.staging | grep -E "^(API_URL|DATABASE)"
  2. Execute deployment:

    bash 复制代码
    npm run build:staging && npm run deploy:staging

Error Handling

If tests fail, abort deployment and report errors.

Examples

bash 复制代码
/deploy-staging
/deploy-staging --environment=production --skip-tests=true
复制代码
#### 5.3.2 Command 执行引擎

```typescript
interface CommandExecutor {
  async execute(command: Command, args: string[]): Promise<Result> {
    // 1. 参数解析
    const parsed = this.parseArgs(command.parameters, args);

    // 2. 前置条件验证
    if (command.git?.requireClean) {
      await this.validateGitStatus();
    }

    // 3. Agent 转发(复杂命令)
    if (command.useAgent) {
      return await this.task({
        subagent_type: command.agent,
        prompt: this.buildAgentPrompt(command, parsed)
      });
    }

    // 4. 直接执行(简单命令)
    const steps = this.extractSteps(command.documentation);

    for (const step of steps) {
      if (step.type === 'bash') {
        await this.bash(step.command);
      } else if (step.type === 'read') {
        await this.read(step.file);
      }
    }

    return { success: true };
  }
}

5.4 Hooks 安全编程

5.4.1 Hook 实现模式

Hook 必须实现以下行为:

  • 永不崩溃主进程: 捕获所有异常
  • 确定性输出: stdout 必须有效 JSON
  • 快速响应: 超时时间 5 秒
  • 无阻塞: 使用异步 I/O
python 复制代码
#!/usr/bin/env python3
"""PreToolUse hook example."""

import sys
import json

def main():
    try:
        # 1. 读取输入
        input_data = json.load(sys.stdin)

        # 2. 执行逻辑
        result = evaluate_rules(input_data)

        # 3. 输出 JSON
        print(json.dumps(result))

    except Exception as e:
        # 4. 错误处理(不阻止主程序)
        print(json.dumps({}))  # 空对象 = 允许通过

    finally:
        # 5. 必须正常退出
        sys.exit(0)

def evaluate_rules(data: dict) -> dict:
    tool_name = data.get('tool_name')
    tool_input = data.get('tool_input')

    # 安全检查逻辑
    if tool_name == 'Bash':
        if 'rm -rf' in tool_input.get('command', ''):
            return {
                "systemMessage": "⚠️ Dangerous rm command detected",
                "hookSpecificOutput": {
                    "permissionDecision": "deny"
                }
            }

    return {}  # 允许通过

if __name__ == '__main__':
    main()
5.4.2 Rule Engine 设计
python 复制代码
class RuleEngine:
    def __init__(self):
        self.compiled_patterns = {}

    def evaluate(self, rules: list, input_data: dict) -> dict:
        """
        Evaluate all rules against input.
        Returns: { systemMessage, decision }
        """
        blocking_rules = []

        for rule in rules:
            if self.rule_matches(rule, input_data):
                if rule.get('action') == 'block':
                    blocking_rules.append(rule)

        # 阻塞规则优先
        if blocking_rules:
            return {
                "systemMessage": self.format_message(blocking_rules),
                "hookSpecificOutput": { "permissionDecision": "deny" }
            }

        return {}  # 允许

    def rule_matches(self, rule: dict, data: dict) -> bool:
        # 工具匹配检查
        if rule.get('tool_matcher'):
            if data.get('tool_name') not in rule['tool_matcher']:
                return False

        # 条件检查(必须全部满足)
        for condition in rule.get('conditions', []):
            if not self.check_condition(condition, data):
                return False

        return True

    def check_condition(self, condition: dict, data: dict) -> bool:
        field = self.extract_field(condition['field'], data)
        pattern = condition['pattern']

        if condition['operator'] == 'regex_match':
            return bool(re.search(pattern, field or '', re.IGNORECASE))

        elif condition['operator'] == 'contains':
            return pattern in (field or '')

        return False

5.5 Skills 开发方法论

5.5.1 Skill 设计原则

原则 1: 触发词精确性

yaml 复制代码
# ❌ 反模式:过于宽泛
description: "This skill is about code quality."
# 问题:触发范围失控,误匹配率 >30%

# ✅ 正模式:具体明确
description: |
  This skill should be used when the user asks to
  "create a hook", "add PreToolUse hook", "validate tool use",
  or mentions hook events (PreToolUse, PostToolUse, Stop).
# 优势:精确触发,召回率 >90%,误匹配率 <5%

原则 2: 渐进式披露

复制代码
总大小: 8,500 tokens
              ↓
SKILL.md: 1,800 tokens (21%) ← 核心加载
              ↓
References: 6,700 tokens (79%) ← 按需加载

原则 3: 资源明确引用

markdown 复制代码
# SKILL.md

## Advanced Patterns
See `references/patterns.md` for 20+ detailed examples.

## Use Cases
Check `examples/sample-config.json` for recommended setup.

## Validation Scripts
Run `scripts/validate.sh` to verify implementation.
5.5.2 Skill 性能优化
typescript 复制代码
// Skill 预热机制
class SkillCache {
  private lruCache = new LRUCache<string, ParsedSkill>(100);

  async loadSkill(skillPath: string): Promise<ParsedSkill> {
    // Check cache
    if (this.lruCache.has(skillPath)) {
      return this.lruCache.get(skillPath)!;
    }

    // Parse skill
    const skill = await this.parseSkill(skillPath);

    // Cache at Level 1 (metadata) and Level 2 (body)
    this.lruCache.set(skillPath, {
      metadata: skill.metadata,
      body: await this.readFile(skillPath)
    });

    // Don't cache Level 3 (references) until needed

    return skill;
  }
}

6. 高级特性

6.1 Multi-Agent 协同

6.1.1 Agent 编排模式

并行执行模式:

复制代码
用户: "Review this PR completely"

主 Agent (coordinator):
  ↓
┌─────────────┬─────────────┬─────────────┐
│             │             │             │
│  Agent A    │  Agent B    │  Agent C    │
│  (Security) │  (Quality)  │  (Tests)    │
│             │             │             │
└──────┬──────┴──────┬──────┴──────┬──────┘
       │             │             │
       └──────┬──────┴──────┬──────┘
              ↓             ↓
      结果聚合 → 综合报告

实现:

typescript 复制代码
// feature-dev plugin 实现
class ReviewOrchestrator {
  async reviewPullRequest(pr: PullRequest): Promise<ReviewReport> {
    // 并行启动多个 Agents
    const agents = [
      { type: 'security-auditor', prompt: 'Review for security issues' },
      { type: 'code-quality', prompt: 'Analyze code quality' },
      { type: 'test-analyzer', prompt: 'Check test coverage' }
    ];

    const results = await Promise.all(
      agents.map(agent =>
        this.task({
          subagent_type: agent.type,
          prompt: agent.prompt
        })
      )
    );

    // 综合结果
    return this.synthesizeResults(results);
  }

  synthesizeResults(results: AgentResult[]): ReviewReport {
    return {
      security: results[0].findings,
      quality: results[1].findings,
      tests: results[2].findings,
      summary: this.generateSummary(results),
      priority: this.calculatePriority(results)
    };
  }
}
6.1.2 Agent 通信协议
typescript 复制代码
interface AgentMessage {
  type: 'request' | 'response' | 'tool_use' | 'tool_result' | 'error';
  id: string;
  payload: any;
  timestamp: number;
}

class AgentIPC {
  async send(agentId: string, message: AgentMessage): Promise<void> {
    const agent = this.agents.get(agentId);
    agent.stdin.write(JSON.stringify(message) + '\n');
  }

  async recv(agentId: string): Promise<AgentMessage> {
    return new Promise((resolve, reject) => {
      const timeout = setTimeout(() => {
        reject(new Error('Agent response timeout'));
      }, 30000);

      const agent = this.agents.get(agentId);
      agent.stdout.once('data', (data) => {
        clearTimeout(timeout);
        resolve(JSON.parse(data));
      });
    });
  }
}

6.2 自定义工具集成

6.2.1 MCP 服务器注册
json5 复制代码
// .mcp.json in project root
{
  "servers": [
    {
      "name": "internal-api",
      "type": "http",
      "endpoint": "https://api.company.com/mcp",
      "auth": {
        "type": "bearer",
        "token": "${API_TOKEN}",  // 从环境变量读取
        "header": "Authorization"
      },
      "tools": [
        {
          "name": "deploy_service",
          "path": "/tools/deploy",
          "method": "POST"
        },
        {
          "name": "get_metrics",
          "path": "/tools/metrics",
          "method": "GET"
        }
      ]
    },
    {
      "name": "local-mcp",
      "type": "stdio",
      "command": "python3",
      "args": ["./mcp_server.py"],
      "description": "Local file analysis tools"
    }
  ]
}
6.2.2 自定义工具实现
python 复制代码
#!/usr/bin/env python3
"""MCP Stdio Server Example"""

import json
import sys
from typing import Dict, Any

def send_response(response: Dict[str, Any]) -> None:
    """Send JSON-RPC response."""
    print(json.dumps(response), flush=True)

def handle_list_tools():
    """List available tools."""
    return {
        "jsonrpc": "2.0",
        "id": 1,
        "result": {
            "tools": [
                {
                    "name": "analyze_complexity",
                    "description": "Analyze code complexity using cyclomatic complexity",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "file_path": {"type": "string"},
                            "threshold": {"type": "number", "default": 10}
                        },
                        "required": ["file_path"]
                    }
                }
            ]
        }
    }

def handle_call_tool(name: str, arguments: Dict[str, Any]):
    """Execute tool."""
    if name == "analyze_complexity":
        result = analyze_complexity(
            arguments["file_path"],
            arguments.get("threshold", 10)
        )
        return {
            "jsonrpc": "2.0",
            "id": 1,
            "result": {
                "content": [{"type": "text", "text": json.dumps(result)}]
            }
        }

def analyze_complexity(file_path: str, threshold: int) -> Dict:
    # 实现复杂度分析逻辑
    return {
        "file": file_path,
        "complexity": 15,
        "threshold": threshold,
        "violations": [...]
    }

def main():
    while True:
        line = sys.stdin.readline()
        if not line:
            break

        request = json.loads(line)
        method = request.get("method")

        if method == "tools/list":
            send_response(handle_list_tools())
        elif method == "tools/call":
            params = request.get("params", {})
            send_response(handle_call_tool(
                params["name"],
                params["arguments"]
            ))

if __name__ == "__main__":
    main()

6.3 工作流自动化

6.3.1 CI/CD 集成
yaml 复制代码
# .github/workflows/claude-code-check.yml
name: Claude Code Validation

on: [push, pull_request]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Set API Key
        env:
          CLAUDE_API_KEY: ${{ secrets.CLAUDE_API_KEY }}
        run: echo "export ANTHROPIC_API_KEY=$CLAUDE_API_KEY" >> ~/.bashrc

      - name: Run Code Standards Check
        run: |
          claude --non-interactive \
                 --expect-exit-code 0 \
                 "Check if all TypeScript files follow project coding standards"

      - name: Security Audit
        run: |
          claude --non-interactive \
                 --plugin security-guidance \
                 "Scan for security vulnerabilities in changed files"

      - name: Generate Review Summary
        if: github.event_name == 'pull_request'
        run: |
          claude --non-interactive \
                 --output review-summary.md \
                 "Review this PR and generate summary of changes and risks"
6.3.2 Pre-commit Hook 集成
bash 复制代码
#!/bin/bash
# .git/hooks/pre-commit

STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM)

if [ -n "$STAGED_FILES" ]; then
  # 使用 Claude Code 验证提交
  claude --non-interactive <<EOF
Review these staged files for quality issues:
$STAGED_FILES

If any critical issues found, exit with error code.
EOF

  if [ $? -ne 0 ]; then
    echo "Pre-commit checks failed. Fix issues before committing."
    exit 1
  fi
fi

7. 工作流优化

7.1 提示工程(Prompt Engineering)

7.1.1 任务分解模式

良好模式:

markdown 复制代码
# Task Decomposition Template

## Objective
Create a login form with validation and error handling.

## Requirements
1. Form fields: email, password
2. Validation: email format, password min length
3. Error display: inline messages
4. Success flow: redirect to dashboard

## Constraints
- Use React Hook Form
- Zod for validation
- Tailwind for styling

## Deliverables
- LoginForm.tsx component
- validation.ts schema
- Unit tests (LoginForm.test.tsx)

不良模式: ❌

markdown 复制代码
"Make a login form good"
7.1.2 上下文提供策略

Goldilocks Principle(适量原则):

复制代码
┌─────────────────────────────────────┐
│ 不足(Too Little)                    │
│  "Fix the bug"                        │
│  → Claude 不了解代码库,效率低下      │
├─────────────────────────────────────┤
│ ✅ 适量(Just Right)                  │
│  "Fix the bug in userAuth.ts:45 where│
│   validateToken fails for expired tokens"
│  → Claude 准确定位并修复             │
├─────────────────────────────────────┤
│ 过多(Too Much)                       │
│  粘贴整个 5000 行代码库               │
│  → 超出上下文窗口,关键信息丢失       │
└─────────────────────────────────────┘
7.1.3 增量式开发
bash 复制代码
# Round 1: 架构设计
> "Design the component structure for a dashboard page using React + TypeScript"

# Round 2: 实现骨架
> "Implement the Dashboard.tsx skeleton based on your design"

# Round 3: 添加功能
> "Add data fetching for the metrics panel in Dashboard.tsx"

# Round 4: 优化与测试
> "Add error handling and loading states, then write unit tests"

7.2 会话管理策略

7.2.1 会话划分原则

按任务划分:

复制代码
会话 1: "Implement user authentication system"
会话 2: "Create automated deployment pipeline"
会话 3: "Refactor legacy payment module"

按时间划分:

复制代码
开发会话: 2-3 小时,专注当前功能实现
审查会话: 30-60 分钟,代码审查与重构
规划会话: 15-30 分钟,架构设计与任务分解
7.2.2 上下文预热

启动新会话时:

bash 复制代码
# 加载项目上下文
> "Brief me on this codebase: architecture, tech stack, key directories"

# 加载相关文档
> "Read CONTRIBUTING.md and summarize coding standards"

# 查看最近变更
> "Show git log for last 5 commits in src/"

7.3 插件配置优化

7.3.1 项目级插件清单

Web 应用项目:

json 复制代码
{
  "plugins": {
    "enabled": [
      "security-guidance",
      "frontend-design",
      "code-review"
    ]
  }
}

微服务项目:

json 复制代码
{
  "plugins": {
    "enabled": [
      "security-guidance",
      "api-development",
      "testing-guide"
    ]
  }
}
7.3.2 性能优化配置
json 复制代码
{
  "context": {
    "autoTruncate": true,
    "summarizeThreshold": 0.8,
    "messageHistoryLimit": 50  // 减少历史消息保持响应速度
  },
  "cache": {
    "enabled": true,
    "ttl": 3600000,
    "maxSize": "50MB"
  }
}

8. 性能调优

8.1 性能指标定义

8.1.1 关键性能指标(KPI)
指标 定义 目标值 测量方法
首次响应时间 用户输入到首次输出时间 < 2s 前端计时器
工具调用延迟 工具调用到结果返回时间 < 500ms 工具层计时
Token 利用率 上下文窗口有效使用比例 > 85% Token 计数器
缓存命中率 缓存请求 / 总请求 > 60% 缓存统计
Agent 启动时间 Agent 子进程初始化时间 < 3s 进程计时
Hook 执行时间 单个 Hook 执行时间 < 100ms Hook 计时
8.1.2 性能监控实现
typescript 复制代码
class PerformanceMonitor {
  private metrics = new Map<string, Histogram>();

  recordToolLatency(tool: string, durationMs: number): void {
    const hist = this.metrics.get(`tool.${tool}.latency`) || new Histogram();
    hist.record(durationMs);
    this.metrics.set(`tool.${tool}.latency`, hist);
  }

  recordTokenUsage(type: TokenType, count: number): void {
    this.tokensByType[type] = (this.tokensByType[type] || 0) + count;
  }

  getReport(): PerformanceReport {
    return {
      timestamp: Date.now(),
      toolLatencies: Object.fromEntries(
        Array.from(this.metrics.entries()).map(([k, v]) => [
          k, v.getSnapshot()
        ])
      ),
      tokenUsage: this.tokensByType,
      cacheStats: this.cache.getStats()
    };
  }
}

8.2 性能优化策略

8.2.1 上下文窗口优化

策略 1: 选择性历史保留

typescript 复制代码
function selectMessagesToKeep(
  messages: Message[],
  maxTokens: number
): Message[] {
  const systemMessages = messages.filter(m => m.type === 'system');
  const tools = messages.filter(m => m.type === 'tool_definition');

  let budget = maxTokens - countTokens(systemMessages) - countTokens(tools);

  const conversation = messages.filter(m =>
    m.type === 'user' || m.type === 'assistant'
  );

  const keep: Message[] = [];
  let seenToolResults = 0;

  // 从后往前(最新优先)
  for (let i = conversation.length - 1; i >= 0; i--) {
    const msg = conversation[i];
    const tokens = countTokens(msg);

    // 始终保留最近 2 次工具结果
    if (msg.type === 'tool_result' && seenToolResults < 2) {
      keep.unshift(msg);
      seenToolResults++;
      budget -= tokens;
      continue;
    }

    if (tokens > budget) break;

    keep.unshift(msg);
    budget -= tokens;
  }

  return [...systemMessages, ...tools, ...keep];
}

策略 2: 智能摘要(Summary)

typescript 复制代码
async function summarizeLongContent(content: string): Promise<string> {
  // 将超过 5k tokens 的内容进行摘要
  if (countTokens(content) > 5000) {
    const summary = await claudeApi.summarize({
      content,
      maxLength: 500  // 摘要长度
    });
    return summary;
  }
  return content;
}
8.2.2 工具执行优化

批量操作:

typescript 复制代码
// ❌ 低效:多次操作
await Read('file1.ts');
await Read('file2.ts');
await Read('file3.ts');

// ✅ 高效:单次批量
await Promise.all([
  Read('file1.ts'),
  Read('file2.ts'),
  Read('file3.ts')
]);

缓存策略:

typescript 复制代码
class ToolCache {
  private cache = new Map<string, ToolResult>();

  async getOrExecute(
    key: string,
    executor: () => Promise<ToolResult>
  ): Promise<ToolResult> {
    const cached = this.cache.get(key);
    if (cached && this.isFresh(cached)) {
      return cached;
    }

    const result = await executor();
    this.cache.set(key, result);

    return result;
  }

  isFresh(result: ToolResult): boolean {
    return Date.now() - result.timestamp < TTL;
  }
}

// 使用示例
const result = await toolCache.getOrExecute(
  `Grep:${pattern}:${path}`,
  () => Grep(pattern, path)
);
8.2.3 Agent 启动优化

Agent 池化:

typescript 复制代码
class AgentPool {
  private idleAgents: Map<string, Agent[]> = new Map();

  async acquire(agentType: string): Promise<Agent> {
    const pool = this.idleAgents.get(agentType) || [];

    if (pool.length > 0) {
      return pool.pop()!;  // 复用空闲 Agent
    }

    // 创建新 Agent
    return await this.createAgent(agentType);
  }

  async release(agent: Agent): Promise<void> {
    const agentType = agent.type;
    if (!this.idleAgents.has(agentType)) {
      this.idleAgents.set(agentType, []);
    }

    // 重置 Agent 状态
    await agent.reset();

    this.idleAgents.get(agentType)!.push(agent);

    // 限制池大小
    if (this.idleAgents.get(agentType)!.length > MAX_POOL_SIZE) {
      await this.destroyAgent(agent);
    }
  }

  async shutdown(): Promise<void> {
    for (const agents of this.idleAgents.values()) {
      await Promise.all(agents.map(a => a.destroy()));
    }
  }
}

8.3 成本优化

8.3.1 Token 成本分析

假设模型定价:

  • Input: $3 / MTok
  • Output: $15 / MTok

典型任务成本:

任务类型 Input Tokens Output Tokens 成本 优化策略
文件读取 2k 500 $0.006 批量读取
代码审查 15k 3k $0.090 增量审查
功能开发 50k 10k $0.300 任务分解
全项目分析 150k 20k $0.750 按需分析
8.3.2 成本优化技巧

技巧 1: 模型选择

typescript 复制代码
// 简单任务使用 Sonnet(更便宜)
const estimation = await claude({
  model: 'claude-sonnet-4.5',
  prompt: 'Simple task...'
});  // Cost: ~$0.005

// 复杂任务使用 Opus(更智能)
const complex = await claude({
  model: 'claude-opus-4.5',
  prompt: 'Complex architecture design...'
});  // Cost: ~$0.500

技巧 2: 结果缓存

typescript 复制代码
class SessionCache {
  private embeddings = new Map<string, number[]>();

  async getEmbedding(text: string): Promise<number[]> {
    const cacheKey = this.hash(text);

    if (this.embeddings.has(cacheKey)) {
      return this.embeddings.get(cacheKey)!;
    }

    // 调用 API(成本较高)
    const embedding = await claude.embed(text);

    this.embeddings.set(cacheKey, embedding);

    return embedding;
  }
}

技巧 3: 上下文复用

typescript 复制代码
// ❌ 低效:每个请求包含完整历史
for (const file of files) {
  await claude({
    messages: [...fullHistory, `Review ${file}`]
  });
}

// ✅ 高效:提取摘要,减少 Token
const summary = await claude.summarize(fullHistory);

for (const file of files) {
  await claude({
    messages: [summary, `Review ${file}`]
  });
}

9. 故障诊断

9.1 常见问题分类

9.1.1 配置问题

问题 : Error: Invalid API key

诊断路径:

bash 复制代码
# 1. 验证密钥格式
echo $ANTHROPIC_API_KEY | grep -E "^sk-ant-[A-Za-z0-9]{32}$"

# 2. 测试 API 连通性
curl -X POST https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{"max_tokens": 10, "messages": [{"role": "user", "content": "Hi"}]}'

# 3. 检查 Claude Code 日志
cat ~/.claude/logs/error.log | grep -A5 "API key"

解决方案:

bash 复制代码
# 重新导出密钥
export ANTHROPIC_API_KEY="sk-ant-..."

# 持久化到配置
claude config set api.key "sk-ant-..."

问题 : Plugin X failed to load: Missing dependency Y

根本原因: 插件依赖的其他插件未安装

解决方案:

bash 复制代码
# 查看依赖树
claude plugin inspect plugin-x

# 安装缺失依赖
claude plugin install dependency-y
9.1.2 执行错误

问题 : Error: cannot find tool 'CustomTool'

诊断流程:

typescript 复制代码
// 1. 检查工具注册表
const tools = toolRegistry.list();
console.log('Registered tools:', Object.keys(tools));

// 2. 检查 MCP 配置
const mcpConfig = await loadMCPConfig();
console.log('MCP servers:', mcpConfig.servers.map(s => s.name));

// 3. 检查插件工具
pluginManager.getAll().forEach(p => {
  console.log(`${p.name} tools:`, p.tools);
});

问题 : Error: Invalid tool input

根本原因: Claude 生成的工具调用与 JSONSchema 不匹配

缓解措施:

typescript 复制代码
// Schema 优化:增加 description 和 examples
{
  "name": "deploy",
  "input_schema": {
    "type": "object",
    "properties": {
      "environment": {
        "type": "string",
        "description": "Target environment: 'staging' or 'production'",
        "enum": ["staging", "production"],
        "examples": ["staging"]
      }
    }
  }
}
9.1.3 性能问题

问题: 首次响应时间 > 5s

分析命令:

bash 复制代码
claude --trace-performance <<EOF
Analyze response time breakdown:
1. Tool discovery: ?ms
2. PreToolUse hooks: ?ms
3. Tool execution: ?ms
4. Token counting: ?ms
5. API latency: ?ms
EOF

# 查看实际性能指标
claude --performance-report

优化清单:

  • 禁用不必要的插件
  • 增加缓存 TTL
  • 使用更快的模型(Sonnet vs Opus)
  • 减少工具定义复杂度
  • 预编译常用正则

问题: 工具调用链过长(>10 次)

诊断:

bash 复制代码
# 启用详细日志
cat ~/.claude/logs/session_*.json | jq '.tool_calls | length'

重构策略:

typescript 复制代码
// ❌ 低效:细粒度工具链
await Read('file1');
await Grep('pattern1');
await Read('file2');
await Grep('pattern2');
// ... 重复 10 次

// ✅ 高效:批量化操作
await Promise.all([
  Read('file1').then(f => Grep(f, 'pattern1')),
  Read('file2').then(f => Grep(f, 'pattern2'))
]);

9.2 调试方法论

9.2.1 Claude Code 调试模式
bash 复制代码
# 启用调试日志
CLAUDE_DEBUG=1 claude

# 详细输出(包含工具调用)
claude --verbose

# 仅显示工具链执行
claude --show-tool-calls

# 记录完整会话
claude --log-session session_debug.json
9.2.2 Hook 调试
python 复制代码
#!/usr/bin/env python3
"""Debug Hook Example"""

import sys
import json
import logging

logging.basicConfig(
    filename='/tmp/hook_debug.log',
    level=logging.DEBUG
)

def main():
    # 记录接收到的数据
    raw_input = sys.stdin.read()
    logging.debug(f"Raw input: {raw_input}")

    try:
        data = json.loads(raw_input)
        logging.debug(f"Parsed data: {json.dumps(data, indent=2)}")

        # 记录决策逻辑
        decision = evaluate(data)
        logging.debug(f"Decision: {decision}")

        print(json.dumps(decision))

    except Exception as e:
        logging.error(f"Error: {e}", exc_info=True)
        print(json.dumps({}))

    finally:
        sys.exit(0)
9.2.3 Agent 调试技巧

Agent 日志分析:

bash 复制代码
# 查看 Agent 子进程日志
tail -f ~/.claude/sessions/session_*/agent_*.log

# 检查 Agent 工具调用统计
cat sessions/session_*.json | jq '.agents[] | {id, tools_called}'

Agent 单步执行:

typescript 复制代码
// 在 Agent 系统提示中添加调试指令
const debugPrompt = `
SYSTEM: You are Agent X
DEBUG: After each step, explain your reasoning before proceeding
RULES:
- Do not proceed until you receive confirmation
- Use explicit numbered steps
`;

9.3 崩溃恢复机制

9.3.1 自动快照保存
typescript 复制代码
class AutoSaveManager {
  private interval = 5 * 60 * 1000;  // 每 5 分钟

  start() {
    this.timer = setInterval(() => {
      this.saveSnapshot();
    }, this.interval);
  }

  async saveSnapshot() {
    const snapshot = {
      sessionId: this.session.id,
      timestamp: Date.now(),
      messages: this.session.messages,
      toolCalls: this.session.toolCalls
    };

    const path = `${SNAPSHOT_DIR}/${this.session.id}-${Date.now()}.json`;
    await fs.writeFile(path, JSON.stringify(snapshot));
  }

  async recover() {
    const snapshots = await this.findRecentSnapshots();
    if (snapshots.length === 0) return null;

    const latest = snapshots[snapshots.length - 1];
    return await this.loadSnapshot(latest);
  }
}
9.3.2 数据完整性验证
typescript 复制代码
class IntegrityChecker {
  async verifySnapshot(snapshot: Snapshot): Promise<boolean> {
    // 1. 检查关键技术
    if (!Array.isArray(snapshot.messages)) return false;

    // 2. 验证消息结构
    for (const msg of snapshot.messages) {
      if (!this.isValidMessage(msg)) {
        return false;
      }
    }

    // 3. 检查会话完整性
    const lastMessage = snapshot.messages[snapshot.messages.length - 1];
    return lastMessage.type === 'assistant' || lastMessage.type === 'tool_result';
  }

  isValidMessage(msg: any): boolean {
    const validTypes = ['user', 'assistant', 'system', 'tool_use', 'tool_result'];
    if (!validTypes.includes(msg.type)) return false;

    if (msg.type === 'tool_use') {
      return (
        typeof msg.toolName === 'string' &&
        typeof msg.toolInput === 'object'
      );
    }

    return true;
  }
}

10. 最佳实践规范

10.1 安全规范

10.1.1 敏感信息保护

禁止行为:

  • ❌ 在提示中直接包含 API 密钥
  • ❌ 将 .env 文件内容粘贴到对话
  • ❌ 提交包含密码的代码片段

推荐方案:

bash 复制代码
# 使用环境变量
export DATABASE_URL="postgresql://..."
claude config set secrets.db_url "$DATABASE_URL"

# 验证敏感文件被忽略
git check-ignore .env
10.1.2 Hook 安全审查

Hook 部署前检查清单:

markdown 复制代码
- [ ] Hook 脚本有完整异常捕获
- [ ] 退出码始终为 0(即使内部错误)
- [ ] 超时机制(防止阻塞)
- [ ] 输入验证(防止注入)
- [ ] 日志审计(可追溯)
- [ ] 资源限制(CPU、内存)
- [ ] 符号链接安全处理
- [ ] 路径遍历防护(../)

10.2 性能规范

10.2.1 Token 使用效率

Token 效率检查表:

markdown 复制代码
- [ ] 工具定义简洁(无冗余描述)
- [ ] Skill 描述精简(1,500-2,000 tokens)
- [ ] 避免重复信息(使用引用)
- [ ] 批量操作优于循环
- [ ] 缓存高频工具调用
- [ ] 及时清理无用会话
- [ ] 使用流式响应(streaming)
10.2.2 资源管理

会话清理策略:

bash 复制代码
# 每日清理旧会话
0 2 * * * find ~/.claude/sessions/ -mtime +7 -delete

# 限制同时活跃会话数
claude config set session.maxActive 10

# 自动清理关闭的会话
claude config set session.autoCleanup true

10.3 代码质量规范

10.3.1 插件代码质量标准

结构要求:

复制代码
插件目录/
├── .claude-plugin/plugin.json  # 必需,标准化格式
├── commands/*.md               # 可选,遵循 Command 规范
├── agents/*.md                 # 可选,包含完整工具集
├── skills/*/SKILL.md           # 可选,符合 Skills 规范
├── hooks/*.py                  # 可选,Hook 安全模式
├── README.md                   # 必需,完整文档
└── tests/                      # 可选,但推荐
    ├── unit/
    └── integration/

文档要求: 每个插件必须包含:

  • 功能概述
  • 使用示例
  • 配置说明
  • 依赖列表
  • 版本历史
10.3.2 测试覆盖率标准
组件类型 单元测试 集成测试 目标
Commands ✅ 必需 ✅ 必需 > 80%
Agents ❌ 不现实 ✅ 必需 > 70%
Skills ❌ 不适用 ✅ 推荐 > 60%
Hooks ✅ 必需 ✅ 推荐 > 75%
MCP Tools ✅ 必需 ✅ 必需 > 85%

10.4 团队协作规范

10.4.1 项目配置标准化

团队模板仓库:

复制代码
team-claude-configs/
├── README.md
├── web-app/
│   └── .claude/settings.json
├── api-service/
│   └── .claude/settings.json
└── shared/
    └── plugins/
        ├── security-rules/
        └── coding-standards/

项目初始化脚本:

bash 复制代码
#!/bin/bash
# init-claude.sh

PROJECT_TYPE=${1:-"web-app"}

echo "Setting up Claude Code for $PROJECT_TYPE..."

# 复制标准配置
cp -r team-claude-configs/$PROJECT_TYPE/.claude ./

# 安装团队插件
claude plugin install team-claude-configs/shared/plugins/*

# 设置 API 密钥(交互式)
read -sp "Enter Anthropic API key: " API_KEY
echo
echo "export ANTHROPIC_API_KEY=$API_KEY" >> ~/.claude/env

echo "Setup complete! Run 'claude' to start."
10.4.2 最佳实践共享

团队 Skills 库: 将团队规范封装为 Skills

bash 复制代码
team-skills/
├── company-coding-standards/
│   └── SKILL.md
├── deployment-workflow/
│   └── SKILL.md
└── code-review-checklist/
    └── SKILL.md

共享方式:

bash 复制代码
# 1. Git Submodule
git submodule add https://github.com/company/team-skills.git .claude/team-skills

# 2. Git Hook 自动同步
echo 'cd .claude/team-skills && git pull' > .git/hooks/post-merge

10.5 文档规范

10.5.1 交互日志管理

会话归档

bash 复制代码
# 归档重要会话
claude --export-session refactoring-session-2025-01-15.json

# 归档到团队知识库
cp refactoring-session-2025-01-15.json \
  team-knowledge/sessions/

决策记录(ADR): 重要技术决策需在 Claude Code 中记录

bash 复制代码
# 创建架构决策记录
claude <<EOF
Create a new ADR for: Use TypeScript instead of JavaScript

Include:
1. Context and problem statement
2. Decision (use TypeScript)
3. Alternatives considered
4. Consequences

Save to: docs/adr/001-use-typescript.md
Follow template: docs/adr/template.md
EOF

附录

附录 A: 快速参考表

A.1 常用命令
命令 说明 示例
/commit 提交代码 /commit "feat: add user auth" --no-verify
/code-review PR 审查 /code-review
/feature-dev 功能开发 /feature-dev "Build dashboard"
/plugin 插件管理 /plugin install security-guidance
/hookify Hook 创建 /hookify create "block-rm-rf"
A.2 快捷键与交互
快捷键 功能
Ctrl+C 中断当前操作
Ctrl+D 退出会话
Tab 命令补全
↑/↓ 历史导航
Ctrl+L 清屏
A.3 环境变量
变量 说明 示例
ANTHROPIC_API_KEY API 密钥(必需) sk-ant-...
CLAUDE_MODEL 默认模型 claude-sonnet-4.5
CLAUDE_CONFIG_DIR 配置目录 ~/.claude
CLAUDE_PLUGIN_DIR 插件目录 ~/.claude/plugins
ENABLE_SECURITY_REMINDER 启用安全提醒 1

附录 B: 故障速查表

B.1 启动问题
症状 原因 解决方案
command not found 未安装或不在 PATH npm install -g @anthropic-ai/claude-code
API key missing 未设置密钥 export ANTHROPIC_API_KEY="sk-ant-..."
Permission denied 文件权限 chmod +x ~/.npm-global/bin/claude
B.2 执行问题
症状 原因 解决方案
"Cannot find tool" 未注册 检查插件安装,claude plugin list
"Invalid tool input" Schema 不匹配 检查 JSONSchema 定义
"Hook blocked" Hook 阻止 查看 Hook 输出,调整规则
B.3 性能问题
症状 原因 解决方案
响应缓慢 >5s 上下文过大 清理对话历史,/clear
工具卡顿 缓存未命中 启用缓存,cache.enabled=true
Agent 启动慢 冷启动 使用 Agent Pool

附录 C: 架构决策记录

C.1 决策 001: 使用 MCP 协议

背景: 需要统一的工具调用规范

考虑方案:

  • 自定义 JSON-RPC
  • OpenAI Function Calling
  • Anthropic MCP (Model Context Protocol) ← 选定

决策理由:

  1. MCP 提供完整的工具发现、调用、结果规范
  2. 与 Claude API 原生集成
  3. 支持多种传输方式(stdio, http, sse)
  4. 可扩展至外部服务

影响: 所有工具实现必须符合 MCP 规范

相关推荐
Fuly10242 小时前
大模型架构理解与学习
人工智能·语言模型
KG_LLM图谱增强大模型2 小时前
[谷歌最新白皮书]嵌入与向量存储:打开AI多模态数据处理的钥匙
人工智能·大模型·知识图谱·向量存储·多模态
roman_日积跬步-终至千里2 小时前
【人工智能导论】08-学习-如何让计算机理解序列数据——用RNN/LSTM建模时序依赖,用文本嵌入表示序列元素
人工智能·rnn·学习
技术吧2 小时前
2025年AI不是宠物,是会思考的幽灵!
人工智能·宠物
苍何3 小时前
以前我以为达人营销很玄学,用了 Aha 才知道还能这么玩!(附教程)
人工智能
苍何3 小时前
扣子彻底变了!拥抱 Vibe Coding,不只是智能体!
人工智能
苍何3 小时前
抢先实测豆包1.8模型,多模态Agent超强!
人工智能
黎相思3 小时前
项目简介
人工智能·chatgpt
Coding茶水间3 小时前
基于深度学习的安检危险品检测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
图像处理·人工智能·深度学习·yolo·目标检测·机器学习·计算机视觉