Files
knowledge-base/4 - Resources/Everything Claude Code 方法论与最佳实践.md
Yaojia Wang d62e5ee37f vault: add detailed examples to ECC methodology note
Added: hooks.json config example, strategic compaction good/bad comparison,
Hookify dialog example, sandboxed subagent YAML, Cascade multi-instance
workflow, tmux/worktree orchestration with plan JSON, AgentShield scan
output, dual-instance project setup, bugfix workflow, security audit
workflow, and refactor workflow with concrete code samples.
2026-03-19 23:23:51 +01:00

20 KiB
Raw Blame History

created, type, tags, source
created type tags source
2026-03-19 12:00 resource
claude-code
AI-tools
methodology
best-practices
agent-orchestration
https://github.com/affaan-m/everything-claude-code

Everything Claude Code 方法论与最佳实践

深度分析 ECC 的六大核心方法论、社区最佳实践、常见陷阱与实战例子。组件列表见 Everything Claude Code 完整指南,按场景速查见 Everything Claude Code 用法速查


一、六大核心方法论

1. Research-First Development研究优先开发

在写任何代码之前,必须搜索现有实现。这是 ECC 工作流的步骤 0强制

流程:
1. gh search repos / gh search code → 搜索 GitHub 现有实现
2. 搜索包注册表npm, PyPI, crates.io→ 优先用成熟库
3. Web 搜索 → 发现先例和最佳实践
4. 如果找到 80%+ 匹配的开源项目 → Fork/移植,不要从零写

例子 — JWT 验证中间件:

# 先搜索,不要直接写
gh search code "jwt middleware verify" --language=typescript
# 找到 jose 库 → 直接用,而不是手写 crypto
npm search jwt verify

2. Agent OrchestrationAgent 编排)

将复杂任务分解给专业 Agent支持串行链和并行执行。

四种预设工作流:

工作流 Agent 链
feature planner → tdd-guide → code-reviewer → security-reviewer
bugfix planner → tdd-guide → code-reviewer
refactor architect → code-reviewer → tdd-guide
security security-reviewer → code-reviewer → architect

自定义链: /orchestrate custom "architect,tdd-guide,code-reviewer" "Redesign caching layer"

Agent 间交接文档格式:

## Handoff: planner → tdd-guide
### Context
- 实现 OAuth2 登录流程,使用 passport.js + Google provider
### Findings
- 需要新建 3 个文件: auth.controller, auth.service, auth.guard
### Files Modified
- (none yet - planning phase)
### Open Questions
- 是否需要 refresh token 支持?
### Recommendations
- 先写 auth.service 的单元测试

3. Hook-Driven EnforcementHook 驱动的强制执行)

核心洞察: Hook 触发率 100%确定性Skill/提示词触发率仅 50-80%(概率性)。因此关键质量控制应通过 Hook 实现,而非依赖提示词。

Hook 类型 触发时机 用途举例
PreToolUse 工具执行前 开发服务器自启、安全监控
PostToolUse 工具执行后 自动格式化、类型检查
PreCompact 上下文压缩前 保存会话状态到 MEMORY.md
SessionStart 新会话开始 加载上次上下文、检测包管理器
Stop 每次响应后 检查 debug 语句、持久化指标

例子 — hooks.json 配置:

{
  "PostToolUse": [
    {
      "matcher": "Write|Edit",
      "command": "prettier --write $FILEPATH && eslint --fix $FILEPATH",
      "description": "每次文件编辑后自动格式化和 lint"
    },
    {
      "matcher": "Write|Edit",
      "command": "npx tsc --noEmit $FILEPATH 2>&1 | head -20",
      "description": "每次文件编辑后自动类型检查"
    }
  ],
  "PreToolUse": [
    {
      "matcher": "Bash",
      "command": "node hooks/dev-server-check.js",
      "description": "执行 bash 命令前确保开发服务器在 tmux 中运行"
    }
  ],
  "PreCompact": [
    {
      "command": "node hooks/save-session-state.js",
      "description": "上下文压缩前自动保存会话状态到 MEMORY.md"
    }
  ],
  "Stop": [
    {
      "command": "grep -rn 'console.log\\|debugger' src/ --include='*.ts' | head -5",
      "description": "每次响应后检查是否遗留了 debug 语句"
    }
  ]
}

运行时控制(无需编辑文件):

export ECC_HOOK_PROFILE=minimal    # 最小化(减少开销)
export ECC_HOOK_PROFILE=standard   # 标准
export ECC_HOOK_PROFILE=strict     # 严格(全部启用)
export ECC_DISABLED_HOOKS=security-monitor,learning-observer  # 禁用特定 hook

4. Continuous Learning持续学习系统v2.1

ECC 最独特的创新 — 本能学习系统

观察(Hook) → 检测模式(Haiku) → 形成本能(Instinct) → 演化为技能(Skill)

工作流程:

  1. Hook 捕获每次工具调用到 observations.jsonl
  2. Haiku 模型后台观察器检测模式
  3. 模式成为"本能"— 原子化学习行为,带信心分数 (0.3-0.9)
  4. 本能按项目隔离git remote URL hash防止跨项目污染
  5. /evolve 将相关本能聚类为新的 skill/command/agent
  6. 信心 >= 0.8 且在 2+ 项目中出现 → 从项目级提升到全局级

例子:

# 会话结束后提取模式
/learn
# → [Instinct] confidence=0.7 scope=project
# → "When editing React components, always check for missing useCallback"

# 多次确认后
/evolve
# → 自动生成新 skill: react-performance-patterns

5. Strategic Compaction策略性压缩

问题: 自动压缩在 ~83.5% 上下文使用率时随机触发,可能丢失关键上下文。

解决方案: 在逻辑工作节点手动触发 /compact

推荐压缩时机:
├── 探索阶段完成后
├── 里程碑完成后
├── 切换任务类型时(调试 → 开发)
└── 工具调用次数达到阈值时Hook 自动提醒)

例子 — 好的 vs 坏的压缩时机:

# 坏: 在重构中途自动压缩,丢失函数签名和依赖关系上下文
# ❌ Auto-compact at 167K tokens mid-refactor
#    → 压缩后 Claude 忘记了之前分析的接口签名
#    → 重新读取 5 个文件,浪费 ~20K tokens

# 好: 在完成一个模块后手动压缩
# Phase 1: Auth module complete ✓
#   → 所有测试通过,代码已提交
/compact
# Phase 2: Start payment module (clean context)
#   → 只需加载 payment 相关文件,不需要 auth 的上下文

# 好: 从调试切到开发时压缩
# Debug session: found root cause → fixed → committed
/compact
# Feature development: start new feature (清除调试噪音)

禁用自动压缩的配置:

{
  "env": {
    "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "50"
  }
}

6. Verification Loop验证循环

6 阶段质量门,建议每 15 分钟或每次重大变更后执行:

/verify → 6 阶段:
1. Build     → 编译是否通过
2. Types     → 类型检查
3. Lint      → 代码规范
4. Tests     → 测试通过 + 覆盖率 >= 80%
5. Security  → 安全扫描
6. Diff      → 变更审查
→ 输出: 结构化 PASS/FAIL 报告

二、社区最佳实践

渐进式采用路线

阶段 重点 内容
第1周 基础 Rules + 基本 Commands (/plan, /tdd)
第2周 管理 Session logging + Memory + Strategic compact
第3周 高级 Agents + Custom skills + Verification loops
第4周 优化 Token optimization + 并行执行
持续 积累 /learn 提取模式,构建项目专用 Agent

Token/成本优化

// settings.json 推荐配置
{
  "model": "sonnet",
  "env": {
    "MAX_THINKING_TOKENS": "10000",
    "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "50"
  }
}
// → ~60% 成本降低 (Sonnet vs Opus)
// → ~70% thinking 成本降低

模型选择策略:

模型 场景 能力/成本比
Haiku 简单任务、频繁调用的轻量 Agent 90% 能力3x 省钱
Sonnet 90% 的日常编码工作 最佳性价比
Opus 架构决策、首次失败重试、5+ 文件跨度 最强推理

MCP 管理

  • 启用的 MCP <= 10 个,活跃工具总数 <= 80 个
  • 10+ MCP 时,有效上下文从 200K 降至 ~70K tokens
  • disabledMcpServers 禁用不用的
  • 重操作优先用 CLIgh)而不是 MCP
  • 使用 llms.txt 模式(如 vercel.com/docs/llms.txt)代替 MCP 获取文档

会话管理

  • 命名会话,特别是使用 git worktree 并行工作时
  • 保存会话状态到 .tmp 文件
  • 同一问题纠正 Claude 超过 2 次 → 开新会话(失败方法污染上下文)
  • 新项目用双实例模式:实例 1 做脚手架,实例 2 做研究,合并后实施

三、常见陷阱

陷阱 影响 解决方案
同时启用所有 MCP 上下文降至 ~70K 保持 <= 10 个
跳过 Plan 阶段 需求不清,大量返工 始终先 /plan
过多并行实例 心智负担 > 生产力 按需添加
文件超 500 行 重读消耗大量 Token 拆分为小文件
不提取可复用模式 每次重复设置 /learn 固化
忽略上下文健康 模型性能下降、幻觉 监控使用率,里程碑处压缩
死代码累积 Token 浪费 定期用 refactor-cleaner
忽略 Agent 质量门 遗漏回归和安全问题 让 Agent 触发运行

四、ECC 独特创新

创新 说明
Hookify 对话式 Hook 创建 — 描述需求自动生成 Hook 配置
pass@k / pass^k 形式化验证 Agent 任务成功率的度量
Sandboxed Subagents 按 Agent 限制工具planner 只读tdd-guide 可写代码+测试)
Cascade Method 多实例管理用于并行开发
AgentShield 安全审计1282 测试98% 覆盖率14 种密钥模式检测)
Plankton 写入时代码质量工具20+ linter + Claude 子进程修复)
NanoClaw v2 模型路由、技能热加载、会话分支/搜索/导出
Continuous Learning v2.1 Hook 观察 → 模式检测 → 本能形成 → 技能演化

各创新功能详细例子

Hookify — 对话式创建 Hook:

用户: "每次我编辑 .py 文件后自动运行 black 格式化"

# Hookify 自动生成:
{
  "PostToolUse": [{
    "matcher": "Write|Edit",
    "command": "if [[ \"$FILEPATH\" == *.py ]]; then black \"$FILEPATH\"; fi",
    "description": "Auto-format Python files with black"
  }]
}
# → 写入 hooks/hooks.json立即生效

Sandboxed Subagents — 工具限制:

# agents/planner.md frontmatter
---
name: planner
model: opus
tools: [Read, Glob, Grep, WebSearch, WebFetch]  # 只读,不能写代码
---

# agents/tdd-guide.md frontmatter
---
name: tdd-guide
model: sonnet
tools: [Read, Write, Edit, Bash, Glob, Grep]  # 可以写代码和运行测试
---

# agents/security-reviewer.md frontmatter
---
name: security-reviewer
tools: [Read, Grep, Glob, Bash]  # 可以读和扫描,不能修改
---

Cascade Method — 多实例并行开发:

# 实例 1: 主开发feature branch
claude --session "auth-feature" --worktree feature/auth
# → 在独立 worktree 中开发 auth 模块

# 实例 2: 并行研究
claude --session "auth-research"
# → 研究 OAuth2 最佳实践、比较库
# → 输出研究报告到 .tmp 文件

# 实例 3: 并行测试基础设施
claude --session "test-infra" --worktree feature/test-setup
# → 搭建测试环境、mock 服务器

# 合并时:
# 实例 1 读取实例 2 的研究结果
# 实例 1 合并实例 3 的测试基础设施

Tmux/Worktree 编排:

// orchestration-plan.json
{
  "workers": [
    {
      "name": "api-worker",
      "branch": "feature/api-endpoints",
      "task": "Implement REST API endpoints for user CRUD",
      "seedPaths": ["src/types/", "src/config/"]
    },
    {
      "name": "db-worker",
      "branch": "feature/db-schema",
      "task": "Create database migrations and repository layer",
      "seedPaths": ["src/types/", "prisma/"]
    },
    {
      "name": "test-worker",
      "branch": "feature/e2e-tests",
      "task": "Write E2E tests for user flows",
      "seedPaths": ["src/types/", "tests/fixtures/"]
    }
  ]
}
# 启动编排
node scripts/orchestrate-worktrees.js orchestration-plan.json
# → 创建 3 个 git worktree
# → 每个在独立 tmux pane 中运行 Claude
# → seedPaths 从主分支复制共享文件到各 worktree

# 查看状态
node scripts/orchestration-status.js
# → api-worker: 3/5 tasks done, branch: feature/api-endpoints
# → db-worker: 5/5 tasks done ✓, branch: feature/db-schema
# → test-worker: 2/4 tasks done, branch: feature/e2e-tests

AgentShield — 安全扫描:

npx ecc-agentshield scan ~/.claude/

# 输出:
# ┌─────────────────────────────────────┐
# │ AgentShield Security Report         │
# │ Grade: B (82/100)                   │
# ├─────────────────────────────────────┤
# │ CRITICAL (0)                        │
# │ HIGH (1)                            │
# │   → settings.json: acceptEdits      │
# │     without scope restriction       │
# │ MEDIUM (3)                          │
# │   → CLAUDE.md: no input validation  │
# │     guidance for MCP tool results   │
# │   → hooks/: PreToolUse hook runs    │
# │     arbitrary shell without sandbox │
# │   → agents/: planner agent has      │
# │     Write tool (should be read-only)│
# │ LOW (2)                             │
# │   → 2 MCP servers without auth      │
# │ SECRET PATTERNS: 0 found            │
# └─────────────────────────────────────┘

双实例模式 — 新项目启动:

# 实例 1: 脚手架
claude --session "scaffold"
> /plan "Create a Next.js 15 app with auth, payments, and admin panel"
> # → 生成项目结构、配置文件、基础路由
> # → 提交到 main 分支

# 实例 2: 研究(同时进行)
claude --session "research"
> "Research: Next.js 15 app router best practices for auth"
> "Research: Stripe integration patterns for Next.js"
> "Research: Admin panel libraries compatible with Next.js 15"
> # → 输出研究笔记到 .claude/research/

# 合并洞察:
# 回到实例 1读取研究结果
> "Read .claude/research/ and apply findings to current scaffold"
> # → 根据研究结果调整架构决策

五、实战完整例子

例子: 从零开发 REST API 端点

# Step 0: Research研究优先
/search-first "express rate limiting middleware"
→ 发现 express-rate-limit 库 (26K stars, 维护活跃)

# Step 1: Plan规划
/plan "Add POST /api/users endpoint with validation and rate limiting"
→ planner agent (Opus):
  - 架构: Controller → Service → Repository 分层
  - 依赖: express-rate-limit, zod, bcrypt
  - 风险: 并发注册的竞态条件
→ 等待用户确认

# Step 2: TDD测试驱动
/tdd
→ tdd-guide agent:
  - users.controller.test.ts (RED → GREEN)
  - users.service.test.ts (RED → GREEN)
  - users.repository.test.ts (RED → GREEN)
→ 覆盖率 82% ✓

# Step 3: Review代码审查自动触发
→ code-reviewer agent:
  - CRITICAL: 无
  - HIGH: "bcrypt rounds should be configurable" → 修复
  - MEDIUM: "Consider adding request ID" → 记录

# Step 4: Security安全检查自动触发
→ security-reviewer agent:
  - ✓ 参数化查询、输入验证、速率限制
  - ⚠ "Add helmet middleware" → 修复

# Step 5: Verify验证循环
/verify → Build ✓ | Types ✓ | Lint ✓ | Tests ✓ (82%) | Security ✓ | Diff ✓

# Step 6: Learn提取模式
/learn
→ [Instinct] "Express API 端点始终加: rate limiting + zod + helmet"
→ confidence=0.6, scope=project

例子: Bug 修复工作流

# 用户报告: "登录后偶尔跳转到 404 页面"

# Step 1: 研究(自动触发 planner
/orchestrate bugfix "Login redirect sometimes lands on 404"

# → planner agent 分析:
#   - 可能原因: race condition in auth callback
#   - 相关文件: auth.callback.ts, router.middleware.ts
#   - 重现条件: 快速连续点击登录按钮

# Step 2: TDD先写复现测试
# → tdd-guide agent:
describe('Auth callback race condition', () => {
  it('should not redirect to 404 when callback fires twice', async () => {
    // 模拟快速连续两次 callback
    const result1 = authCallback(mockReq, mockRes);
    const result2 = authCallback(mockReq, mockRes);
    await Promise.all([result1, result2]);
    expect(mockRes.redirect).toHaveBeenCalledWith('/dashboard');
    expect(mockRes.redirect).not.toHaveBeenCalledWith('/404');
  });
});
# → 测试 RED ✓ (确认 bug 存在)

# Step 3: 修复
# → 添加 idempotency guard:
#   if (session.redirectHandled) return;
#   session.redirectHandled = true;
# → 测试 GREEN ✓

# Step 4: Review
# → code-reviewer agent:
#   - 确认修复正确
#   - 建议: "Add comment explaining the race condition for future maintainers"

例子: 安全审计工作流

# 代码审计请求
/orchestrate security "Audit payment processing module"

# → security-reviewer agent 扫描:
# ┌────────────────────────────────────────────┐
# │ Security Audit: src/payments/              │
# ├────────────────────────────────────────────┤
# │ CRITICAL (1):                              │
# │   payment.service.ts:45                    │
# │   → Stripe secret key in string literal    │
# │   → FIX: Move to env var STRIPE_SECRET_KEY │
# │                                            │
# │ HIGH (2):                                  │
# │   webhook.controller.ts:12                 │
# │   → Missing Stripe signature verification  │
# │   → FIX: Add stripe.webhooks.construct()   │
# │                                            │
# │   refund.service.ts:78                     │
# │   → No rate limiting on refund endpoint    │
# │   → FIX: Add express-rate-limit (5/min)    │
# │                                            │
# │ MEDIUM (3):                                │
# │   → Amount not validated as positive int   │
# │   → Error messages expose internal IDs     │
# │   → Missing audit log for payment actions  │
# └────────────────────────────────────────────┘

# → code-reviewer agent 确认修复:
#   - CRITICAL: Stripe key moved to .env ✓
#   - HIGH: Webhook signature verification added ✓
#   - HIGH: Rate limiting configured ✓

# → architect agent 建议:
#   - "Consider adding idempotency keys for payment requests"
#   - "Add circuit breaker for Stripe API calls"

例子: 重构工作流

/orchestrate refactor "Split monolithic UserService into domain services"

# → architect agent 分析:
# UserService (1200 lines) 应拆分为:
#   - AuthService (认证/授权, ~200 lines)
#   - ProfileService (用户资料, ~150 lines)
#   - NotificationService (通知偏好, ~100 lines)
#   - SubscriptionService (订阅管理, ~180 lines)
# 依赖图:
#   AuthService ← ProfileService
#   NotificationService ← SubscriptionService
#   (无循环依赖 ✓)

# → code-reviewer agent 审查拆分:
#   - 接口一致性 ✓
#   - 依赖注入正确 ✓
#   - 无遗漏的 public method ✓

# → tdd-guide agent 验证:
#   - 原有 45 个测试全部通过 ✓
#   - 新增 12 个测试覆盖拆分后的交互 ✓
#   - 覆盖率: 原 78% → 现 85% ✓

六、与其他方案对比

维度 ECC 最小 CLAUDE.md claude-code-ultimate-guide 自建配置
定位 生产级框架 轻量约定 教学材料 定制化
复杂度 可控
Token 开销 较大 最小 可控
学习曲线 陡峭 平缓 教程式 渐进
自动化 全面Hook 驱动) 手动 按需
学习系统 完整本能系统 无/部分
适用场景 重度日常使用 简单项目 入门学习 特定需求

七、关键数据

  • GitHub Stars: 50K+9天内达 31.9K
  • 社区评分: 5/5 CRITICALclaude-code-ultimate-guide 评价)
  • 作者实战: 10+ 个月日常高强度使用
  • 跨平台: Claude Code, Cursor, Codex, OpenCode
  • 许可: MIT