Agent Skills › AvivK5498/The-Claude-Protocol

AvivK5498/The-Claude-Protocol

GitHub

引导用户完成轻量级多智能体编排环境的初始化。强制收集项目信息并确认执行提供商(仅Claude或外部),随后克隆仓库、运行Bootstrap脚本,并在重启后执行发现代理以建立任务追踪与代码审查机制。

6 skills 335

Install All Skills

npx skills add AvivK5498/The-Claude-Protocol --all -g -y
More Options

List skills in collection

npx skills add AvivK5498/The-Claude-Protocol --list

Skills in Collection (6)

引导用户完成轻量级多智能体编排环境的初始化。强制收集项目信息并确认执行提供商(仅Claude或外部),随后克隆仓库、运行Bootstrap脚本,并在重启后执行发现代理以建立任务追踪与代码审查机制。
需要设置多智能体工作流 初始化Beads编排环境 配置Agent委托策略
.claude/skills/create-beads-orchestration/SKILL.md
npx skills add AvivK5498/The-Claude-Protocol --skill create-beads-orchestration -g -y
SKILL.md
Frontmatter
{
    "name": "create-beads-orchestration",
    "description": "Bootstrap lean multi-agent orchestration with beads task tracking. Use for projects needing agent delegation without heavy MCP overhead.",
    "user-invocable": true
}

Create Beads Orchestration

Set up lightweight multi-agent orchestration with git-native task tracking and mandatory code review gates.


CRITICAL: Mandatory 4-Step Workflow

You MUST follow ALL 4 steps below in exact order. Missing ANY step is a CATASTROPHIC FAILURE.
Step Action Checkpoint
1 Get project info from user Have project name, directory, AND provider choice
2 Clone repo and run bootstrap Bootstrap completes successfully
3 STOP - Instruct user to restart Claude Code User confirms they will restart
4 After restart: Run discovery agent Supervisors created in .claude/agents/

DO NOT:

  • Skip asking for project info
  • Skip asking about provider delegation (Claude-only vs External providers)
  • Continue after bootstrap without telling user to restart
  • Forget to run discovery after restart
  • Consider setup complete until discovery has run

The setup is NOT complete until Step 4 (discovery) has run.


Step 1: Get Project Info

**YOU MUST ASK ALL THREE QUESTIONS BEFORE PROCEEDING TO STEP 2 using AskUserQuestion.**
  1. Project directory: Where to install (default: current working directory)
  2. Project name: For agent templates (will auto-infer from package.json/pyproject.toml if not provided)
  3. Provider delegation: MANDATORY - You MUST use AskUserQuestion for this choice

1.1 Get Project Directory and Name

Ask the user or auto-detect from package.json/pyproject.toml.

1.2 MANDATORY: Ask Provider Delegation Choice

**YOU MUST CALL AskUserQuestion WITH THIS EXACT QUESTION BEFORE RUNNING BOOTSTRAP.**

Do NOT skip this. Do NOT assume a default. Do NOT proceed without the user's explicit choice.

AskUserQuestion(
  questions=[{
    "question": "How should read-only agents (scout, detective, architect, scribe, code-reviewer) be executed?",
    "header": "Providers",
    "options": [
      {"label": "Claude only (Recommended)", "description": "All agents run via Claude Task(). Simpler setup, no external dependencies."},
      {"label": "External providers", "description": "Delegate to Codex CLI (with Gemini fallback). Requires codex login and optional gemini CLI."}
    ],
    "multiSelect": false
  }]
)

After user answers:

  • If "Claude only" → use --claude-only flag in bootstrap
  • If "External providers" → do NOT use --claude-only flag

DO NOT proceed to Step 2 until you have the provider choice from the user.


Step 2: Clone and Run Bootstrap

git clone --depth=1 https://github.com/AvivK5498/The-Claude-Protocol "${TMPDIR:-/tmp}/beads-orchestration-setup"
# If user selected "Claude only":
python3 "${TMPDIR:-/tmp}/beads-orchestration-setup/bootstrap.py" \
  --project-name "{{PROJECT_NAME}}" \
  --project-dir "{{PROJECT_DIR}}" \
  --claude-only

# If user selected "External providers":
python3 "${TMPDIR:-/tmp}/beads-orchestration-setup/bootstrap.py" \
  --project-name "{{PROJECT_NAME}}" \
  --project-dir "{{PROJECT_DIR}}"

The bootstrap script will:

  1. Install beads CLI (via brew, npm, or go)
  2. Initialize .beads/ directory
  3. Copy agent templates to .claude/agents/
  4. Copy hooks to .claude/hooks/
  5. Configure .claude/settings.json
  6. Set up .mcp.json for provider_delegator
  7. Create CLAUDE.md with orchestrator instructions
  8. Update .gitignore

Verify bootstrap completed successfully before proceeding.


Step 3: STOP - User Must Restart

**YOU MUST STOP HERE AND INSTRUCT THE USER TO RESTART CLAUDE CODE.**

Tell the user:

Setup phase complete. You MUST restart Claude Code now.

The new hooks and MCP configuration will only load after restart.

After restarting:

  1. Open this same project directory
  2. Tell me "Continue orchestration setup" or run /create-beads-orchestration again
  3. I will run the discovery agent to complete setup

Do not skip this restart - the orchestration will not work without it.

DO NOT proceed to Step 4 in this session. The restart is mandatory.


Step 4: Run Discovery (After Restart)

If the user returns after restart and says "continue setup" or similar:
  1. Verify bootstrap completed (check for .claude/agents/scout.md)
  2. Run the discovery agent:
Task(
    subagent_type="discovery",
    prompt="Detect tech stack and create supervisors for this project"
)

Discovery will:

  • Scan package.json, requirements.txt, Dockerfile, etc.
  • Fetch specialist agents from external directory
  • Inject beads workflow into each supervisor
  • Write supervisors to .claude/agents/
  1. After discovery completes, tell the user:

Orchestration setup complete!

Created supervisors: [list what discovery created]

You can now use the orchestration workflow:

  • Create tasks with bd create "Task name" -d "Description"
  • The orchestrator will delegate to appropriate supervisors
  • All work requires code review before completion

Cleanup (Optional)

rm -rf "${TMPDIR:-/tmp}/beads-orchestration-setup"

What This Creates

  • Beads CLI for git-native task tracking (one bead = one branch = one task)
  • Core agents: scout, detective, architect, scribe, code-reviewer
  • Discovery agent: Auto-detects tech stack and creates specialized supervisors
  • Hooks: Enforce orchestrator discipline, code review gates, concise responses
  • Branch-per-task workflow: Parallel development with automated merge conflict handling

With --claude-only (default):

  • All agents run via Claude Task() - no external dependencies

With external providers:

  • MCP Provider Delegator enables Codex→Gemini→Claude fallback chain
  • Additional enforcement hooks for provider delegation

Requirements

Claude only mode (default):

  • beads CLI: Installed automatically (or manually via brew/npm/go)
  • uv: Python package manager (only if using external providers)

External providers mode:

  • Codex CLI: codex login for authentication (primary provider)
  • Gemini CLI: Optional fallback when Codex hits rate limits
  • uv: Python package manager for MCP server

More Information

See the full documentation: https://github.com/AvivK5498/The-Claude-Protocol

为Claude Code配置轻量级多智能体编排,利用Beads CLI和Git工作树实现任务追踪与并行开发。自动检测状态、获取项目信息并引导用户完成初始化及发现阶段,确保工作流纪律。
需要设置多智能体协作流程 希望使用轻量级任务追踪替代MCP 初始化基于Beads的Agent工作区
npx skills add AvivK5498/The-Claude-Protocol --skill create-beads-orchestration -g -y
SKILL.md
Frontmatter
{
    "name": "create-beads-orchestration",
    "description": "Bootstrap lean multi-agent orchestration with beads task tracking. Use for projects needing agent delegation without heavy MCP overhead.",
    "user-invocable": true
}

Create Beads Orchestration

Set up lightweight multi-agent orchestration with git-native task tracking for Claude Code.

What This Skill Does

This skill bootstraps a complete multi-agent workflow where:

  • Orchestrator (you) investigates issues, manages tasks, delegates implementation
  • Supervisors (specialized agents) execute fixes in isolated worktrees
  • Beads CLI tracks all work with git-native task management
  • Hooks enforce workflow discipline automatically

Each task gets its own worktree at .worktrees/bd-{BEAD_ID}/, keeping main clean and enabling parallel work.

Beads Kanban UI

The setup will auto-detect Beads Kanban UI and configure accordingly. If not found, you'll be offered to install it.


Step 0: Detect Setup State (ALWAYS RUN FIRST)

**Before doing anything else, detect if this is a fresh setup or a resume after restart.**

Check for bootstrap artifacts:

ls .claude/agents/scout.md 2>/dev/null && echo "BOOTSTRAP_COMPLETE" || echo "FRESH_SETUP"

If BOOTSTRAP_COMPLETE:

  • Bootstrap already ran in a previous session
  • Skip directly to Step 4: Run Discovery
  • Do NOT ask for project info or run bootstrap again

If FRESH_SETUP:

  • This is a new installation
  • Proceed to Step 1: Get Project Info

Workflow Overview

| Step | Action | When to Run | |------|--------|-------------| | 0 | Detect setup state | **ALWAYS** (determines path) | | 1 | Get project info from user | Fresh setup only | | 2 | Run bootstrap | Fresh setup only | | 3 | **STOP** - Instruct user to restart | Fresh setup only | | 4 | Run discovery agent | After restart OR if bootstrap already complete |

The setup is NOT complete until Step 4 (discovery) has run.


Step 1: Get Project Info (Fresh Setup Only)

**YOU MUST GET PROJECT INFO AND DETECT/ASK ABOUT KANBAN UI BEFORE PROCEEDING TO STEP 2.**
  1. Project directory: Where to install (default: current working directory)
  2. Project name: For agent templates (will auto-infer from package.json/pyproject.toml if not provided)
  3. Kanban UI: Auto-detect, or ask the user to install

1.1 Get Project Directory and Name

Ask the user or auto-detect from package.json/pyproject.toml.

1.2 Detect or Install Kanban UI

which bead-kanban 2>/dev/null && echo "KANBAN_FOUND" || echo "KANBAN_NOT_FOUND"

If KANBAN_FOUND → Use --with-kanban-ui flag. Tell the user:

Detected Beads Kanban UI. Configuring worktree management via API.

If KANBAN_NOT_FOUND → Ask:

AskUserQuestion(
  questions=[
    {
      "question": "Beads Kanban UI not detected. It adds a visual kanban board with dependency graphs and API-driven worktree management. Install it?",
      "header": "Kanban UI",
      "options": [
        {"label": "Yes, install it (Recommended)", "description": "Runs: npm install -g beads-kanban-ui"},
        {"label": "Skip", "description": "Use git worktrees directly. You can install later."}
      ],
      "multiSelect": false
    }
  ]
)
  • If "Yes" → Run npm install -g beads-kanban-ui, then use --with-kanban-ui flag
  • If "Skip" → do NOT use --with-kanban-ui flag

Step 2: Run Bootstrap

# With Kanban UI:
npx beads-orchestration@latest bootstrap \
  --project-name "{{PROJECT_NAME}}" \
  --project-dir "{{PROJECT_DIR}}" \
  --with-kanban-ui

# Without Kanban UI (git worktrees only):
npx beads-orchestration@latest bootstrap \
  --project-name "{{PROJECT_NAME}}" \
  --project-dir "{{PROJECT_DIR}}"

The bootstrap script will:

  1. Install beads CLI (via brew, npm, or go)
  2. Initialize .beads/ directory
  3. Copy agent templates to .claude/agents/
  4. Copy hooks to .claude/hooks/
  5. Configure .claude/settings.json
  6. Create CLAUDE.md with orchestrator instructions
  7. Update .gitignore

Verify bootstrap completed successfully before proceeding.


Step 3: STOP - User Must Restart

**YOU MUST STOP HERE AND INSTRUCT THE USER TO RESTART CLAUDE CODE.**

Tell the user:

Setup phase complete. You MUST restart Claude Code now.

The new hooks and MCP configuration will only load after restart.

After restarting:

  1. Open this same project directory
  2. Tell me "Continue orchestration setup" or run /create-beads-orchestration again
  3. I will run the discovery agent to complete setup

Do not skip this restart - the orchestration will not work without it.

DO NOT proceed to Step 4 in this session. The restart is mandatory.


Step 4: Run Discovery (After Restart OR Detection)

**Run this step if:** - Step 0 detected `BOOTSTRAP_COMPLETE`, OR - User returned after restart and said "continue setup" or ran `/create-beads-orchestration` again
  1. Verify bootstrap completed (check for .claude/agents/scout.md) - already done in Step 0
  2. Run the discovery agent:
Task(
    subagent_type="discovery",
    prompt="Detect tech stack and create supervisors for this project"
)

Discovery will:

  • Scan package.json, requirements.txt, Dockerfile, etc.
  • Fetch specialist agents from external directory
  • Inject beads workflow into each supervisor
  • Write supervisors to .claude/agents/
  1. After discovery completes, tell the user:

Orchestration setup complete!

Created supervisors: [list what discovery created]

You can now use the orchestration workflow:

  • Create tasks with bd create "Task name" -d "Description"
  • The orchestrator will delegate to appropriate supervisors
  • All work requires code review before completion

What This Creates

  • Beads CLI for git-native task tracking (one bead = one worktree = one task)
  • Core agents: scout, detective, architect, scribe, code-reviewer (all run via Claude Task)
  • Discovery agent: Auto-detects tech stack and creates specialized supervisors
  • Hooks: Enforce orchestrator discipline, code review gates, concise responses
  • Worktree-per-task workflow: Isolated development in .worktrees/bd-{BEAD_ID}/

With --with-kanban-ui:

  • Worktrees created via API (localhost:3008) with git fallback
  • Requires Beads Kanban UI running

Without --with-kanban-ui:

  • Worktrees created via raw git commands

Epic Workflow (Cross-Domain Features)

For features requiring multiple supervisors (e.g., DB + API + Frontend), use the epic workflow:

When to Use Epics

Task Type Workflow
Single-domain (one supervisor) Standalone bead
Cross-domain (multiple supervisors) Epic with children

Epic Workflow Steps

  1. Create epic: bd create "Feature name" -d "Description" --type epic
  2. Create design doc (if needed): Dispatch architect to create .designs/{EPIC_ID}.md
  3. Link design: bd update {EPIC_ID} --design ".designs/{EPIC_ID}.md"
  4. Create children with dependencies:
    bd create "DB schema" -d "..." --parent {EPIC_ID}              # BD-001.1
    bd create "API endpoints" -d "..." --parent {EPIC_ID} --deps BD-001.1  # BD-001.2
    bd create "Frontend" -d "..." --parent {EPIC_ID} --deps BD-001.2       # BD-001.3
    
  5. Dispatch sequentially: Use bd ready to find unblocked tasks (each child gets own worktree)
  6. User merges each PR: Wait for child's PR to merge before dispatching next
  7. Close epic: bd close {EPIC_ID} after all children merged

Design Docs

Design docs ensure consistency across epic children:

  • Schema definitions (exact column names, types)
  • API contracts (endpoints, request/response shapes)
  • Shared constants/enums
  • Data flow between layers

Key rule: Orchestrator dispatches architect to create design docs. Orchestrator never writes design docs directly.

Hooks Enforce Epic Workflow

  • enforce-sequential-dispatch.sh: Blocks dispatch if task has unresolved blockers
  • enforce-bead-for-supervisor.sh: Requires BEAD_ID for all supervisors
  • validate-completion.sh: Verifies worktree, push, bead status before supervisor completes

Requirements

  • beads CLI: Installed automatically by bootstrap (via brew, npm, or go)

More Information

See the full documentation: https://github.com/AvivK5498/The-Claude-Protocol

为Claude Code配置轻量级多智能体编排,通过Beads CLI实现基于Git的任务跟踪与隔离工作树管理。适用于需智能体委派且避免MCP开销的项目,支持自动检测状态、引导用户获取项目信息并集成看板UI。
需要设置多智能体协作流程 希望使用Git原生方式跟踪任务 避免重型MCP架构的代理委派需求
skills/create-beads-orchestration/SKILL.md
npx skills add AvivK5498/The-Claude-Protocol --skill create-beads-orchestration -g -y
SKILL.md
Frontmatter
{
    "name": "create-beads-orchestration",
    "description": "Bootstrap lean multi-agent orchestration with beads task tracking. Use for projects needing agent delegation without heavy MCP overhead.",
    "user-invocable": true
}

Create Beads Orchestration

Set up lightweight multi-agent orchestration with git-native task tracking for Claude Code.

What This Skill Does

This skill bootstraps a complete multi-agent workflow where:

  • Orchestrator (you) investigates issues, manages tasks, delegates implementation
  • Supervisors (specialized agents) execute fixes in isolated worktrees
  • Beads CLI tracks all work with git-native task management
  • Hooks enforce workflow discipline automatically

Each task gets its own worktree at .worktrees/bd-{BEAD_ID}/, keeping main clean and enabling parallel work.

Beads Kanban UI

The setup will auto-detect Beads Kanban UI and configure accordingly. If not found, you'll be offered to install it.


Step 0: Detect Setup State (ALWAYS RUN FIRST)

**Before doing anything else, detect if this is a fresh setup or a resume after restart.**

Check for bootstrap artifacts:

ls .claude/agents/scout.md 2>/dev/null && echo "BOOTSTRAP_COMPLETE" || echo "FRESH_SETUP"

If BOOTSTRAP_COMPLETE:

  • Bootstrap already ran in a previous session
  • Skip directly to Step 4: Run Discovery
  • Do NOT ask for project info or run bootstrap again

If FRESH_SETUP:

  • This is a new installation
  • Proceed to Step 1: Get Project Info

Workflow Overview

| Step | Action | When to Run | |------|--------|-------------| | 0 | Detect setup state | **ALWAYS** (determines path) | | 1 | Get project info from user | Fresh setup only | | 2 | Run bootstrap | Fresh setup only | | 3 | **STOP** - Instruct user to restart | Fresh setup only | | 4 | Run discovery agent | After restart OR if bootstrap already complete |

The setup is NOT complete until Step 4 (discovery) has run.


Step 1: Get Project Info (Fresh Setup Only)

**YOU MUST GET PROJECT INFO AND DETECT/ASK ABOUT KANBAN UI BEFORE PROCEEDING TO STEP 2.**
  1. Project directory: Where to install (default: current working directory)
  2. Project name: For agent templates (will auto-infer from package.json/pyproject.toml if not provided)
  3. Kanban UI: Auto-detect, or ask the user to install

1.1 Get Project Directory and Name

Ask the user or auto-detect from package.json/pyproject.toml.

1.2 Detect or Install Kanban UI

which bead-kanban 2>/dev/null && echo "KANBAN_FOUND" || echo "KANBAN_NOT_FOUND"

If KANBAN_FOUND → Use --with-kanban-ui flag. Tell the user:

Detected Beads Kanban UI. Configuring worktree management via API.

If KANBAN_NOT_FOUND → Ask:

AskUserQuestion(
  questions=[
    {
      "question": "Beads Kanban UI not detected. It adds a visual kanban board with dependency graphs and API-driven worktree management. Install it?",
      "header": "Kanban UI",
      "options": [
        {"label": "Yes, install it (Recommended)", "description": "Runs: npm install -g beads-kanban-ui"},
        {"label": "Skip", "description": "Use git worktrees directly. You can install later."}
      ],
      "multiSelect": false
    }
  ]
)
  • If "Yes" → Run npm install -g beads-kanban-ui, then use --with-kanban-ui flag
  • If "Skip" → do NOT use --with-kanban-ui flag

Step 2: Run Bootstrap

# With Kanban UI:
npx beads-orchestration@latest bootstrap \
  --project-name "{{PROJECT_NAME}}" \
  --project-dir "{{PROJECT_DIR}}" \
  --with-kanban-ui

# Without Kanban UI (git worktrees only):
npx beads-orchestration@latest bootstrap \
  --project-name "{{PROJECT_NAME}}" \
  --project-dir "{{PROJECT_DIR}}"

The bootstrap script will:

  1. Install beads CLI (via brew, npm, or go)
  2. Initialize .beads/ directory
  3. Copy agent templates to .claude/agents/
  4. Copy hooks to .claude/hooks/
  5. Configure .claude/settings.json
  6. Create CLAUDE.md with orchestrator instructions
  7. Update .gitignore

Verify bootstrap completed successfully before proceeding.


Step 3: STOP - User Must Restart

**YOU MUST STOP HERE AND INSTRUCT THE USER TO RESTART CLAUDE CODE.**

Tell the user:

Setup phase complete. You MUST restart Claude Code now.

The new hooks and MCP configuration will only load after restart.

After restarting:

  1. Open this same project directory
  2. Tell me "Continue orchestration setup" or run /create-beads-orchestration again
  3. I will run the discovery agent to complete setup

Do not skip this restart - the orchestration will not work without it.

DO NOT proceed to Step 4 in this session. The restart is mandatory.


Step 4: Run Discovery (After Restart OR Detection)

**Run this step if:** - Step 0 detected `BOOTSTRAP_COMPLETE`, OR - User returned after restart and said "continue setup" or ran `/create-beads-orchestration` again
  1. Verify bootstrap completed (check for .claude/agents/scout.md) - already done in Step 0
  2. Run the discovery agent:
Task(
    subagent_type="discovery",
    prompt="Detect tech stack and create supervisors for this project"
)

Discovery will:

  • Scan package.json, requirements.txt, Dockerfile, etc.
  • Fetch specialist agents from external directory
  • Inject beads workflow into each supervisor
  • Write supervisors to .claude/agents/
  1. After discovery completes, tell the user:

Orchestration setup complete!

Created supervisors: [list what discovery created]

You can now use the orchestration workflow:

  • Create tasks with bd create "Task name" -d "Description"
  • The orchestrator will delegate to appropriate supervisors
  • All work requires code review before completion

What This Creates

  • Beads CLI for git-native task tracking (one bead = one worktree = one task)
  • Core agents: scout, detective, architect, scribe, code-reviewer (all run via Claude Task)
  • Discovery agent: Auto-detects tech stack and creates specialized supervisors
  • Hooks: Enforce orchestrator discipline, code review gates, concise responses
  • Worktree-per-task workflow: Isolated development in .worktrees/bd-{BEAD_ID}/

With --with-kanban-ui:

  • Worktrees created via API (localhost:3008) with git fallback
  • Requires Beads Kanban UI running

Without --with-kanban-ui:

  • Worktrees created via raw git commands

Epic Workflow (Cross-Domain Features)

For features requiring multiple supervisors (e.g., DB + API + Frontend), use the epic workflow:

When to Use Epics

Task Type Workflow
Single-domain (one supervisor) Standalone bead
Cross-domain (multiple supervisors) Epic with children

Epic Workflow Steps

  1. Create epic: bd create "Feature name" -d "Description" --type epic
  2. Create design doc (if needed): Dispatch architect to create .designs/{EPIC_ID}.md
  3. Link design: bd update {EPIC_ID} --design ".designs/{EPIC_ID}.md"
  4. Create children with dependencies:
    bd create "DB schema" -d "..." --parent {EPIC_ID}              # BD-001.1
    bd create "API endpoints" -d "..." --parent {EPIC_ID} --deps BD-001.1  # BD-001.2
    bd create "Frontend" -d "..." --parent {EPIC_ID} --deps BD-001.2       # BD-001.3
    
  5. Dispatch sequentially: Use bd ready to find unblocked tasks (each child gets own worktree)
  6. User merges each PR: Wait for child's PR to merge before dispatching next
  7. Close epic: bd close {EPIC_ID} after all children merged

Design Docs

Design docs ensure consistency across epic children:

  • Schema definitions (exact column names, types)
  • API contracts (endpoints, request/response shapes)
  • Shared constants/enums
  • Data flow between layers

Key rule: Orchestrator dispatches architect to create design docs. Orchestrator never writes design docs directly.

Hooks Enforce Epic Workflow

  • enforce-sequential-dispatch.sh: Blocks dispatch if task has unresolved blockers
  • enforce-bead-for-supervisor.sh: Requires BEAD_ID for all supervisors
  • validate-completion.sh: Verifies worktree, push, bead status before supervisor completes

Requirements

  • beads CLI: Installed automatically by bootstrap (via brew, npm, or go)

More Information

See the full documentation: https://github.com/AvivK5498/The-Claude-Protocol

强制在实现任务前验证外部数据,要求同时执行组件与功能测试,并记录DEMO证据。旨在通过‘先观察后编码’和端到端验证,确保代码与实际数据一致及集成无误。
开始任何实现任务时 涉及外部数据读写时
skills/subagents-discipline/SKILL.md
npx skills add AvivK5498/The-Claude-Protocol --skill subagents-discipline -g -y
SKILL.md
Frontmatter
{
    "name": "subagents-discipline",
    "description": "Invoke at the start of any implementation task to enforce verification-first development"
}

Implementation Discipline

Core principle: Test the FEATURE, not just the component you built.


Three Rules

Rule 1: Look Before You Code

Before writing code that touches external data (API, database, file, config):

  1. Fetch/read the ACTUAL data - run the command, see the output
  2. Note exact field names, types, formats - not what docs say, what you SEE
  3. Code against what you observed - not what you assumed

This catches: field name mismatches, wrong data shapes, missing fields, format differences.

WITHOUT looking first:
  Assumed: column is "reference_images"
  Reality: column is "reference_image_url"
  Result:  Query fails

WITH looking first:
  Ran: SELECT column_name FROM information_schema.columns WHERE table_name = 'assets';
  Saw: reference_image_url
  Coded against: reference_image_url
  Result: Works

Rule 2: Test Both Levels

Component test catches: logic bugs, edge cases, type errors Feature test catches: integration bugs, auth issues, data flow problems

Both are required. Component test alone is NOT sufficient.

You built Component test Feature test
API endpoint curl returns 200 UI calls API, displays result
Database change Migration runs App reads/writes correctly
Frontend component Renders, no errors User can see and interact
Full-stack feature Each piece works alone End-to-end flow works

The pattern:

  1. Build the thing
  2. Component test - verify your piece works in isolation
  3. Feature test - verify the integrated feature works end-to-end
  4. Only then claim done

Rule 3: Use Your Tools

Before claiming you can't fully test:

  1. Check what MCP servers you have access to - list available tools
  2. If any tool can help verify the feature works, use it
  3. Be resourceful - browser automation, database inspection, API testing tools

"I couldn't test the feature" is only valid after exhausting available options.


DEMO Block (Required)

Every completion must include evidence. Code reviewer will verify this.

DEMO:
  COMPONENT:
    Command: [what you ran to test the component]
    Result: [what you observed]

  FEATURE:
    Steps: [how you tested the integrated feature]
    Result: [what you observed - screenshot, output, etc.]

When Full Feature Test Isn't Possible

If you genuinely cannot test end-to-end (long-running job, external service, no browser tools):

DEMO:
  COMPONENT:
    Command: curl localhost:3008/api/endpoint
    Result: 200, returns expected data

  FEATURE: PARTIAL
    Verified: [what you could test]
    Needs human check: [what still needs verification]
    Why: [specific reason - no browser MCP, takes 10+ minutes, requires external service]

Not acceptable reasons for PARTIAL:

  • "Server wasn't running" → start it
  • "Didn't have test data" → create it
  • "Would take too long" → if < 2 minutes, do it

Acceptable reasons:

  • No browser/UI automation tools available
  • External API with rate limits or costs
  • Job takes > 5 minutes to complete
  • Requires production data that can't be mocked

For Epic Children

If your BEAD_ID contains a dot (e.g., BD-001.2), you're implementing part of a larger feature:

  1. Check for design doc: bd show {EPIC_ID} --json | jq -r '.[0].design'
  2. Read it if it exists - this is your contract
  3. Match it exactly - same field names, same types, same shapes

Design docs ensure all pieces fit together. If you deviate, integration fails.


Completion Checklist

Before marking done:

  • Looked at actual data/interfaces before coding (not assumed)
  • Component test passes (your piece works in isolation)
  • Feature test passes OR documented as PARTIAL with valid reason
  • DEMO block included with evidence
  • Used available tools to test (checked MCP servers, used what helps)

Red Flags - Stop and Verify

When you catch yourself thinking:

  • "This should work..." → run it and see
  • "I assume the field is..." → look at the actual data
  • "I'll test it later..." → test it now
  • "It's too simple to break..." → verify anyway

When you're about to say:

  • "Done!" / "Fixed!" / "Should work now!" → show the DEMO first

The Bottom Line

Component test passing ≠ feature works
Curl returning 200 ≠ UI displays correctly
TypeScript compiles ≠ user can use it

Test the feature like a user would use it. Then show evidence. Then claim done.

提供React和Next.js性能优化最佳实践,涵盖消除数据瀑布流、减小包体积及并行数据获取等40+条规则。在编写代码前应用,确保遵循高性能架构模式。
实现React或Next.js组件时 重构现有前端代码以提升性能时 设计数据获取策略时
templates/skills/react-best-practices/SKILL.md
npx skills add AvivK5498/The-Claude-Protocol --skill react-best-practices -g -y
SKILL.md
Frontmatter
{
    "name": "react-best-practices",
    "description": "React and Next.js performance optimization patterns. Use BEFORE implementing any React code to ensure best practices are followed."
}

React Best Practices

Version 1.0.0 Source: Vercel Engineering (vercel-labs/agent-skills)

Note: This document is for agents and LLMs to follow when maintaining, generating, or refactoring React and Next.js codebases. Contains 40+ rules across 8 categories, prioritized by impact.


How to Use This Skill

Before implementing ANY React/Next.js code:

  1. Review the relevant sections based on what you're building
  2. Apply the patterns as you write code
  3. Use the "Incorrect" vs "Correct" examples as templates

Priority order: Eliminating Waterfalls > Bundle Size > Server-Side > Client-Side > Re-renders > Rendering > JS Perf > Advanced


Quick Reference: Critical Rules

Top 5 Rules (Always Apply)

  1. Promise.all() for independent operations - Never sequential awaits for independent data
  2. Avoid barrel file imports - Import directly from source files
  3. Dynamic imports for heavy components - Lazy-load Monaco, charts, etc.
  4. Parallel data fetching with component composition - Structure RSC for parallelism
  5. Minimize serialization at RSC boundaries - Only pass needed fields to client

1. Eliminating Waterfalls

Impact: CRITICAL - Waterfalls are the #1 performance killer.

1.1 Defer Await Until Needed

Move await into branches where actually used.

// BAD: blocks both branches
async function handleRequest(userId: string, skipProcessing: boolean) {
  const userData = await fetchUserData(userId)
  if (skipProcessing) return { skipped: true }
  return processUserData(userData)
}

// GOOD: only blocks when needed
async function handleRequest(userId: string, skipProcessing: boolean) {
  if (skipProcessing) return { skipped: true }
  const userData = await fetchUserData(userId)
  return processUserData(userData)
}

1.2 Promise.all() for Independent Operations

// BAD: 3 round trips
const user = await fetchUser()
const posts = await fetchPosts()
const comments = await fetchComments()

// GOOD: 1 round trip
const [user, posts, comments] = await Promise.all([
  fetchUser(),
  fetchPosts(),
  fetchComments()
])

1.3 Strategic Suspense Boundaries

// BAD: wrapper blocked by data
async function Page() {
  const data = await fetchData()
  return (
    <div>
      <Sidebar />
      <DataDisplay data={data} />
      <Footer />
    </div>
  )
}

// GOOD: wrapper shows immediately
function Page() {
  return (
    <div>
      <Sidebar />
      <Suspense fallback={<Skeleton />}>
        <DataDisplay />
      </Suspense>
      <Footer />
    </div>
  )
}

2. Bundle Size Optimization

Impact: CRITICAL - Reduces TTI and LCP.

2.1 Avoid Barrel File Imports

// BAD: loads 1,583 modules
import { Check, X, Menu } from 'lucide-react'

// GOOD: loads only 3 modules
import Check from 'lucide-react/dist/esm/icons/check'
import X from 'lucide-react/dist/esm/icons/x'
import Menu from 'lucide-react/dist/esm/icons/menu'

// ALTERNATIVE: Next.js 13.5+ config
// next.config.js
module.exports = {
  experimental: {
    optimizePackageImports: ['lucide-react', '@mui/material']
  }
}

2.2 Dynamic Imports for Heavy Components

// BAD: Monaco bundles with main chunk (~300KB)
import { MonacoEditor } from './monaco-editor'

// GOOD: Monaco loads on demand
import dynamic from 'next/dynamic'
const MonacoEditor = dynamic(
  () => import('./monaco-editor').then(m => m.MonacoEditor),
  { ssr: false }
)

2.3 Defer Non-Critical Libraries

// BAD: blocks initial bundle
import { Analytics } from '@vercel/analytics/react'

// GOOD: loads after hydration
import dynamic from 'next/dynamic'
const Analytics = dynamic(
  () => import('@vercel/analytics/react').then(m => m.Analytics),
  { ssr: false }
)

2.4 Preload on User Intent

function EditorButton({ onClick }: { onClick: () => void }) {
  const preload = () => {
    if (typeof window !== 'undefined') {
      void import('./monaco-editor')
    }
  }
  return (
    <button onMouseEnter={preload} onFocus={preload} onClick={onClick}>
      Open Editor
    </button>
  )
}

3. Server-Side Performance

Impact: HIGH

3.1 Minimize Serialization at RSC Boundaries

// BAD: serializes all 50 fields
async function Page() {
  const user = await fetchUser()  // 50 fields
  return <Profile user={user} />
}

// GOOD: serializes only needed fields
async function Page() {
  const user = await fetchUser()
  return <Profile name={user.name} avatar={user.avatar} />
}

3.2 Parallel Data Fetching with Component Composition

// BAD: Sidebar waits for Header's fetch
export default async function Page() {
  const header = await fetchHeader()
  return (
    <div>
      <div>{header}</div>
      <Sidebar />
    </div>
  )
}

// GOOD: both fetch simultaneously
async function Header() {
  const data = await fetchHeader()
  return <div>{data}</div>
}

async function Sidebar() {
  const items = await fetchSidebarItems()
  return <nav>{items.map(renderItem)}</nav>
}

export default function Page() {
  return (
    <div>
      <Header />
      <Sidebar />
    </div>
  )
}

3.3 Per-Request Deduplication with React.cache()

import { cache } from 'react'

export const getCurrentUser = cache(async () => {
  const session = await auth()
  if (!session?.user?.id) return null
  return await db.user.findUnique({ where: { id: session.user.id } })
})

3.4 Use after() for Non-Blocking Operations

import { after } from 'next/server'

export async function POST(request: Request) {
  await updateDatabase(request)

  // Log after response is sent
  after(async () => {
    const userAgent = (await headers()).get('user-agent')
    logUserAction({ userAgent })
  })

  return Response.json({ status: 'success' })
}

4. Client-Side Data Fetching

Impact: MEDIUM-HIGH

4.1 Use SWR for Automatic Deduplication

// BAD: no deduplication
function UserList() {
  const [users, setUsers] = useState([])
  useEffect(() => {
    fetch('/api/users').then(r => r.json()).then(setUsers)
  }, [])
}

// GOOD: multiple instances share one request
import useSWR from 'swr'
function UserList() {
  const { data: users } = useSWR('/api/users', fetcher)
}

5. Re-render Optimization

Impact: MEDIUM

5.1 Use Functional setState Updates

// BAD: requires state as dependency, risk of stale closure
const addItems = useCallback((newItems: Item[]) => {
  setItems([...items, ...newItems])
}, [items])

// GOOD: stable callback, no stale closures
const addItems = useCallback((newItems: Item[]) => {
  setItems(curr => [...curr, ...newItems])
}, [])

5.2 Use Lazy State Initialization

// BAD: runs on every render
const [settings] = useState(JSON.parse(localStorage.getItem('settings') || '{}'))

// GOOD: runs only once
const [settings] = useState(() => {
  const stored = localStorage.getItem('settings')
  return stored ? JSON.parse(stored) : {}
})

5.3 Use Transitions for Non-Urgent Updates

import { startTransition } from 'react'

function ScrollTracker() {
  const [scrollY, setScrollY] = useState(0)
  useEffect(() => {
    const handler = () => {
      startTransition(() => setScrollY(window.scrollY))
    }
    window.addEventListener('scroll', handler, { passive: true })
    return () => window.removeEventListener('scroll', handler)
  }, [])
}

5.4 Narrow Effect Dependencies

// BAD: re-runs on any user field change
useEffect(() => {
  console.log(user.id)
}, [user])

// GOOD: re-runs only when id changes
useEffect(() => {
  console.log(user.id)
}, [user.id])

6. Rendering Performance

Impact: MEDIUM

6.1 CSS content-visibility for Long Lists

.message-item {
  content-visibility: auto;
  contain-intrinsic-size: 0 80px;
}

6.2 Hoist Static JSX Elements

// BAD: recreates element every render
function Container() {
  return loading && <div className="animate-pulse h-20 bg-gray-200" />
}

// GOOD: reuses same element
const loadingSkeleton = <div className="animate-pulse h-20 bg-gray-200" />
function Container() {
  return loading && loadingSkeleton
}

6.3 Animate SVG Wrapper, Not SVG Element

// BAD: no hardware acceleration
<svg className="animate-spin">...</svg>

// GOOD: hardware accelerated
<div className="animate-spin">
  <svg>...</svg>
</div>

7. JavaScript Performance

Impact: LOW-MEDIUM

7.1 Build Index Maps for Repeated Lookups

// BAD: O(n) per lookup
items.filter(item => allowedIds.includes(item.id))

// GOOD: O(1) per lookup
const allowedSet = new Set(allowedIds)
items.filter(item => allowedSet.has(item.id))

7.2 Use toSorted() Instead of sort()

// BAD: mutates original array
const sorted = users.sort((a, b) => a.name.localeCompare(b.name))

// GOOD: creates new array
const sorted = users.toSorted((a, b) => a.name.localeCompare(b.name))

7.3 Early Return from Functions

// BAD: processes all items after finding error
function validateUsers(users: User[]) {
  let hasError = false
  for (const user of users) {
    if (!user.email) hasError = true
  }
  return hasError ? { valid: false } : { valid: true }
}

// GOOD: returns immediately on first error
function validateUsers(users: User[]) {
  for (const user of users) {
    if (!user.email) return { valid: false, error: 'Email required' }
  }
  return { valid: true }
}

8. Advanced Patterns

Impact: LOW

8.1 useEffectEvent for Stable Callbacks

import { useEffectEvent } from 'react'

function useWindowEvent(event: string, handler: () => void) {
  const onEvent = useEffectEvent(handler)
  useEffect(() => {
    window.addEventListener(event, onEvent)
    return () => window.removeEventListener(event, onEvent)
  }, [event])
}

Checklist Before Implementation

  • Independent async operations use Promise.all()
  • Heavy components use dynamic imports
  • RSC boundaries pass only needed fields
  • Suspense boundaries isolate data fetching
  • No barrel file imports for large libraries
  • State updates use functional form when depending on current state
  • Effects have narrow dependencies
  • Repeated lookups use Set/Map

References

提供工程实现核心原则,强调先读上下文、验证外部数据真实结构、通过实际运行快速闭环测试,并善用工具资源,确保代码准确可靠。
需要执行代码实现任务时 进行功能开发或修复bug时 涉及API、数据库或配置变更时
templates/skills/subagents-discipline/SKILL.md
npx skills add AvivK5498/The-Claude-Protocol --skill subagents-discipline -g -y
SKILL.md
Frontmatter
{
    "name": "subagents-discipline",
    "description": "Core engineering principles for implementation tasks"
}

Implementation Principles

Rule 0: Read the Bead First

Before implementing anything, read the bead comments for context:

bd show {BEAD_ID}
bd comments {BEAD_ID}

The orchestrator's dispatch prompt is automatically logged as a DISPATCH comment on the bead. This contains:

  • The investigation findings
  • Root cause analysis (file, function, line)
  • Related files that may need changes
  • Gotchas and edge cases

Use this context. Don't re-investigate. The comments contain everything you need to implement confidently.

If no dispatch or context comments exist, ask the orchestrator to provide context before proceeding.


Rule 1: Look Before You Code

Before writing code that touches external data (API, database, file, config):

  1. Fetch/read the ACTUAL data - run the command, see the output
  2. Note exact field names, types, formats - not what docs say, what you SEE
  3. Code against what you observed - not what you assumed
WITHOUT looking first:
  Assumed: column is "reference_images"
  Reality: column is "reference_image_url"
  Result:  Query fails

WITH looking first:
  Ran: SELECT column_name FROM information_schema.columns WHERE table_name = 'assets';
  Saw: reference_image_url
  Coded against: reference_image_url
  Result: Works

Rule 2: Test Functionally (Close the Loop)

Principle: Optimize for the fastest way to verify your work actually works.

You built Fast verification Slower alternative
API endpoint curl the endpoint, check response Write integration test
Database change Run migration, query the result Write migration test
Frontend component Load in browser, interact with it Write component test
CLI tool Run the command, check output Write unit test
Config change Restart service, verify behavior N/A — just verify

Two strategies:

  1. User Journey Tests — Test actual behavior as a user experiences it:

    # API: curl with real data
    curl -X POST localhost:3000/api/users -d '{"name":"test"}' -H "Content-Type: application/json"
    
    # CLI: run the command
    bd create "Test" -d "Testing" && bd list
    
    # Error case: curl with invalid auth
    curl -X POST localhost:3000/api/users -H "Authorization: Bearer invalid"
    
  2. Component Tests — Supplement for regression prevention when fast verification isn't possible:

    • Complex logic with many edge cases
    • Code that runs in environments you can't easily replicate
    • Shared libraries used by multiple consumers

"Close the Loop" principle: Run the actual thing. Verify it works. Check error cases.

Good: "Curled endpoint with invalid auth, got 401 as expected" Bad: "Wrote tests, they compile"

Rule 3: Use Your Tools

Before claiming you can't fully test:

  1. Check what MCP servers you have access to - list available tools
  2. If any tool can help verify the feature works, use it
  3. Be resourceful - browser automation, database inspection, API testing tools

Rule 4: Log Your Approach (Optional)

If you deviated from the orchestrator's suggestion, found a better path, or made a choice future maintainers might question:

bd comment {BEAD_ID} "APPROACH: Used X instead of Y because Z"

When to log:

  • Deviated from the suggested fix
  • Multiple valid solutions, chose one for a specific reason
  • Future maintainers might question the approach

Skip if the code is self-explanatory. This is not enforced.


For Epic Children

If your BEAD_ID contains a dot (e.g., BD-001.2), you're implementing part of a larger feature:

  1. Check for design doc: bd show {EPIC_ID} --json | jq -r '.[0].design'
  2. Read it if it exists - this is your contract
  3. Match it exactly - same field names, same types, same shapes

Red Flags - Stop and Verify

When you catch yourself thinking:

  • "This should work..." → run it and see
  • "I assume the field is..." → look at the actual data
  • "I'll test it later..." → test it now
  • "It's too simple to break..." → verify anyway

Главная - Вики-сайт
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-07-11 14:32
浙ICP备14020137号-1 $Гость$