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.
This commit is contained in:
Yaojia Wang
2026-03-19 23:23:51 +01:00
parent 872401be72
commit d62e5ee37f

View File

@@ -77,6 +77,44 @@ npm search jwt verify
| SessionStart | 新会话开始 | 加载上次上下文、检测包管理器 |
| Stop | 每次响应后 | 检查 debug 语句、持久化指标 |
**例子 — hooks.json 配置**:
```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 语句"
}
]
}
```
**运行时控制**(无需编辑文件):
```bash
@@ -130,6 +168,27 @@ ECC 最独特的创新 — **本能学习系统**。
└── 工具调用次数达到阈值时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 (清除调试噪音)
```
禁用自动压缩的配置:
```json
@@ -237,6 +296,160 @@ ECC 最独特的创新 — **本能学习系统**。
| **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 — 工具限制**:
```yaml
# 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 — 多实例并行开发**:
```bash
# 实例 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 编排**:
```json
// 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/"]
}
]
}
```
```bash
# 启动编排
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 — 安全扫描**:
```bash
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"
> # → 根据研究结果调整架构决策
```
---
## 五、实战完整例子
@@ -284,6 +497,112 @@ ECC 最独特的创新 — **本能学习系统**。
→ 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% ✓
```
---
## 六、与其他方案对比