Claude Code Commands 教学文档

掌握 Commands 系统 - 构建可复用的工作流自动化工具


目录

  1. [Commands 概述](#Commands 概述)
  2. [Command 结构详解](#Command 结构详解)
  3. [创建你的第一个 Command](#创建你的第一个 Command)
  4. [Command 类型与模式](#Command 类型与模式)
  5. [高级 Command 开发](#高级 Command 开发)
  6. 实战案例
  7. 最佳实践
  8. 故障排查

1. Commands 概述

1.1 什么是 Commands

Commands (命令)是 Claude Code 中显式调用 的自动化工作流,以 /command 格式触发。当你输入 /commit "message" 时,就是在调用一个 Command。

核心作用:

  • 封装重复性工作流: 将多步骤任务封装为单条命令
  • 标准化团队流程: 确保团队成员遵循一致的流程
  • 简化复杂操作: 将 10 个步骤的 Git 流程简化为 1 条命令
  • 提供交互式指导: 引导用户完成复杂任务

1.2 Commands vs 其他插件组件

组件类型 触发方式 执行模型 适用场景
Commands 显式调用(/ 同步/异步工具链 重复性工作流
Agents Task() 独立子进程 + 自主循环 复杂多步骤任务
Skills 关键词匹配 上下文注入 知识增强
Hooks 事件监听 拦截器 安全检查

何时使用 Commands:

  • ✅ 流程标准化(Git 工作流、部署流程)
  • ✅ 重复性任务(代码格式化、测试运行)
  • ✅ 交互式引导(新手引导、环境配置)
  • ✅ 批量操作(文件重命名、批量修改)

何时不使用 Commands:

  • ❌ 需要自主决策(用 Agents)
  • ❌ 需要知识引导(用 Skills)
  • ❌ 安全检查(用 Hooks)

2. Command 结构详解

2.1 基本结构

每个 Command 是一个 Markdown 文件,包含 YAML Frontmatter + Markdown 内容:

markdown 复制代码
---
# YAML Frontmatter(元数据)
name: command-name           # 命令名称
allowed-tools: Bash(git), Read  # 允许使用的工具
description: Description   # 描述
---

# Markdown 内容(指令)

## Context

可执行上下文命令(运行并提供结果)

## Your task

Claude 需要执行的任务说明

2.2 YAML Frontmatter 字段

yaml 复制代码
---
# 必需字段
name: command-name           # 命令唯一标识
description: Description   # 在帮助中显示

# 可选字段
allowed-tools: Bash(git), Read  # 工具白名单
argument-hint: "description"    # 参数提示
parameters:                    # 参数定义(高级)
  param1:
    type: string
    required: true
  param2:
    type: boolean
    default: false

# Git 相关
git:
  requireClean: true          # 要求工作区干净
  branch: ["main", "dev"]       # 允许的分支

# 依赖
depends-on: []               # 依赖其他插件
requires: ["Bash", "Git"]     # 需要这些工具
---

2.3 上下文命令(Context)

Command 的独特功能:在调用时自动执行上下文命令:

markdown 复制代码
---
# metadata
---

## Context

Current status: !`git status`                    # 执行并插入结果
Recent commits: !`git log --oneline -10`        # 使用反引号
Branch: !`git branch --show-current`

工作原理:

复制代码
用户: /commit "message"
   ↓
Claude Code:
  1. 解析 commit.md
  2. 执行 Context 中的所有 !`command`
  3. 将执行结果插入 system prompt
  4. 告诉 Claude "You have the capability to call tools..."
   ↓
Claude: 基于当前状态生成工具调用
   ↓
执行工具链 → 完成

优势:

  • Claude 知道当前状态(git status, 分支等)
  • 减少对话轮数
  • 避免滞后决策

2.4 任务指令(Task)

markdown 复制代码
## Your task

Based on the above changes:

1. Create a single commit with appropriate message
2. Push to origin
3. You have the capability to call multiple tools in a single response

**CRITICAL**: Do not use any other tools. You MUST do all in a single message.

关键指令:

  • "You have the capability to call multiple tools" - 授权多工具调用
  • "in a single response" - 强制批量执行
  • "Do not use any other tools" - 限制范围

3. 创建你的第一个 Command

3.1 目标:创建一个部署命令

创建一个 /deploy-staging 命令,自动完成:

  1. 检查是否有未提交的更改
  2. 运行测试
  3. 构建项目
  4. 部署到 staging 环境

3.2 步骤 1:创建目录结构

bash 复制代码
# 在项目或全局插件目录
cd my-project
mkdir -p .claude-plugin/commands  # 或使用插件目录

# 创建命令文件
touch .claude-plugin/commands/deploy-staging.md

3.3 步骤 2:编写 YAML Frontmatter

yaml 复制代码
---
name: deploy-staging
description: Deploy application to staging environment with full verification
allowed-tools: Bash, Read
argument-hint: "[--skip-tests] -- skip running tests"
---

3.4 步骤 3:编写上下文

markdown 复制代码
## Context

Current git status: !`git status --porcelain`
Current branch: !`git branch --show-current`
Last commit: !`git log -1 --oneline`
Test status: !`npm test --silent 2>&1 || echo "Tests not run yet"`
Build status: !`ls -la dist/ 2>/dev/null || echo "No build artifacts"`

3.5 步骤 4:编写任务指令

markdown 复制代码
## Your task

Based on the above context, deploy the application to staging:

1. **Check prerequisites**:
   - If git status shows uncommitted changes, fail with error
   - If on main branch, require confirmation

2. **Run tests** (unless --skip-tests):
   - Run `npm test`
   - If tests fail, abort deployment

3. **Build project**:
   - Run `npm run build:staging`
   - Verify dist/ directory exists

4. **Deploy**:
   - Run deployment command
   - Verify deployment success

5. **Report results**:
   - Deployment status
   - URL (if available)
   any issues encountered

You have the capability to call multiple tools in a single response. Please do steps 2-4 in as few tool calls as possible.

**CRITICAL**: If any step fails, stop and report the error. Do not proceed.

3.6 步骤 5:测试你的 Command

bash 复制代码
# 启动 Claude Code
claude

# 测试命令(使用 dry-run 模式)
> "/deploy-staging --skip-tests"

# 查看执行过程
Claude Code 应该:
✓ 执行上下文命令(git status, branch等)
✓ 识别未提交更改并警告
✓ 跳过测试(--skip-tests)
✓ 执行构建
✓ 运行部署

3.7 完整示例

markdown 复制代码
// .claude-plugin/commands/deploy-staging.md

---
name: deploy-staging
description: Deploy application to staging environment with full verification
allowed-tools: Bash, Read, Glob
git:
  requireClean: true
  branch: ["develop", "staging", "release/*"]
---

## Context

Git status: !`git status --porcelain`
Current branch: !`git branch --show-current`
Last commit: !`git log -1 --oneline`
Last test run: !`cat .last-test-run 2>/dev/null || echo "never"`
Build artifacts: !`ls -la dist/ 2>/dev/null | wc -l`

## Your task

Deploy application to staging environment following these steps:

### 1. Prerequisites Check

- FAIL if git status shows uncommitted changes
- WARN if on main branch (require explicit confirmation)
- CONTINUE if all checks pass

### 2. Test Phase (if --skip-tests not provided)

- Run: `npm test -- --coverage`
- Verify: All tests pass
- Store: Test results in .last-test-run

### 3. Build Phase

- Run: `npm run build:staging`
- Verify: dist/ directory exists and has files
- Check: No build errors

### 4. Deploy Phase

- Run: `npm run deploy:staging`
- Verify: Exit code 0
- Extract: Deployment URL from output

### 5. Verification

- Run: `curl -f $DEPLOYMENT_URL/health`
- Verify: HTTP 200 status
- Report: Success + URL + timestamp

You can call multiple tools in a single response. Minimize tool calls by batching commands.

If any step fails, stop immediately and report the error.

4. Command 类型与模式

4.1 模式 1:简单工具链(Git Commands)

特点:

  • 2-5 个工具调用
  • 同步执行
  • 线性流程
  • 无需人工干预

示例 : /commit

yaml 复制代码
---
name: commit
description: Create a git commit
allowed-tools: Bash(git add:*), Bash(git commit:*)
---

## Context

Git status: !`git status`
Diff: !`git diff HEAD`
Branch: !`git branch --show-current`

## Your task

1. Stage all changes: `git add .`
2. Create commit: `git commit -m $MESSAGE`
3. Report commit hash

Do all in single message.

4.2 模式 2:条件逻辑(Branch Check)

特点:

  • 包含 if/else 逻辑
  • 基于上下文决策
  • 可能需要用户确认

示例 : /deploy-staging(见上)

4.3 模式 3:多阶段 Agent(Feature Dev)

特点:

  • 7+ 个阶段
  • 每个阶段使用 Agent
  • 需要用户确认
  • 涉及决策点

示例 : /feature-dev

yaml 复制代码
---
description: Guided feature development with codebase understanding
argument-hint: Optional feature description
---

## Phase 1: Discovery

Ask clarifying questions.

## Phase 2: Exploration

Launch code-explorer agents.

## Phase 3: Questions

Identify gaps, ask user.

## Phase 4: Architecture

Launch code-architect agents.

## Phase 5: Implementation

Wait for approval, then implement.

## Phase 6: Review

Launch code-reviewer agents.

## Phase 7: Summary

Document what was built.

关键要点:

  • 每个阶段有明确目标
  • 使用 TodoWrite 跟踪进度
  • 需要用户确认才能继续
  • 多个 Agent 并行执行

4.4 模式 4:并行 Agent(Code Review)

特点:

  • 3-5 个 Agent 并行
  • 不同 Agent 专注不同方面
  • 结果聚合
  • 置信度加权

示例 : /code-review

yaml 复制代码
---
description: Review pull request
description: Code review a pull request
---

## Your task

1. Launch haiku agent to check PR status (closed/draft/already reviewed)

2. Launch sonnet agent to summarize PR changes

3. Launch 4 agents in parallel:
   - Agent 1+2: CLAUDE.md compliance
   - Agent 3: Bug detection
   - Agent 4: Code quality

4. Consolidate findings

5. Present to user

并行执行流程:

复制代码
用户: /code-review
   ↓
主程序:
  ├─ 启动 Agent 1 (安全) → 等待结果
  ├─ 启动 Agent 2 (质量) → 等待结果
  ├─ 启动 Agent 3 (测试) → 等待结果
  └─ 启动 Agent 4 (简化) → 等待结果
      ↓
  Promise.all([...])  // 并行执行
      ↓
  收集结果 → 聚合 → 去重 → 排序(置信度)
      ↓
  生成综合报告

4.5 模式 5:交互式引导(Interactive Setup)

特点:

  • 多轮对话
  • 逐步引导用户
  • 收集输入
  • 验证配置

示例 : /setup-project

yaml 复制代码
---
name: setup-project
description: Interactive project setup wizard
---

## Phase 1: Collect Requirements

Ask user:
- Project name?
- Tech stack? (React, Vue, Node)
- Features needed?
- Testing framework?

## Phase 2: Validate

Check if directory exists.
Check if dependencies available.

## Phase 3: Generate

Create package.json
Create directory structure
Install dependencies

## Phase 4: Verify

Verify installation succeeded
Run tests
Show next steps

5. 高级 Command 开发

5.1 参数处理

简单参数(字符串):

yaml 复制代码
---
name: deploy
description: Deploy to environment
argument-hint: "<environment> -- Environment: staging|production"
---

## Your task

Environment: $ARGUMENTS

1. Validate environment is "staging" or "production"
2. Deploy to $ARGUMENTS

使用示例:

bash 复制代码
> /deploy staging
> /deploy production

高级参数(显式定义):

yaml 复制代码
---
name: release
parameters:
  version:
    type: string
    required: true
    description: "Version number (e.g., 1.2.3)"
  skip-tests:
    type: boolean
    default: false
    description: "Skip test execution"
  environment:
    type: choice
    choices: ["staging", "production"]
    default: "staging"
---

参数解析(使用 $ARGUMENTS):

bash 复制代码
用户输入: /release 1.2.3 --skip-tests --environment=production

Claude 接收:
$ARGUMENTS = "1.2.3 --skip-tests --environment=production"

解析:
- version: "1.2.3" (第一个词)
- skip-tests: true (包含 --skip-tests)
- environment: "production" (extract from --environment=...)

参数解析示例代码:

typescript 复制代码
// 在 Command 中的解析逻辑

## Your task

Parse $ARGUMENTS to extract:
- version: first word
- skip-tests: true if contains "--skip-tests"
- environment: extract from "--environment=X"

Implementation steps:
1. Read arguments: $ARGUMENTS
2. Split by space to get tokens
3. First token = version
4. If "--skip-tests" in tokens → skip = true
5. Find token starting with "--environment=" → extract value
6. Validate version matches semver: /^\d+\.\d+\.\d+$/
7. Validate environment is "staging" or "production"
8. Fail if validation fails

Execute release:
- npm version $version
- npm run build
- [if !skip-tests] npm test
- deploy to $environment
- create git tag

5.2 上下文动态加载

基于文件存在性加载上下文:

yaml 复制代码
---
name: test
---

## Context

# 条件加载:如果存在 jest 配置,加载它
Jest config: !`[ -f jest.config.js ] && cat jest.config.js || echo "No Jest config"`

# 根据项目类型加载不同上下文
Project type: !`[ -f package.json ] && echo "node" || [ -f pyproject.toml ] && echo "python" || echo "unknown"`

## Your task

Based on project type:
- If "node": run npm test
- If "python": run pytest
- Otherwise: error

5.3 错误处理模式

严格模式(任何错误停止):

markdown 复制代码
## Your task

1. Run tests: `npm test`
   - If exit code != 0: STOP and report

2. Build: `npm run build`
   - If exit code != 0: STOP and report

3. Deploy: `npm run deploy`
   - If exit code != 0: STOP and report

CRITICAL: If any step fails, stop immediately.

宽容模式(某些步骤可选):

markdown 复制代码
## Your task

1. Run linter: `npm run lint`
   - Exit code 0: Continue
   - Exit code != 0: Warn but continue

2. Run tests: `npm test`
   - Exit code 0: Continue
   - Exit code != 0: STOP (required)

3. Generate docs: `npm run docs`
   - Exit code != 0: Warn but continue (optional)

重试逻辑:

typescript 复制代码
## Your task

1. Attempt deploy: `npm run deploy`
   - If fails:
     - Wait 5 seconds
     - Retry: `npm run deploy`
     - If fails again:
       - Run: `npm run deploy:rollback`
       - STOP with error

5.4 与 Agent 协作

Command 中调用 Agent:

yaml 复制代码
---
name: review
---

## Your task

1. Launch code-reviewer agent for overall review
2. Launch security-auditor agent for security check
3. Wait for both agents to complete
4. Consolidate findings and present to user

Use Task tool:
- Task(subagent_type="code-reviewer", prompt="Review this code for quality issues")
- Task(subagent_type="security-auditor", prompt="Check for vulnerabilities")

优势: Command 提供框架,Agent 提供专业分析。


6. 实战案例

案例 1:代码质量检查 Command

yaml 复制代码
---
name: quality-check
description: Run comprehensive code quality checks
allowed-tools: Bash(npm:*), Bash(pnpm:*), Read, Glob
git:
  requireClean: false
---

## Context

Package manager: !`[ -f package-lock.json ] && echo "npm" || [ -f pnpm-lock.yaml ] && echo "pnpm" || echo "unknown"`
Node version: !`node --version`
ESLint config: !`[ -f .eslintrc.js ] && echo "present" || echo "missing"`
TypeScript config: !`[ -f tsconfig.json ] && echo "present" || echo "missing"`

## Your task

Run comprehensive quality checks:

### Phase 1: Environment Check

- Verify Node version >= 18.0.0
- Verify package manager lock file is present
- Results: PASS/FAIL

### Phase 2: Linting

- Run: `${PACKAGE_MANAGER} run lint`
- If no lint script: WARN and skip
- If fails: collect errors but continue

### Phase 3: Type Check

- If TypeScript config="present":
  - Run: `${PACKAGE_MANAGER} run type-check`
  - If fails: collect errors
- Else: SKIP

### Phase 4: Tests

- Run: `${PACKAGE_MANAGER} test -- --coverage`
- If no coverage: WARN
- Collect: coverage %

### Phase 5: Security Audit

- Run: `${PACKAGE_MANAGER} audit --audit-level=high`
- If vulnerabilities: WARN but continue

### Phase 6: Complexity

- Find all .ts/.js files
- Run complexity analysis
- Flag files with >20 cyclomatic complexity

## Report

Summarize:
- Total issues found
- Breakdown by category
- Files that need attention
- Recommendations

案例 2:发布版本 Command

yaml 复制代码
---
name: release-version
description: Release a new version (major|minor|patch)
allowed-tools: Bash(npm:*), Bash(pnpm:*), Bash(git:*), Bash(gh:*), Write, Edit, Read
git:
  requireClean: true
  branch: ["main", "release/*"]
---

## Context

Current version: !`cat package.json | grep \"version\" | head -1 | cut -d'\"' -f4`
Git status: !`git status --porcelain`
Current branch: !`git branch --show-current`
Latest tag: !`git describe --tags --abbrev=0 2>/dev/null || echo "none"`
Unreleased commits: !`git log $(git describe --tags --abbrev=0 2>/dev/null || echo "HEAD")..HEAD --oneline | wc -l`

## Parameters

Bump type: $ARGUMENTS
Valid values: major, minor, patch

## Validation

- FAIL if bump type missing
- FAIL if status != "clean"
- FAIL if branch not in allowed list
- FAIL if version not semver

## Your task

Release steps:

1. **Bump version**:
   - Read package.json
   - Increment version based on bump type
   - Write updated package.json

2. **Update changelog**:
   - Read CHANGELOG.md
   - Add new section for version
   - Insert commits since last tag

3. **Stage changes**:
   - git add package.json CHANGELOG.md

4. **Create commit**:
   - Message: "release: v{NEW_VERSION}"

5. **Create tag**:
   - git tag -a v{NEW_VERSION} -m "Release v{NEW_VERSION}"

6. **Push**:
   - git push && git push --tags

7. **Create GitHub release**:
   - gh release create v{NEW_VERSION} --notes-file CHANGELOG.md

8. **Report**:
   - Version: v{NEW_VERSION}
   - Commit: {HASH}
   - Tag: created
   - Release: URL

案例 3:快速原型 Command

yaml 复制代码
---
name: prototype
description: Quickly prototype a new feature
allowed-tools: Bash, Write, Glob, TodoWrite
---

## Your task

Create a quick prototype for: $ARGUMENTS

Constraints:
- Timebox: 30 minutes
- Focus: Proof-of-concept only
- Quality: Functional but not production-ready
- Documentation: Basic inline comments

Steps:

1. Understand requirements from "$ARGUMENTS"

2. Create minimal implementation:
   - Main functionality file
   - Basic demo/test
   - README with usage

3. Note limitations and next steps

4. Use TodoWrite to track progress

**Goal**: Show feasibility quickly, not build perfect solution.

7. 最佳实践

7.1 设计原则

原则 1:单一职责

错误: 多功能混杂

yaml 复制代码
name: deploy
# 包含:测试、构建、部署、通知、文档生成
# 问题:20+ 步骤,难以维护
description: Deploy with everything (test, build, deploy, notify, docs, ...)

正确: 功能分离

yaml 复制代码
# 拆分为多个 Commands
name: test        # 只运行测试
name: build       # 只构建
name: deploy      # 只部署
name: release     # 组合上述步骤
原则 2:失败快速(Fail Fast)

在开头验证所有前提条件:

yaml 复制代码
## Your task

### Prerequisites Check

- Verify git status is clean: !`git status --porcelain`
- Verify on correct branch: must be "main" or "staging"
- Verify all required tools available: npm, docker, etc.
- Verify environment variables set: API_KEY, DATABASE_URL

If any check fails, STOP with clear error message.

### Main Execution (only if all checks pass)
...
原则 3:上下文最小化

错误: 加载过多上下文

yaml 复制代码
## Context
n
# 加载 10+ 条信息,大多不需要
Git log: !`git log --all --oneline -100`
CI status: !`curl https://ci.example.com/status`
Test results: !`cat test-results/*.xml`
Dependencies: !`npm ls --depth=10`
...

正确: 按需加载

yaml 复制代码
## Context

Git status: !`git status --porcelain`  # 必需:检查干净工作区
Current branch: !`git branch --show-current`  # 必需:分支验证

Context 加载指南:

  • 只加载影响决策的信息

  • 5 条上下文 = 太多了

  • 如果不需要,不要加载

原则 4:明确授权

明确告诉 Claude 可以做什么:

yaml 复制代码
## Your task

You have the capability to call multiple tools in a single response.
Please combine related commands to minimize tool calls.

Example:
# ✅ 批量执行
- Bash: git add . && git commit -m "$MESSAGE" && git push

# ❌ 分开执行(慢)
- Bash: git add .
- Bash: git commit -m "$MESSAGE"
- Bash: git push
原则 5:清晰的错误消息

错误消息不明确:

typescript 复制代码
// Claude 生成
if (exitCode !== 0) {
  return { error: "Failed" };  // 用户不知道原因
}

明确错误消息:

typescript 复制代码
// 在 Command 中的指导
if tests fail:
  - Capture stderr
  - Parse error messages
  - Suggest: "Run npm test locally to debug"
  - Provide: "Check test-results/test.log for details"

7.2 命名规范

Command 名称

好的命名:

bash 复制代码
# 动词开头,清晰表达动作
/deploy-staging      # 部署到 staging
/create-component    # 创建组件
/lint-fix            # 修复 lint 错误
/test-coverage       # 测试覆盖率

# 使用连字符分隔
/release-patch       # ✅ 好
/releasePatch        # ❌ 差(驼峰)
/release_patch       # ❌ 差(下划线)

不好的命名:

bash 复制代码
/do                # 太泛
/process           # 不清楚做什么
/handle            # 动词模糊
/workflow          # 技术术语,不具体

命名格式:

复制代码
<action>-<target>[-<modifier>]

action: deploy, create, test, lint, review, setup
target: staging, component, coverage, fix, pr, project
modifier: optional (fast, full, quick)

Examples:
✅ deploy-staging
✅ create-component
✅ test-coverage
✅ lint-fix
✅ review-pr
✅ setup-project
参数命名

一致的参数风格:

bash 复制代码
# 布尔标志
/some-command --skip-tests --dry-run --verbose

# 键值对
/some-command --environment=staging --output=file.txt

7.3 性能优化

减少工具调用
bash 复制代码
# ❌ 低效:3 次调用
> Bash: git add .
> Bash: git commit -m "msg"
> Bash: git push

# ✅ 高效:1 次调用
> Bash: git add . && git commit -m "msg" && git push

性能对比:

  • 工具调用延迟: ~200-500ms/次
  • 网络延迟: ~50-100ms
  • 批处理节省: 30-60% 时间
并行执行
bash 复制代码
# ❌ 串行(6 秒)
> Bash: npm run lint       # 2s
> Bash: npm test           # 3s
> Bash: npm run build      # 1s
Total: 6s

# ✅ 并行(3 秒)
> Bash: npm run lint & npm test & npm run build
> Bash: wait  # 等待所有完成
Total: max(2s, 3s, 1s) = 3s

注意事项:

  • 依赖步骤不能并行
  • 使用 wait 等待所有完成
  • 检查所有退出码

7.4 测试策略

Command 测试方法
bash 复制代码
# 1. 单元测试:验证每个步骤
# test-deploy-staging.sh

test_checks_status_clean() {
  cd test-repo
  echo "test" > file.txt  # 创建未提交更改

  result=$(claude --non-interactive "/deploy-staging 2>&1")

  assert_contains "$result" "uncommitted changes"
  assert_contains "$result" "FAILED"
}

# 2. 集成测试:完整流程
# integration-test.sh

test_full_deployment() {
  cd test-repo

  # 设置干净状态
  git add . && git commit -m "test"

  # 运行部署
  result=$(claude --non-interactive --expect-exit-code 0 \
    "/deploy-staging --skip-tests")

  assert_contains "$result" "SUCCESS"
  assert_contains "$result" "Deployment URL:"
}

# 3. 模拟测试:使用模拟工具
# mock-test.sh

# 模拟 npm 命令
mkdir -p ./mock/bin
echo '#!/bin/bash\necho "Mock: npm $@"' > ./mock/bin/npm
chmod +x ./mock/bin/npm
export PATH="./mock/bin:$PATH"

# 测试(不会实际运行 npm)
claude "/deploy-staging"

7.5 文档规范

每个 Command 必须包含:

markdown 复制代码
---
name: command-name
description: Clear description of what the command does  # 必需
argument-hint: "<argument> -- description"              # 如果有参数
---

## Context

[Auto-loaded context commands]

## Your task

[Clear step-by-step instructions]

### Phase 1: [Name]

[具体步骤]

### Phase 2: [Name]

[具体步骤]

## Examples

```bash
/command arg1 arg2
/command --flag1 --option=value

Notes

  • Prerequisites

  • Limitations

  • Special cases

    7.6 版本管理

    yaml 复制代码
    ---
    name: deploy-staging
    version: "1.0.0"              # 版本号
    description: Deploy to staging
    changelog:                    # 变更记录
      "1.0.0": Initial version
      "1.1.0": Added health check
      "1.2.0": Added rollback on failure
    ---

版本号规范: SemVer

  • MAJOR: 破坏性变更(命令改名、参数变化)
  • MINOR: 新功能(添加步骤、新选项)
  • PATCH: Bug 修复(错误消息、小优化)

8. 故障排查

8.1 Command 无法触发

症状 : /my-command 显示 "Command not found"

排查步骤:

bash 复制代码
# 1. 检查文件位置
ls -la .claude-plugin/commands/my-command.md
# 应该存在且有读取权限

# 2. 检查 YAML Frontmatter
cat .claude-plugin/commands/my-command.md | head -10
# 必须有 name: 和 description:

# 3. 检查插件加载
claude --verbose
# 查看启动时是否加载了命令

# 4. 检查语法错误
cat .claude-plugin/commands/my-command.md
# 确保 YAML 格式正确(缩进、冒号)

# 5. 重启 Claude Code
# 配置变更需要重启
cd .claude-plugin && claude

常见问题:

问题 症状 解决方案
文件位置错误 命令未找到 放入 .claude-plugin/commands/
YAML 格式错误 解析失败 检查缩进,使用 : 而不是 =
缺少 name 字段 无法注册 添加 name: command-name
缺少 description 帮助不显示 添加 description: description
未重启 新命令未加载 重启 Claude Code

8.2 Command 执行失败

症状: Command 启动但中途失败

排查步骤:

bash 复制代码
# 1. 查看错误消息
# Claude Code 会显示哪一步失败

# 2. 手动执行上下文命令
git status  # 验证上下文命令是否成功
git branch --show-current

# 3. 检查工具权限
which git     # 确保 git 可用
which npm     # 确保 npm 可用

# 4. 检查参数解析
echo "$ARGUMENTS"  # 查看传递的参数

# 5. 启用 verbose 模式
claude --verbose
# 查看详细的工具调用

常见错误:

bash 复制代码
# 错误示例 1: 工具未授权
Error: Tool "Edit" not allowed
解决: 在 YAML 中添加 allowed-tools: Edit

# 错误示例 2: 命令未找到
bash: line 1: some-command: command not found
解决: 检查命令是否存在,或指定完整路径

# 错误示例 3: 参数解析失败
Invalid arguments"$ARGUMENTS"
解决: 在 Command 中添加参数解析逻辑

# 错误示例 4: 上下文命令失败
Context command failed: git status
解决: 进入正确的目录,确保有 Git 仓库

8.3 Context 命令未执行

症状: Context 信息未显示或显示错误

原因分析:

markdown 复制代码
// ❌ 错误的 Context 格式
## Context

Git status: !git status           # 缺少反引号
Branch: `git branch`              # 缺少 !

// ✅ 正确的格式
## Context

Git status: !`git status`         # ! + 反引号
Branch: !`git branch --show-current`

调试 Context:

bash 复制代码
# 手动执行 Context 命令
cd your-project

echo "Git status:"
git status

echo "Branch:"
git branch --show-current

# 如果成功,Claude Code 应该也能成功

8.4 Claude 不遵循指令

症状: Claude 不按照 Command 中的步骤执行

原因分析:

markdown 复制代码
// ❌ 不明确的指令
## Your task

Do some stuff with git.
Then deploy if possible.

// ✅ 明确的指令
## Your task

### 1. Check git status

Run: `git status`
If dirty: STOP with error

### 2. Run tests

Run: `npm test`
If fail: STOP with error

### 3. Deploy

Run: `npm run deploy`
Verify: Exit code 0
Success: Report URL

**CRITICAL**: If any step fails, stop immediately.

最佳实践:

  1. 使用编号步骤
  2. 明确每个工具的输入
  3. 指定成功/失败条件
  4. 使用 CRITICAL 标注关键要求

8.5 性能问题

症状: Command 执行缓慢(>30 秒)

优化建议:

bash 复制代码
# 1. 批处理工具调用
# ❌ 低效:多次调用
git add .
git commit
git push

# ✅ 高效:单次调用
git add . && git commit && git push

# 2. 减少不必要的 Context
# ❌ 加载不需要的信息
Context: !`git log --all --oneline -100`  # 100 条历史,可能不需要

# ✅ 只加载必要信息
Context: !`git log -1 --oneline`          # 只最后一条

# 3. 并行执行独立任务
# ❌ 串行
npm run lint    # 2s
npm test        # 5s
npm run build   # 10s
Total: 17s

# ✅ 并行
npm run lint & npm test & npm run build & wait
Total: 10s (以最长为准)

性能指标:

指标 优秀 一般
工具调用次数 < 5 5-10 > 10
执行时间 < 10s 10-30s > 30s
Context 命令 < 3 3-5 > 5

附录 A: 常用 Commands 示例库

A.1 Git 工作流

git-status:

yaml 复制代码
name: status
description: Show git status
git: {}
---

## Context

Status: !`git status`
Branch: !`git branch --show-current`
---

## Your task

Show git status information.

git-undo:

yaml 复制代码
name: undo
description: Undo last commit (keeps changes)
---

## Your task

1. Check HEAD is not at initial commit: !`git rev-parse HEAD`
2. Run: `git reset --soft HEAD~1`
3. Report: Previous commit undone, changes kept staged

A.2 代码质量

format-code:

yaml 复制代码
name: format-code
description: Format all code files
allowed-tools: Bash, Edit
---

## Context

Project files: !`find src -name "*.js" -o -name "*.ts"`

## Your task

1. Run: `npm run format` or `npx prettier --write src/`
2. Verify all files formatted
3. Report files changed

find-dead-code:

yaml 复制代码
name: find-dead-code
description: Find potentially unused code
---

## Your task

1. Search for "TODO", "FIXME", "XXX" in source
2. Find imports that are never used
3. Find functions that are never called
4. Report findings with file:line

A.3 开发效率

create-component:

yaml 复制代码
name: create-component
description: Create a React component with tests
git:
  requireClean: false
---

## Your task

Component name: $ARGUMENTS

Steps:
1. Create src/components/{ComponentName}.tsx
2. Create src/components/{ComponentName}.test.tsx
3. Create basic implementation
4. Create basic test
5. Export from index.ts

附录 B: 最佳实践清单

创建 Command 时检查列表:

  • 命名 : name 清晰,使用连字符,动词开头
  • 描述 : description 简洁,说明用途
  • 上下文: 只加载必要信息,< 5 条命令
  • 步骤: 明确编号,每个步骤有验证
  • 工具授权 : allowed-tools 包含所有需要的工具
  • 错误处理: 失败条件有处理,错误消息清晰
  • 参数: 如果有参数,说明格式和选项
  • 示例: 提供 1-2 个使用示例
  • CRITICAL : 重要要求用 CRITICAL 标注
  • 测试: 手动测试通过
  • 文档: 说明局限性和注意事项

附录 C: 故障排查速查表

症状 可能原因 解决方案
"Command not found" 文件不存在或不在正确位置 检查 .claude-plugin/commands/
"YAML parse error" Frontmatter 格式错误 检查缩进和冒号
"Tool not allowed" 未声明 allowed-tools 添加 allowed-tools: Bash, Edit
"Context command failed" 上下文命令执行失败 手动执行命令验证
"Nothing happens" 缺少任务指令 添加 ## Your task
相关推荐
NocoBase2 小时前
GitHub 上星星数量前 10 的 AI CRM 开源项目
人工智能·低代码·开源·github·无代码
小陈phd2 小时前
大语言模型实战(二)——Transformer网络架构解读
人工智能·深度学习·transformer
鲨莎分不晴2 小时前
读心术:对手建模与心智理论 (Agent Modeling & Theory of Mind)
人工智能·机器学习
LiYingL2 小时前
Pref-GRPO:通过成对比较实现稳定文本图像生成强化学习的新方法
人工智能
Felaim2 小时前
[自动驾驶] 小鹏 FutureX 要点总结(小鹏)
人工智能·机器学习·自动驾驶
傅科摆 _ py2 小时前
PCA 降维技术概览
人工智能
EasyCVR2 小时前
视频汇聚平台EasyCVR筑牢消防领域可视化监控防线
运维·人工智能·音视频
飞哥数智坊2 小时前
AI帮我搭猫窝:一场空间推理能力的实战测评
人工智能
Robot侠2 小时前
ROS1从入门到精通 9: TF坐标变换(机器人的空间认知)
人工智能·机器人·ros·机器人操作系统·tf坐标变换