diff --git a/4 - Resources/Claude-Code/Autonomous Loops 自主循环模式.md b/4 - Resources/Claude-Code/Autonomous Loops 自主循环模式.md new file mode 100644 index 0000000..7b9b88d --- /dev/null +++ b/4 - Resources/Claude-Code/Autonomous Loops 自主循环模式.md @@ -0,0 +1,400 @@ +--- +created: "2026-04-06" +type: resource +tags: [resource, claude-code, AI-tools, autonomous-loops, agent-orchestration, ECC] +source: "~/.claude/skills/autonomous-loops/SKILL.md" +--- + +# Autonomous Loops 自主循环模式 + +ECC 提供的让 Claude Code 在无人干预下持续循环工作的模式集合。v1.10.0 中 `autonomous-loops` 已标记为兼容保留,新的 canonical 名称是 `continuous-agent-loop`。 + +相关笔记:[[dmux 多Agent并行编排]]、[[Everything Claude Code 完整指南]]、[[Ralphinho RFC-DAG 编排模式]] + +## 模式选择流程 + +``` +单个聚焦的改动? +├─ 是 -> Sequential Pipeline +└─ 否 -> 有写好的 spec/RFC? + ├─ 是 -> 需要并行实现? + │ ├─ 是 -> Ralphinho (DAG) + │ └─ 否 -> Continuous PR Loop + └─ 否 -> 需要同一事物的多个变体? + ├─ 是 -> Infinite Agentic Loop + └─ 否 -> Sequential + De-Sloppify +``` + +## 模式总览 + +| 模式 | 复杂度 | 适用场景 | 上下文管理 | +|------|--------|---------|-----------| +| Sequential Pipeline | 低 | 单功能开发、日常 bugfix | 每步全新上下文,靠文件系统传递 | +| NanoClaw REPL | 低 | 交互式探索、持久会话 | Markdown 文件累积历史 | +| Infinite Agentic Loop | 中 | 批量内容生成、多变体 | Orchestrator 分配方向 | +| Continuous PR Loop | 中 | 多天迭代、提升覆盖率 | SHARED_TASK_NOTES.md 桥接 | +| De-Sloppify | 附加 | 任何实现步骤后的清理 | 独立清理 agent | +| Ralphinho RFC-DAG | 高 | 大型功能、多 unit 并行 | DAG 依赖 + 合并队列 | + +--- + +## 模式 1: Sequential Pipeline + +最简单最实用。把开发拆成多个 `claude -p` 非交互调用,串行执行。 + +### 核心原理 + +- 每次 `claude -p` 是全新上下文,无前一步记忆 +- 靠文件系统状态在步骤间传递信息 +- `set -e` 任何步骤失败就停止 + +### 基本模板 + +```bash +#!/bin/bash +set -e + +# 实现 +claude -p "Read the spec in docs/spec.md. Implement the feature. Write tests first (TDD)." + +# 清理 (De-Sloppify) +claude -p "Review all changes. Remove unnecessary tests and defensive checks. Run tests." + +# 验证 +claude -p "Run full build, lint, test suite. Fix any failures. Do not add new features." + +# 提交 +claude -p "Create a conventional commit for all staged changes." +``` + +### 进阶技巧 + +**按复杂度选模型:** +```bash +claude -p --model haiku "Fix import ordering in src/utils.ts" # 简单 +claude -p --model sonnet "Implement caching layer" # 中等 +claude -p --model opus "Refactor auth module to strategy pattern" # 复杂 +``` + +**限制工具权限:** +```bash +claude -p --allowedTools "Read,Grep,Glob" "Audit for security..." # 只读分析 +claude -p --allowedTools "Read,Write,Edit,Bash" "Implement fixes..." # 可写实现 +``` + +**通过文件传递上下文:** +```bash +echo "Focus: auth module, API rate limiting" > .claude-context.md +claude -p "Read .claude-context.md for priorities. Work through them." +rm .claude-context.md +``` + +### 实际例子:smart-support 加反馈评分功能 + +```bash +#!/bin/bash +set -e + +# Step 1: 规划 +claude -p "Read docs/DEVELOPMENT-PLAN.md and docs/ARCHITECTURE.md. +Plan a user feedback rating feature: +- Backend: POST /api/feedback, store in PostgreSQL +- Frontend: thumbs up/down on AI reply +- Analytics: feedback stats query +Write plan to docs/phases/feedback-plan.md" + +# Step 2: 后端 TDD +claude -p "Read docs/phases/feedback-plan.md. +Create backend/app/feedback/models.py and router.py. +Write tests FIRST in backend/tests/unit/test_feedback.py. +Follow patterns from backend/app/analytics/. +Run pytest --cov=app." + +# Step 3: 前端 +claude -p "Read docs/phases/feedback-plan.md. +Create FeedbackButton component. Wire into chat message. +Call POST /api/feedback on click." + +# Step 4: 清理 +claude -p "Review git diff. Remove test slop, console.log, commented code. +Run pytest --cov=app." + +# Step 5: 验证 + 提交 +claude -p "Run pytest --cov=app --cov-report=term-missing. Fix failures." +claude -p "Stage feedback-related files. Commit: feat: add user feedback rating" +``` + +--- + +## 模式 2: NanoClaw REPL + +ECC 内置的持久会话 REPL,对话历史存储为 Markdown。 + +### 启动 + +```bash +node ~/.claude/scripts/claw.js + +# 带名称和技能 +CLAW_SESSION=my-project CLAW_SKILLS=tdd-workflow,security-review node ~/.claude/scripts/claw.js +``` + +### 内置命令 + +| 命令 | 功能 | +|------|------| +| `/model` | 切换模型 | +| `/load` | 动态加载 skill | +| `/branch` | 会话分支 | +| `/search` | 跨会话搜索 | +| `/compact` | 压缩历史 | +| `/export` | 导出为 md/json/txt | +| `/metrics` | 会话指标 | + +### vs Sequential Pipeline + +| | NanoClaw | Sequential Pipeline | +|---|---|---| +| 交互式 | 是 | 否 | +| 上下文累积 | 每轮增长 | 每步全新 | +| 会话持久化 | 内置 | 手动 | +| CI/CD 集成 | 差 | 好 | +| 适合 | 探索性工作 | 脚本自动化 | + +--- + +## 模式 3: Infinite Agentic Loop + +按 spec 批量并行生成多个变体。Orchestrator 读 spec,分配不同创意方向给 N 个子 agent。 + +### 原理 + +1. Orchestrator 读取 specification 文件 +2. 扫描 output 目录找到最高迭代号 +3. 并行启动 N 个子 agent,每个分配不同的创意方向和迭代号 +4. infinite 模式下以 3-5 个为一波持续生成 + +### 设置 + +创建 `.claude/commands/infinite.md`: + +```markdown +Parse the following arguments from $ARGUMENTS: +1. spec_file -- path to the specification markdown +2. output_dir -- where iterations are saved +3. count -- integer 1-N or "infinite" + +PHASE 1: Read and deeply understand the specification. +PHASE 2: List output_dir, find highest iteration number. Start at N+1. +PHASE 3: Plan creative directions -- each agent gets a DIFFERENT theme. +PHASE 4: Deploy sub-agents in parallel (Task tool). +PHASE 5 (infinite mode): Loop in waves of 3-5 until context is low. +``` + +### 调用 + +```bash +/project:infinite specs/component-spec.md src/ 5 # 生成5个 +/project:infinite specs/component-spec.md src/ infinite # 持续生成 +``` + +### 批次策略 + +| 数量 | 策略 | +|------|------| +| 1-5 | 全部同时 | +| 6-20 | 每批5个 | +| infinite | 每波3-5个,逐步提升复杂度 | + +### 关键:通过分配确保唯一性 + +不要依赖 agent 自行区分。Orchestrator 显式分配每个 agent 的创意方向和迭代号,避免重复。 + +--- + +## 模式 4: Continuous PR Loop + +生产级自动 PR 循环:建分支 -> 实现 -> 建 PR -> 等 CI -> 合并 -> 循环。 + +### 循环流程 + +``` +1. Create branch (continuous-claude/iteration-N) +2. Run claude -p with enhanced prompt +3. (Optional) Reviewer pass +4. Commit changes +5. Push + create PR (gh pr create) +6. Wait for CI checks (poll gh pr checks) +7. CI failure? -> Auto-fix pass +8. Merge PR +9. Return to main -> repeat +``` + +### 使用 + +```bash +# 基本:10轮迭代 +continuous-claude --prompt "Add unit tests for untested functions" --max-runs 10 + +# 限制花费 +continuous-claude --prompt "Fix all linter errors" --max-cost 5.00 + +# 限制时间 +continuous-claude --prompt "Improve test coverage" --max-duration 8h + +# 带 review pass +continuous-claude \ + --prompt "Add authentication feature" \ + --max-runs 10 \ + --review-prompt "Run npm test && npm run lint, fix any failures" + +# 并行 (worktree 隔离) +continuous-claude --prompt "Add tests" --worktree tests-worker & +continuous-claude --prompt "Refactor" --worktree refactor-worker & +wait +``` + +### 跨迭代上下文:SHARED_TASK_NOTES.md + +每轮开始读、结束写,桥接 `claude -p` 的无记忆问题: + +```markdown +## Progress +- [x] app/feedback/ - 65% -> 92% (iteration 1) +- [x] app/graph.py - 70% -> 88% (iteration 2) +- [ ] app/openapi/ - 68% (next target) + +## Overall: 82% -> 91% +``` + +### CI 失败自动恢复 + +自动 `gh run view` 查日志 -> 修代码 -> 推送 -> 重新等 CI(最多 `--ci-retry-max` 次)。 + +### 完成信号 + +```bash +continuous-claude \ + --prompt "Fix all bugs" \ + --completion-signal "CONTINUOUS_CLAUDE_PROJECT_COMPLETE" \ + --completion-threshold 3 # 连续3轮"完成"才停 +``` + +### 关键配置 + +| Flag | 功能 | +|------|------| +| `--max-runs N` | 最多 N 轮 | +| `--max-cost $X` | 花费上限 | +| `--max-duration 2h` | 时间上限 | +| `--merge-strategy squash` | squash/merge/rebase | +| `--worktree ` | 并行用 worktree | +| `--disable-commits` | 干跑模式 | +| `--review-prompt "..."` | 每轮加 review | +| `--ci-retry-max N` | CI 失败自动修复次数 | + +### 实际例子:提升 smart-support 测试覆盖率 + +```bash +continuous-claude \ + --prompt "Read backend/tests/ and find modules with lowest coverage. + Write unit tests for the least-covered module. + Use pytest patterns from conftest.py. + Run pytest --cov=app --cov-report=term-missing. + Update SHARED_TASK_NOTES.md with progress." \ + --max-runs 8 \ + --max-cost 10.00 \ + --review-prompt "Run pytest --cov=app. If coverage < 95%, note gaps." \ + --completion-signal "COVERAGE_TARGET_MET" \ + --completion-threshold 2 +``` + +--- + +## 模式 5: De-Sloppify (附加清理 Pass) + +不是独立模式,而是加在任何实现步骤后的清理。 + +### 问题 + +LLM 做 TDD 时过度测试:测类型系统能不能工作、加不必要的防御性检查。 + +### 错误做法 + +在提示里说"不要测类型系统" -> 模型变畏首畏尾,跳过正常测试。 + +### 正确做法 + +让实现步骤自由发挥,然后加独立清理 agent: + +```bash +for feature in "${features[@]}"; do + claude -p "Implement $feature with TDD." + claude -p "Cleanup: remove test/code slop, run tests." + claude -p "Run build + lint + tests. Fix failures." + claude -p "Commit: feat: add $feature" +done +``` + +> 核心洞察:两个专注的 agent 优于一个受约束的 agent。 + +--- + +## ECC 内置命令 + +### 启动循环 + +```bash +/ecc:loop-start sequential # Sequential 模式 +/ecc:loop-start continuous-pr # PR 循环模式 +/ecc:loop-start rfc-dag # Ralphinho 模式 +/ecc:loop-start infinite # 无限生成模式 + +/ecc:loop-start sequential --mode safe # safe = 严格质量门 +/ecc:loop-start sequential --mode fast # fast = 减少检查 +``` + +### 监控 + +```bash +/ecc:loop-status # 查看当前循环状态 +/ecc:loop-status --watch # 持续监控 +``` + +### 故障恢复 + +``` +1. 冻结循环 +2. 运行 /harness-audit +3. 缩小范围到失败的 unit +4. 用明确的验收标准重试 +``` + +--- + +## 反模式 + +| 反模式 | 问题 | 正确做法 | +|--------|------|---------| +| 无退出条件的无限循环 | 烧钱 | 始终设 max-runs/max-cost/max-duration | +| 迭代间无上下文桥梁 | 重复劳动 | 用 SHARED_TASK_NOTES.md | +| 对同一失败盲目重试 | 浪费 | 捕获错误上下文给下次 | +| 用否定指令代替清理 pass | 质量下降 | De-Sloppify 独立 pass | +| 所有 agent 在同一上下文 | 自我审查偏差 | 每阶段独立进程 | +| 并行任务编辑同一文件 | 冲突 | git worktree 隔离 | + +--- + +## 组合使用 + +1. **Sequential + De-Sloppify** -- 最常见,每个实现步骤后加清理 +2. **Continuous PR + De-Sloppify** -- `--review-prompt` 里加清理指令 +3. **任何循环 + Verification** -- 提交前用 `/ecc:verify` 做质量门 +4. **简单循环里用分级模型** -- 简单任务 Haiku,复杂任务 Opus + +## Related + +- [[dmux 多Agent并行编排]] +- [[Ralphinho RFC-DAG 编排模式]] +- [[Everything Claude Code 完整指南]] +- [[Everything Claude Code 用法速查]] diff --git a/4 - Resources/Claude-Code/Everything Claude Code 完整指南.md b/4 - Resources/Claude-Code/Everything Claude Code 完整指南.md index dfb3df2..c06594b 100644 --- a/4 - Resources/Claude-Code/Everything Claude Code 完整指南.md +++ b/4 - Resources/Claude-Code/Everything Claude Code 完整指南.md @@ -7,18 +7,20 @@ source: "https://github.com/affaan-m/everything-claude-code" # Everything Claude Code 完整指南 -生产级 Claude Code 插件系统,包含 108 skills、25 agents、57 commands、hooks 和 rules。v1.8.0,经过 10+ 个月的高强度日常使用演化。方法论与最佳实践见 [[Everything Claude Code 方法论与最佳实践]],按场景速查见 [[Everything Claude Code 用法速查]]。 +生产级 Claude Code 插件系统。v1.10.0 (2026-04-06 更新),包含 215 skills、112 agents、82 commands、hooks 和 rules (608 files total)。方法论与最佳实践见 [[Everything Claude Code 方法论与最佳实践]],按场景速查见 [[Everything Claude Code 用法速查]]。 + +自主循环和并行编排详见:[[Autonomous Loops 自主循环模式]]、[[dmux 多Agent并行编排]]、[[Ralphinho RFC-DAG 编排模式]] ## 项目架构 ``` -everything-claude-code/ -├── agents/ (16个) - 专用子代理 -├── skills/ (65个) - 工作流定义和领域知识 -├── commands/ (40个) - slash 命令 +everything-claude-code/ (v1.10.0, 608 files) +├── agents/ (112个) - 专用子代理 (.agents/ + agents/) +├── skills/ (215个) - 工作流定义和领域知识 +├── commands/ (82个) - slash 命令 ├── hooks/ - 基于事件的自动化 -├── rules/ - 始终遵循的规则(按语言分层) -├── scripts/ - 跨平台 Node.js 工具脚本 +├── rules/ - 始终遵循的规则(15种语言 + common) +├── scripts/ (93个) - 跨平台 Node.js 工具脚本 ├── mcp-configs/- MCP 服务器配置模板 └── contexts/ - 动态注入的上下文文件 ``` @@ -30,12 +32,50 @@ everything-claude-code/ /plugin marketplace add affaan-m/everything-claude-code /plugin install everything-claude-code@everything-claude-code -# Rules 手动安装(插件无法分发规则) -git clone https://github.com/affaan-m/everything-claude-code.git -cd everything-claude-code -./install.sh python typescript # 按需选语言 +# Rules 安装 (v1.10.0 新方式:插件内置 install.sh) +# 插件缓存位于 ~/.claude/plugins/cache/everything-claude-code/ecc/{version}/ +cd ~/.claude/plugins/cache/everything-claude-code/ecc/1.10.0 +bash install.sh --profile full # 安装全部 (608 files) +bash install.sh python typescript golang # 按需选语言 ``` +## v1.10.0 主要变更 + +### Legacy Commands -> Skills 迁移 + +12 个 command 变为 legacy shim,推荐直接使用对应 skill: + +| Legacy Command | 替代 Skill | +|---|---| +| `/ecc:orchestrate` | `dmux-workflows` / `autonomous-agent-harness` | +| `/ecc:verify` | `verification-loop` | +| `/ecc:tdd` | `tdd-workflow` | +| `/ecc:eval` | `eval-harness` | +| `/ecc:e2e` | `e2e-testing` | +| `/ecc:docs` | `documentation-lookup` | +| `/ecc:claw` | `nanoclaw-repl` | +| `/ecc:agent-sort` | `agent-sort` | +| `/ecc:context-budget` | `context-budget` | +| `/ecc:devfleet` | `claude-devfleet` | +| `/ecc:prompt-optimize` | `prompt-optimizer` | +| `/ecc:rules-distill` | `rules-distill` | + +Legacy shim 仍然可用(向后兼容),只是内部转发到对应 skill。 + +### 模块化安装 + +新增 manifest-based 安装系统,20 个模块: +- rules-core, agents-core, commands-core, hooks-runtime +- platform-configs, framework-language, database +- workflow-quality, security, research-apis +- business-content, operator-workflows, social-distribution +- media-generation, orchestration, swift-apple +- agentic-patterns, devops-infra, supply-chain-domain, document-processing + +### 新增语言支持 + +Rules 新增:java, kotlin, dart, csharp, cpp, rust, perl, php, web, zh (中文) + --- ## 全部 65 Skills @@ -256,6 +296,9 @@ ECC_DISABLED_HOOKS="pre:bash:tmux-reminder,post:edit:typecheck" ### Resources - [[Everything Claude Code 方法论与最佳实践]] - [[Everything Claude Code 用法速查]] +- [[Autonomous Loops 自主循环模式]] +- [[dmux 多Agent并行编排]] +- [[Ralphinho RFC-DAG 编排模式]] ### Zettelkasten - [[Everything Claude Code 最佳实践]] diff --git a/4 - Resources/Claude-Code/Ralphinho RFC-DAG 编排模式.md b/4 - Resources/Claude-Code/Ralphinho RFC-DAG 编排模式.md new file mode 100644 index 0000000..e01af1f --- /dev/null +++ b/4 - Resources/Claude-Code/Ralphinho RFC-DAG 编排模式.md @@ -0,0 +1,271 @@ +--- +created: "2026-04-06" +type: resource +tags: [resource, claude-code, AI-tools, ralphinho, RFC, DAG, multi-agent, orchestration, ECC] +source: "~/.claude/skills/ralphinho-rfc-pipeline/SKILL.md" +--- + +# Ralphinho RFC-DAG 编排模式 + +最复杂的自主循环模式。把 RFC/PRD 分解为依赖 DAG,按层并行执行,每个 unit 过分级质量管道,最后通过合并队列着陆。由 enitrat 创建。 + +相关笔记:[[Autonomous Loops 自主��环模式]]、[[dmux 多Agent并行编排]] + +## 架构总览 + +``` +RFC 文档 + | + v +AI 分解为 WorkUnit (含依赖 DAG) + | + v +RALPH LOOP (最多 3 pass) + | + +-- 按 DAG 层执行 (层内并行): + | 每个 unit 在独立 worktree: + | Research -> Plan -> Implement -> Test -> Review + | (深度按复杂度分级) + | + +-- 合并队列: + Rebase onto main -> Run tests -> Land or Evict + 被驱逐的 unit 带着冲突上下文重新进入 +``` + +## WorkUnit 定义 + +```typescript +interface WorkUnit { + id: string; // kebab-case 标识 + name: string; // 可读名称 + rfcSections: string[]; // 对应 RFC 哪些章节 + description: string; // 详细描述 + deps: string[]; // 依赖 (其他 unit ID) + acceptance: string[]; // 具体验收标准 + tier: "trivial" | "small" | "medium" | "large"; +} +``` + +### 分解原则 + +- 偏好更少、更内聚的 unit(减少合并风险) +- 最小化跨 unit 文件重叠(避免冲突) +- 测试跟随实现(不要分成 "implement X" + "test X") +- 仅在有真实代码依赖时才建立依赖关系 + +## DAG 层级执行 + +依赖 DAG 决定执行顺序: + +``` +Layer 0: [unit-a, unit-b] <- 无依赖,并行 +Layer 1: [unit-c] <- 依赖 unit-a +Layer 2: [unit-d, unit-e] <- 依赖 unit-c +``` + +同层内并行,跨层顺序执行。 + +## 复杂度分级管道 + +不同复杂度走不同深度的质量管道: + +| 级别 | 管道阶段 | +|------|---------| +| trivial | implement -> test | +| small | implement -> test -> code-review | +| medium | research -> plan -> implement -> test -> PRD-review + code-review -> review-fix | +| large | research -> plan -> implement -> test -> PRD-review + code-review -> review-fix -> final-review | + +## 分离上下文窗口 (消除自我审查偏差) + +每个阶段运行在独立 agent 进程中,reviewer 永远不是 author: + +| 阶段 | 模型 | 目的 | +|------|------|------| +| Research | Sonnet | 读代码+RFC,产出上下文文档 | +| Plan | Opus | 设计实现步骤 | +| Implement | Codex/Sonnet | 写代码 | +| Test | Sonnet | 跑构建+测试 | +| PRD Review | Sonnet | Spec 合规检查 | +| Code Review | Opus | 质量+安全检查 | +| Review Fix | Codex/Sonnet | 处理 review 意见 | +| Final Review | Opus | 质量门 (仅 large tier) | + +## 合并队列 + +``` +Unit branch + | + +-- Rebase onto main + | 冲突? -> EVICT (捕获冲突上下文) + | + +-- Run build + tests + | 失败? -> EVICT (捕获测试输出) + | + +-- Pass -> Fast-forward main, push, delete branch +``` + +### 文件重叠智能 + +- 无重叠的 unit:投机性并行着陆 +- 有重叠的 unit:逐个着陆,每次 rebase + +### 驱逐恢复 + +被驱逐时,完整上下文(冲突文件、diff、测试输出)传给下次实现: + +```markdown +## MERGE CONFLICT -- RESOLVE BEFORE NEXT LANDING + +Your previous implementation conflicted with another unit that landed first. +Restructure your changes to avoid the conflicting files/lines below. + +{完整驱逐上下文和 diff} +``` + +## 阶段间数据流 + +``` +research.contextFilePath --------> plan +plan.implementationSteps --------> implement +implement.{filesCreated} --------> test, reviews +test.failingSummary ------------> reviews, implement (next pass) +reviews.{feedback} -------------> review-fix -> implement (next pass) +final-review.reasoning ---------> implement (next pass) +evictionContext -----------------> implement (after merge conflict) +``` + +## Worktree 隔离 + +每个 unit 在独立 worktree 中运行。同一 unit 的各管道阶段共享 worktree,保留跨阶段状态(上下文文件、计划文件、代码变更)。 + +--- + +## 实际例子:smart-support 多租户改造 + +### Step 1: 写 RFC + +```markdown +# RFC: Multi-Tenant Agent Architecture + +## Goal +Support multiple tenants, each with own agent config and conversation history. + +## Work Units +1. tenant-model: Tenant SQLAlchemy model + migration +2. tenant-middleware: FastAPI middleware, extract tenant from JWT +3. agent-scoping: Scope agent registry per tenant +4. conversation-isolation: Filter conversations by tenant_id +5. frontend-tenant-selector: Tenant switcher in UI header +6. e2e-multi-tenant: E2E test for full flow + +## Dependencies +tenant-model -> tenant-middleware -> agent-scoping +tenant-model -> conversation-isolation +agent-scoping + conversation-isolation -> frontend-tenant-selector +all -> e2e-multi-tenant +``` + +### Step 2: DAG 分解 + +``` +Layer 0: [tenant-model] # tier: small +Layer 1: [tenant-middleware, conversation-isolation] # tier: medium, small +Layer 2: [agent-scoping] # tier: medium +Layer 3: [frontend-tenant-selector] # tier: small +Layer 4: [e2e-multi-tenant] # tier: small +``` + +### Step 3: 执行脚本 + +```bash +#!/bin/bash +set -e + +# --- Layer 0: tenant-model (small: implement -> test -> review) --- +claude -p --model sonnet "Implement Tenant SQLAlchemy model in backend/app/models/tenant.py. + Fields: id, name, api_key_hash, created_at. Write migration. Tests first." +claude -p --model opus "Review changes for security (api_key hashing) and schema design." + +# --- Layer 1: 并行 (medium + small) --- + +# tenant-middleware (medium: research -> plan -> implement -> test -> review) +( + claude -p --model sonnet --allowedTools "Read,Grep,Glob" \ + "Research how FastAPI middleware works in this project. Document in /tmp/middleware-research.md" + claude -p --model opus \ + "Read /tmp/middleware-research.md. Plan tenant extraction from JWT. Write to /tmp/middleware-plan.md" + claude -p --model sonnet \ + "Read /tmp/middleware-plan.md. Implement tenant middleware. Tests first." + claude -p --model opus \ + "Review tenant-middleware changes for security and correctness." +) & +PID1=$! + +# conversation-isolation (small: implement -> test -> review) +( + claude -p --model sonnet \ + "Add tenant_id to conversations table. Filter all conversation queries by tenant_id. Tests first." + claude -p --model opus \ + "Review conversation-isolation changes." +) & +PID2=$! + +wait $PID1 $PID2 + +# De-sloppify Layer 1 +claude -p "Review all uncommitted changes. Remove test slop. Run pytest --cov=app." + +# --- Layer 2: agent-scoping (medium) --- +claude -p --model sonnet --allowedTools "Read,Grep,Glob" \ + "Research how backend/app/registry.py loads agents. Document in /tmp/registry-research.md" +claude -p --model opus \ + "Read /tmp/registry-research.md. Plan tenant-scoped agent loading. Write to /tmp/scoping-plan.md" +claude -p --model sonnet \ + "Read /tmp/scoping-plan.md. Implement tenant-scoped agent loading. Tests first." +claude -p --model opus \ + "Review agent-scoping changes for correctness and security." + +# --- Layer 3: frontend (small) --- +claude -p "Add tenant selector to frontend header. Call GET /api/tenants. + Store selected tenant in context. Pass tenant_id header on all API calls." + +# --- Layer 4: E2E (small) --- +claude -p "Write E2E test in backend/tests/e2e/test_multi_tenant.py: + 1. Create two tenants + 2. Send chat as tenant A + 3. Verify tenant B cannot see A's conversations + Run pytest -m e2e" + +# --- Final verification --- +claude -p "Run pytest --cov=app --cov-report=term-missing. Fix any failures." +``` + +--- + +## 何时使用 Ralphinho vs 更简单的模式 + +| 信号 | 用 Ralphinho | 用更简单的 | +|------|-------------|-----------| +| 多个相互依赖的 work unit | 是 | 否 | +| 需要并行实现 | 是 | 否 | +| 合并冲突可能 | 是 | 否 (sequential 就行) | +| 单文件变更 | 否 | 是 (sequential) | +| 多天项目 | 是 | 可能 (continuous-claude) | +| Spec/RFC 已写好 | 是 | 可能 | +| 快速迭代单一事物 | 否 | 是 (NanoClaw 或 pipeline) | + +## 关键设计原则 + +1. **确定性执行** -- 前置分解锁定并行度和���序 +2. **人在关键杠杆点审查** -- work plan 是最高杠杆的干预点 +3. **关注点分离** -- 每阶段独立上下文+独立 agent +4. **带上下文的冲突恢复** -- 不是盲目重试 +5. **分级深度** -- trivial 跳过 research/review,large 最大审查力度 +6. **可恢复工作流** -- 状态持久化到 SQLite,任意点恢复 + +## Related + +- [[Autonomous Loops 自主循环���式]] +- [[dmux 多Agent并行编排]] +- [[Everything Claude Code ��整指南]] diff --git a/4 - Resources/Claude-Code/dmux 多Agent并行编排.md b/4 - Resources/Claude-Code/dmux 多Agent并行编排.md new file mode 100644 index 0000000..8090c3b --- /dev/null +++ b/4 - Resources/Claude-Code/dmux 多Agent并行编排.md @@ -0,0 +1,268 @@ +--- +created: "2026-04-06" +type: resource +tags: [resource, claude-code, AI-tools, dmux, multi-agent, parallel, orchestration, ECC] +source: "~/.claude/skills/dmux-workflows/SKILL.md" +--- + +# dmux 多Agent并行编排 + +用 tmux 管理多个 AI agent 面板,每个面板跑独立 agent 会话,最后合并结果。ECC v1.10.0 中 `/ecc:orchestrate` 的并行执行部分路由到此 skill。 + +相关笔记:[[Autonomous Loops 自主循环模式]]、[[Everything Claude Code 完整指南]] + +## 什么是 dmux + +tmux-based 的 AI agent 面板管理工具: +- 按 `n` 创建新面板 + 输入 prompt +- 按 `m` 合并面板输出到主会话 +- 支持:Claude Code、Codex、OpenCode、Cline、Gemini、Qwen + +安装:`https://github.com/standardagents/dmux` + +## 快速开始 + +```bash +# 启动 dmux +dmux + +# 创建面板 (按 n,输入 prompt) +# 面板1: "Implement auth middleware in src/auth/" +# 面板2: "Write tests for the user service" +# 面板3: "Update API documentation" + +# 各面板独立运行 +# 完成后按 m 合并 +``` + +--- + +## 5 种工作模式 + +### 模式 1: Research + Implement (调研 + 实现) + +``` +面板1 (Research): "Research best practices for rate limiting in Node.js. + Write findings to /tmp/rate-limit-research.md" + +面板2 (Implement): "Implement rate limiting middleware for Express API. + Start with basic token bucket, we'll refine after research completes." + +# 面板1完成后,合并到面板2的上下文 +``` + +### 模式 2: Multi-File Feature (多文件并行) + +``` +面板1: "Create database schema and migrations for billing" +面板2: "Build billing API endpoints in src/api/billing/" +面板3: "Create billing dashboard UI components" + +# 全部合并后在主面板做集成 +``` + +### 模式 3: Test + Fix Loop (测试 + 修复) + +``` +面板1 (Watcher): "Run test suite in watch mode. Summarize failures." +面板2 (Fixer): "Fix failing tests based on error output from pane 1" +``` + +### 模式 4: Cross-Harness (跨工具) + +``` +面板1 (Claude Code): "Review security of auth module" +面板2 (Codex): "Refactor utility functions for performance" +面板3 (Claude Code): "Write E2E tests for checkout flow" +``` + +### 模式 5: Code Review Pipeline (并行审查) + +``` +面板1: "Review src/api/ for security vulnerabilities" +面板2: "Review src/api/ for performance issues" +面板3: "Review src/api/ for test coverage gaps" + +# 合并为单份报告 +``` + +--- + +## Git Worktree 隔离 + +当并行任务可能编辑同一文件时,用 worktree 隔离: + +```bash +# 创建隔离 worktree +git worktree add -b feat/auth ../feature-auth HEAD +git worktree add -b feat/billing ../feature-billing HEAD + +# 各面板在不同 worktree 里工作 +# 面板1: cd ../feature-auth && claude +# 面板2: cd ../feature-billing && claude + +# 完成后合并分支 +git merge feat/auth +git merge feat/billing +``` + +--- + +## ECC orchestrate-worktrees.js + +ECC 提供的 worktree 编排辅助脚本,位于 `~/.claude/scripts/orchestrate-worktrees.js`。 + +### 使用方式 + +```bash +# 干跑 (只打印计划) +node ~/.claude/scripts/orchestrate-worktrees.js plan.json + +# 只写编排文件 +node ~/.claude/scripts/orchestrate-worktrees.js plan.json --write-only + +# 执行 (创建 worktree + tmux session) +node ~/.claude/scripts/orchestrate-worktrees.js plan.json --execute +``` + +### plan.json 格式 + +```json +{ + "sessionName": "feature-auth", + "baseRef": "HEAD", + "launcherCommand": "claude -p \"$(cat {task_file})\"", + "workers": [ + { "name": "backend-api", "task": "Implement auth API endpoints" }, + { "name": "frontend-ui", "task": "Build login UI components" }, + { "name": "tests", "task": "Write integration tests for auth" } + ] +} +``` + +### 可用占位符 + +| 占位符 | 说明 | +|--------|------| +| `{worker_name}` | Worker 名称 | +| `{worker_slug}` | Worker slug | +| `{session_name}` | Session 名称 | +| `{repo_root}` | 仓库根目录 | +| `{worktree_path}` | Worktree 路径 | +| `{branch_name}` | 分支名 | +| `{task_file}` | 任务文件路径 | +| `{handoff_file}` | 交接文件路径 | +| `{status_file}` | 状态文件路径 | + +### seedPaths:共享未提交文件 + +当 worker 需要访问主 checkout 中未提交的文件时(本地脚本、草稿计划等): + +```json +{ + "sessionName": "workflow-e2e", + "seedPaths": [ + "scripts/orchestrate-worktrees.js", + ".claude/plan/workflow-e2e-test.json" + ], + "launcherCommand": "bash {repo_root}/scripts/worker.sh {task_file}", + "workers": [ + { "name": "seed-check", "task": "Verify seeded files are present." } + ] +} +``` + +### 查看编排状态 + +```bash +node ~/.claude/scripts/orchestration-status.js plan.json +``` + +输出包含:session 活跃度、tmux 面板元数据、worker 状态、目标、交接摘要。 + +--- + +## 实际例子:smart-support 并行开发 + +### 例1:反馈功能三面板并行 + +```json +{ + "sessionName": "feedback-feature", + "baseRef": "HEAD", + "launcherCommand": "claude -p \"$(cat {task_file})\"", + "workers": [ + { + "name": "backend-api", + "task": "In backend/app/feedback/, create models.py (Feedback SQLAlchemy model) and router.py (POST /api/feedback, GET /api/feedback/stats). Follow backend/app/replay/router.py patterns. Write tests in backend/tests/unit/test_feedback.py FIRST. Run pytest --cov=app." + }, + { + "name": "frontend-ui", + "task": "In frontend/src/components/, create FeedbackButton.tsx (thumbs-up/down). onClick calls POST /api/feedback. Integrate into chat message component." + }, + { + "name": "docs-update", + "task": "Update docs/ARCHITECTURE.md to add feedback module. Update docs/DEVELOPMENT-PLAN.md with feedback feature." + } + ] +} +``` + +```bash +# 执行 +node ~/.claude/scripts/orchestrate-worktrees.js .claude/plan/feedback.json --execute + +# 完成后合并 +git merge feedback-feature/backend-api +git merge feedback-feature/frontend-ui +git merge feedback-feature/docs-update +``` + +### 例2:Code Review Pipeline + +```json +{ + "sessionName": "review-pipeline", + "baseRef": "HEAD", + "launcherCommand": "claude -p --allowedTools 'Read,Grep,Glob' \"$(cat {task_file})\"", + "workers": [ + { "name": "security", "task": "Review backend/app/ for security vulnerabilities. Write report to /tmp/security-review.md" }, + { "name": "performance", "task": "Review backend/app/ for performance issues. Write report to /tmp/perf-review.md" }, + { "name": "coverage", "task": "Analyze backend/tests/ for coverage gaps. Write report to /tmp/coverage-review.md" } + ] +} +``` + +--- + +## 最佳实践 + +1. **只并行独立任务** -- 有依赖关系的不要并行 +2. **清晰边界** -- 每个面板处理不同的文件或关注点 +3. **策略性合并** -- 合并前先 review 面板输出 +4. **用 worktree** -- 可能编辑同一文件时必须隔离 +5. **控制面板数** -- 每个面板消耗 API token,建议不超过 5-6 个 + +## 互补工具对比 + +| 工具 | 功能 | 适用 | +|------|------|------| +| dmux | tmux 面板管理 | 并行 agent 会话 | +| Superset | 终端 IDE (10+ 并行) | 大规模编排 | +| Claude Code Task tool | 进程内子 agent | 会话内程序化并行 | +| orchestrate-worktrees.js | ECC worktree 编排 | 长时间/跨工具会话 | + +## 故障排除 + +| 问题 | 解决 | +|------|------| +| 面板无响应 | `tmux capture-pane -pt :0.` 检查 | +| 合并冲突 | 用 git worktree 隔离 | +| Token 消耗高 | 减少并行面板数 | +| tmux 未找到 | `brew install tmux` (macOS) / `apt install tmux` (Linux) | + +## Related + +- [[Autonomous Loops 自主循环模式]] +- [[Ralphinho RFC-DAG 编排模式]] +- [[Everything Claude Code 完整指南]]