Skip to content
Back to search

The-Claude-Protocol

SkillWorks with Claude CodeGitHub

Mutli-Agent orchestration workflow for Claude Code with automated task management using Beads CLI

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked yesterday
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/avivk5498--the-claude-protocol/badge.svg)](/listings/avivk5498--the-claude-protocol)

HTML

<a href="/listings/avivk5498--the-claude-protocol"><img src="/api/listings/avivk5498--the-claude-protocol/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

npx skills add AvivK5498/The-Claude-Protocol

Or via npm:

npm install -g beads-orchestration

Then in any Claude Code session:

/create-beads-orchestration

The skill walks you through setup, scans your tech stack, and creates supervisors with best practices injected.

Requirements

- Claude Code with hooks support - Node.js (for npx) - Python 3 (for bootstrap) - beads CLI (installed automatically)

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 263 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. ---
  2. name: create-beads-orchestration
  3. description: Bootstrap lean multi-agent orchestration with beads task tracking. Use for projects needing agent delegation without heavy MCP overhead.
  4. user-invocable: true
  5. ---
  6. # Create Beads Orchestration
  7. Set up lightweight multi-agent orchestration with git-native task tracking for Claude Code.
  8. ## What This Skill Does
  9. This skill bootstraps a complete multi-agent workflow where:
  10. - **Orchestrator** (you) investigates issues, manages tasks, delegates implementation
  11. - **Supervisors** (specialized agents) execute fixes in isolated worktrees
  12. - **Beads CLI** tracks all work with git-native task management
  13. - **Hooks** enforce workflow discipline automatically
  14. Each task gets its own worktree at `.worktrees/bd-{BEAD_ID}/`, keeping main clean and enabling parallel work.
  15. ## Beads Kanban UI
  16. The setup will auto-detect [Beads Kanban UI](https://github.com/AvivK5498/Beads-Kanban-UI) and configure accordingly. If not found, you'll be offered to install it.
  17. ---
  18. ## Step 0: Detect Setup State (ALWAYS RUN FIRST)
  19. <detection-phase>
  20. **Before doing anything else, detect if this is a fresh setup or a resume after restart.**
  21. Check for bootstrap artifacts:
  22. ```bash
  23. ls .claude/agents/scout.md 2>/dev/null && echo "BOOTSTRAP_COMPLETE" || echo "FRESH_SETUP"
  24. ```
  25. **If `BOOTSTRAP_COMPLETE`:**
  26. - Bootstrap already ran in a previous session
  27. - Skip directly to **Step 4: Run Discovery**
  28. - Do NOT ask for project info or run bootstrap again
  29. **If `FRESH_SETUP`:**
  30. - This is a new installation
  31. - Proceed to **Step 1: Get Project Info**
  32. </detection-phase>
  33. ---
  34. ## Workflow Overview
  35. <mandatory-workflow>
  36. | Step | Action | When to Run |
  37. |------|--------|-------------|
  38. | 0 | Detect setup state | **ALWAYS** (determines path) |
  39. | 1 | Get project info from user | Fresh setup only |
  40. | 2 | Run bootstrap | Fresh setup only |
  41. | 3 | **STOP** - Instruct user to restart | Fresh setup only |
  42. | 4 | Run discovery agent | After restart OR if bootstrap already complete |
  43. **The setup is NOT complete until Step 4 (discovery) has run.**
  44. </mandatory-workflow>
  45. ---
  46. ## Step 1: Get Project Info (Fresh Setup Only)
  47. <critical-step1>
  48. **YOU MUST GET PROJECT INFO AND DETECT/ASK ABOUT KANBAN UI BEFORE PROCEEDING TO STEP 2.**
  49. 1. **Project directory**: Where to install (default: current working directory)
  50. 2. **Project name**: For agent templates (will auto-infer from package.json/pyproject.toml if not provided)
  51. 3. **Kanban UI**: Auto-detect, or ask the user to install
  52. </critical-step1>
  53. ### 1.1 Get Project Directory and Name
  54. Ask the user or auto-detect from package.json/pyproject.toml.
  55. ### 1.2 Detect or Install Kanban UI
  56. ```bash
  57. which bead-kanban 2>/dev/null && echo "KANBAN_FOUND" || echo "KANBAN_NOT_FOUND"
  58. ```
  59. **If KANBAN_FOUND** → Use `--with-kanban-ui` flag. Tell the user:
  60. > Detected Beads Kanban UI. Configuring worktree management via API.
  61. **If KANBAN_NOT_FOUND** → Ask:
  62. ```
  63. AskUserQuestion(
  64. questions=[
  65. {
  66. "question": "Beads Kanban UI not detected. It adds a visual kanban board with dependency graphs and API-driven worktree management. Install it?",
  67. "header": "Kanban UI",
  68. "options": [
  69. {"label": "Yes, install it (Recommended)", "description": "Runs: npm install -g beads-kanban-ui"},
  70. {"label": "Skip", "description": "Use git worktrees directly. You can install later."}
  71. ],
  72. "multiSelect": false
  73. }
  74. ]
  75. )
  76. ```
  77. - If "Yes" → Run `npm install -g beads-kanban-ui`, then use `--with-kanban-ui` flag
  78. - If "Skip" → do NOT use `--with-kanban-ui` flag
  79. ---
  80. ## Step 2: Run Bootstrap
  81. ```bash
  82. # With Kanban UI:
  83. npx beads-orchestration@latest bootstrap \
  84. --project-name "{{PROJECT_NAME}}" \
  85. --project-dir "{{PROJECT_DIR}}" \
  86. --with-kanban-ui
  87. # Without Kanban UI (git worktrees only):
  88. npx beads-orchestration@latest bootstrap \
  89. --project-name "{{PROJECT_NAME}}" \
  90. --project-dir "{{PROJECT_DIR}}"
  91. ```
  92. The bootstrap script will:
  93. 1. Install beads CLI (via brew, npm, or go)
  94. 2. Initialize `.beads/` directory
  95. 3. Copy agent templates to `.claude/agents/`
  96. 4. Copy hooks to `.claude/hooks/`
  97. 5. Configure `.claude/settings.json`
  98. 6. Create `CLAUDE.md` with orchestrator instructions
  99. 7. Update `.gitignore`
  100. **Verify bootstrap completed successfully before proceeding.**
  101. ---
  102. ## Step 3: STOP - User Must Restart
  103. <critical>
  104. **YOU MUST STOP HERE AND INSTRUCT THE USER TO RESTART CLAUDE CODE.**
  105. Tell the user:
  106. > **Setup phase complete. You MUST restart Claude Code now.**
  107. >
  108. > The new hooks and MCP configuration will only load after restart.
  109. >
  110. > After restarting:
  111. > 1. Open this same project directory
  112. > 2. Tell me "Continue orchestration setup" or run `/create-beads-orchestration` again
  113. > 3. I will run the discovery agent to complete setup
  114. >
  115. > **Do not skip this restart - the orchestration will not work without it.**
  116. **DO NOT proceed to Step 4 in this session. The restart is mandatory.**
  117. </critical>
  118. ---
  119. ## Step 4: Run Discovery (After Restart OR Detection)
  120. <post-restart>
  121. **Run this step if:**
  122. - Step 0 detected `BOOTSTRAP_COMPLETE`, OR
  123. - User returned after restart and said "continue setup" or ran `/create-beads-orchestration` again
  124. 1. Verify bootstrap completed (check for `.claude/agents/scout.md`) - already done in Step 0
  125. 2. Run the discovery agent:
  126. ```python
  127. Task(
  128. subagent_type="discovery",
  129. prompt="Detect tech stack and create supervisors for this project"
  130. )
  131. ```
  132. Discovery will:
  133. - Scan package.json, requirements.txt, Dockerfile, etc.
  134. - Fetch specialist agents from external directory
  135. - Inject beads workflow into each supervisor
  136. - Write supervisors to `.claude/agents/`
  137. 3. After discovery completes, tell the user:
  138. > **Orchestration setup complete!**
  139. >
  140. > Created supervisors: [list what discovery created]
  141. >
  142. > You can now use the orchestration workflow:
  143. > - Create tasks with `bd create "Task name" -d "Description"`
  144. > - The orchestrator will delegate to appropriate supervisors
  145. > - All work requires code review before completion
  146. </post-restart>
  147. ---
  148. ## What This Creates
  149. - **Beads CLI** for git-native task tracking (one bead = one worktree = one task)
  150. - **Core agents**: scout, detective, architect, scribe, code-reviewer (all run via Claude Task)
  151. - **Discovery agent**: Auto-detects tech stack and creates specialized supervisors
  152. - **Hooks**: Enforce orchestrator discipline, code review gates, concise responses
  153. - **Worktree-per-task workflow**: Isolated development in `.worktrees/bd-{BEAD_ID}/`
  154. **With `--with-kanban-ui`:**
  155. - Worktrees created via API (localhost:3008) with git fallback
  156. - Requires [Beads Kanban UI](https://github.com/AvivK5498/Beads-Kanban-UI) running
  157. **Without `--with-kanban-ui`:**
  158. - Worktrees created via raw git commands
  159. ## Epic Workflow (Cross-Domain Features)
  160. For features requiring multiple supervisors (e.g., DB + API + Frontend), use the **epic workflow**:
  161. ### When to Use Epics
  162. | Task Type | Workflow |
  163. |-----------|----------|
  164. | Single-domain (one supervisor) | Standalone bead |
  165. | Cross-domain (multiple supervisors) | Epic with children |
  166. ### Epic Workflow Steps
  167. 1. **Create epic**: `bd create "Feature name" -d "Description" --type epic`
  168. 2. **Create design doc** (if needed): Dispatch architect to create `.designs/{EPIC_ID}.md`
  169. 3. **Link design**: `bd update {EPIC_ID} --design ".designs/{EPIC_ID}.md"`
  170. 4. **Create children with dependencies**:
  171. ```bash
  172. bd create "DB schema" -d "..." --parent {EPIC_ID} # BD-001.1
  173. bd create "API endpoints" -d "..." --parent {EPIC_ID} --deps BD-001.1 # BD-001.2
  174. bd create "Frontend" -d "..." --parent {EPIC_ID} --deps BD-001.2 # BD-001.3
  175. ```
  176. 5. **Dispatch sequentially**: Use `bd ready` to find unblocked tasks (each child gets own worktree)
  177. 6. **User merges each PR**: Wait for child's PR to merge before dispatching next
  178. 7. **Close epic**: `bd close {EPIC_ID}` after all children merged
  179. ### Design Docs
  180. Design docs ensure consistency across epic children:
  181. - Schema definitions (exact column names, types)
  182. - API contracts (endpoints, request/response shapes)
  183. - Shared constants/enums
  184. - Data flow between layers
  185. **Key rule**: Orchestrator dispatches architect to create design docs. Orchestrator never writes design docs directly.
  186. ### Hooks Enforce Epic Workflow
  187. - **enforce-sequential-dispatch.sh**: Blocks dispatch if task has unresolved blockers
  188. - **enforce-bead-for-supervisor.sh**: Requires BEAD_ID for all supervisors
  189. - **validate-completion.sh**: Verifies worktree, push, bead status before supervisor completes
  190. ## Requirements
  191. - **beads CLI**: Installed automatically by bootstrap (via brew, npm, or go)
  192. ## More Information
  193. See the full documentation: https://github.com/AvivK5498/The-Claude-Protocol
README.md · README · 196 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <div align="center">
  2. # THE CLAUDE PROTOCOL
  3. **Enforcement-first orchestration for Claude Code. Every agent tracked. Every decision logged. Nothing gets lost.**
  4. **Claude Code plans great. Without structure, nothing survives past one session.**
  5. [![npm version](https://img.shields.io/npm/v/beads-orchestration?style=for-the-badge&logo=npm&logoColor=white&color=CB3837)](https://www.npmjs.com/package/beads-orchestration)
  6. [![GitHub stars](https://img.shields.io/github/stars/AvivK5498/The-Claude-Protocol?style=for-the-badge&logo=github&color=181717)](https://github.com/AvivK5498/The-Claude-Protocol)
  7. [![License](https://img.shields.io/badge/license-MIT-blue?style=for-the-badge)](LICENSE)
  8. <br>
  9. ```bash
  10. npx skills add AvivK5498/The-Claude-Protocol
  11. ```
  12. **macOS and Linux.**
  13. <br>
  14. ![The Claude Protocol — Kanban UI](screenshots/kanbanui.png)
  15. <br>
  16. [Why This Exists](#why-this-exists) · [How It Works](#how-it-works) · [Getting Started](#getting-started) · [Hooks](#hooks)
  17. </div>
  18. ---
  19. ## Why This Exists
  20. Claude Code is the best coding agent out there. But let it run unsupervised and you get agents editing main, commits without PRs, lost context every session, and zero traceability on what was done and why.
  21. Plan mode helps — until you need to coordinate across files, track what was planned vs what shipped, or pick up a task three sessions later. Plans vanish. Context resets. Investigation gets redone from scratch.
  22. The Claude Protocol is the enforcement layer. It wraps Claude Code with 13 hooks that physically block bad actions, isolates every task in its own git worktree, and documents everything automatically — dispatch prompts, agent knowledge, decisions, all of it. [Beads](https://github.com/steveyegge/beads) (git-native tickets) track every unit of work from creation to merge.
  23. The complexity is in the system. What you see: Claude plans with you, you approve, agents execute in isolation, PRs get merged. Done.
  24. ---
  25. ## How It Works
  26. ```
  27. ┌─────────────────────────────────────────┐
  28. │ ORCHESTRATOR (Co-Pilot) │
  29. │ Plans with you (Plan mode) │
  30. │ Investigates with Grep/Read/Glob │
  31. │ Delegates implementation via Task() │
  32. └──────────────────┬──────────────────────┘
  33. │
  34. ┌───────────┼───────────┐
  35. ▼ ▼ ▼
  36. ┌─────────┐ ┌─────────┐ ┌─────────┐
  37. │ react- │ │ python- │ │ nextjs- │
  38. │supervisor│ │supervisor│ │supervisor│
  39. └────┬────┘ └────┬────┘ └────┬────┘
  40. │ │ │
  41. .worktrees/ .worktrees/ .worktrees/
  42. bd-BD-001 bd-BD-002 bd-BD-003
  43. ```
  44. **The orchestrator** investigates, discusses with you, and plans. It never writes code. Dispatch prompts are auto-logged to the bead so nothing gets lost.
  45. **Supervisors** are created automatically based on your tech stack. They read bead comments for full context, work in isolated worktrees, and push clean PRs.
  46. **Beads** are git-native tickets. Every task, every epic, every dependency — tracked in your repo, not a third-party service. One bead = one unit of work = one worktree = one PR.
  47. ### Workflow
  48. **Standalone** — Investigate → plan → approve → create bead → dispatch supervisor → worktree → PR → merge.
  49. **Epics** — Cross-domain work (DB + API + frontend) becomes an epic with enforced child dependencies. Each child gets its own worktree. Dependencies prevent dispatching out of order.
  50. **Quick Fix** — For trivial changes (<10 lines), the orchestrator can edit directly on a feature branch. The hook prompts the user for approval with file name and change size. Hard blocked on main — must use bead workflow there.
  51. Every task goes through beads — unless the user explicitly approves a quick fix.
  52. ### Kanban UI
  53. The Claude Protocol pairs with the [Beads Kanban UI](https://github.com/AvivK5498/Beads-Kanban-UI) for visual task management and GitOps directly from the browser. Track epics, subtasks, dependencies, and PR status across columns — without leaving the board.
  54. ---
  55. ## Getting Started
  56. ```bash
  57. npx skills add AvivK5498/The-Claude-Protocol
  58. ```
  59. Or via npm:
  60. ```bash
  61. npm install -g beads-orchestration
  62. ```
  63. Then in any Claude Code session:
  64. ```bash
  65. /create-beads-orchestration
  66. ```
  67. The skill walks you through setup, scans your tech stack, and creates supervisors with best practices injected.
  68. ### Requirements
  69. - Claude Code with hooks support
  70. - Node.js (for npx)
  71. - Python 3 (for bootstrap)
  72. - beads CLI (installed automatically)
  73. ---
  74. ## What Makes This Different
  75. ### Enforcement, Not Suggestions
  76. 13 hooks across 5 lifecycle events. They don't warn — they block. The orchestrator can't edit code on main. Supervisors can't skip beads. Epics can't close with open children. `git commit --no-verify` is blocked — pre-commit hooks always run.
  77. ### Investigation-First, Constraint-Driven
  78. The orchestrator must read the actual source file before delegating — no guessing. Constraints ("never dispatch without reading the source") outperform instructions ("remember to investigate"), inspired by [Cursor's multi-agent research](https://cursor.com/blog/self-driving-codebases). The orchestrator also maintains persistent memory across sessions.
  79. ### Documentation That Writes Itself
  80. Every supervisor dispatch prompt is automatically captured as a bead comment. Agents voluntarily log conventions and gotchas into a persistent knowledge base. Session start surfaces recent knowledge so agents don't re-investigate solved problems.
  81. ```bash
  82. # Agent captures an insight
  83. bd comment BD-001 "LEARNED: TaskGroup requires @Sendable closures in strict concurrency mode."
  84. # Search the knowledge base
  85. .beads/memory/recall.sh "concurrency"
  86. ```
  87. ### Follow-Up Traceability
  88. Closed beads are immutable. Bug fixes become new beads linked via `bd dep relate` — full history, no reopening. Merged branches don't get reused. Each fix gets its own worktree and PR.
  89. ---
  90. ## What Gets Installed
  91. ```
  92. .claude/
  93. ├── agents/ # Supervisors (auto-created for your tech stack)
  94. ├── hooks/ # Workflow enforcement (13 hooks)
  95. ├── skills/ # subagents-discipline, react-best-practices
  96. └── settings.json
  97. CLAUDE.md # Orchestrator instructions
  98. .beads/ # Task database
  99. memory/ # Knowledge base (knowledge.jsonl + recall.sh)
  100. .worktrees/ # Isolated worktrees per task (created dynamically)
  101. ```
  102. ---
  103. ## Hooks
  104. 13 hooks enforce every workflow step. They block before bad actions happen, auto-log after good ones, and validate before supervisors exit.
  105. **PreToolUse** (7 hooks) — Block orchestrator from writing code on main. Prompt for quick-fix approval on feature branches. Block `--no-verify` on commits. Allow memory file writes. Require beads for supervisor dispatch. Enforce worktree isolation. Block closing epics with open children. Enforce sequential dependency dispatch.
  106. **PostToolUse** (3 hooks) — Auto-log dispatch prompts as bead comments. Capture knowledge base entries. Enforce concise supervisor responses.
  107. **SubagentStop** (1 hook) — Verify worktree exists, code is pushed, bead status is updated.
  108. **SessionStart** (1 hook) — Surface task status, recent knowledge, and cleanup suggestions.
  109. **UserPromptSubmit** (1 hook) — Prompt for clarification on ambiguous requests.
  110. ---
  111. ## Advanced: External Providers
  112. By default, all agents run via Claude's Task(). To delegate read-only agents (scout, detective, etc.) to Codex/Gemini:
  113. ```bash
  114. /create-beads-orchestration --external-providers
  115. ```
  116. Requires Codex CLI (`codex login`), optionally Gemini CLI, and [uv](https://github.com/astral-sh/uv).
  117. ---
  118. ## License
  119. MIT
  120. ## Credits
  121. - [beads](https://github.com/steveyegge/beads) — Git-native task tracking by Steve Yegge
  122. - [sub-agents.directory](https://github.com/ayush-that/sub-agents.directory) — External agent templates
bootstrap.py · Bundled script · 928 lines · 5 findings marked
  1. #!/usr/bin/env python3
  2. """
  3. Bootstrap script for beads-based orchestration.
  4. Creates:
  5. - .beads/ directory with beads CLI
  6. - .claude/agents/ with agent templates (copied, not generated)
  7. - .claude/hooks/ with hook scripts
  8. - .claude/settings.json with hook configuration
  9. - .mcp.json with provider-delegator configuration (only with --external-providers)
  10. Usage:
  11. python bootstrap.py [--project-name NAME] [--project-dir DIR] [--with-kanban-ui]
  12. Modes:
  13. Default: All agents use Claude Task() directly (claude-only)
  14. --external-providers: Sets up provider_delegator MCP for Codex/Gemini delegation
  15. """
  16. import os
  17. import sys
  18. import json
  19. import shutil
  20. import stat
  21. import subprocess
  22. try:
  23. import tomllib
  24. except ImportError:
  25. tomllib = None
  26. from pathlib import Path
  27. from datetime import datetime
  28. import random
  29. # Get the directory where this script lives (lean-orchestration repo)
  30. SCRIPT_DIR = Path(__file__).parent.resolve()
  31. TEMPLATES_DIR = SCRIPT_DIR / "templates"
  32. # ============================================================================
  33. # CONFIGURATION
  34. # ============================================================================
  35. CORE_AGENTS = ["scout", "detective", "architect", "scribe", "discovery", "merge-supervisor", "code-reviewer"]
  36. # NOTE: Supervisors are NOT bootstrapped - they are created dynamically by the
  37. # discovery agent which fetches specialists from the external agents directory
  38. # and injects the beads workflow.
  39. # ============================================================================
  40. # PROJECT NAME INFERENCE
  41. # ============================================================================
  42. def infer_project_name(project_dir: Path) -> str:
  43. """Auto-infer project name from package files or directory name."""
  44. # Try package.json (Node.js)
  45. package_json = project_dir / "package.json"
  46. if package_json.exists():
  47. try:
  48. data = json.loads(package_json.read_text())
  49. if name := data.get("name"):
  50. return name.replace("-", " ").replace("_", " ").title()
  51. except (json.JSONDecodeError, KeyError):
  52. pass
  53. # Try pyproject.toml (Python)
  54. if tomllib:
  55. pyproject = project_dir / "pyproject.toml"
  56. if pyproject.exists():
  57. try:
  58. data = tomllib.loads(pyproject.read_text())
  59. if name := data.get("project", {}).get("name"):
  60. return name.replace("-", " ").replace("_", " ").title()
  61. if name := data.get("tool", {}).get("poetry", {}).get("name"):
  62. return name.replace("-", " ").replace("_", " ").title()
  63. except Exception:
  64. pass
  65. # Try Cargo.toml (Rust)
  66. cargo = project_dir / "Cargo.toml"
  67. if cargo.exists():
  68. try:
  69. data = tomllib.loads(cargo.read_text())
  70. if name := data.get("package", {}).get("name"):
  71. return name.replace("-", " ").replace("_", " ").title()
  72. except Exception:
  73. pass
  74. # Try go.mod (Go)
  75. go_mod = project_dir / "go.mod"
  76. if go_mod.exists():
  77. try:
  78. content = go_mod.read_text()
  79. for line in content.splitlines():
  80. if line.startswith("module "):
  81. module_path = line.split()[1]
  82. name = module_path.split("/")[-1]
  83. return name.replace("-", " ").replace("_", " ").title()
  84. except Exception:
  85. pass
  86. # Fallback to directory name
  87. return project_dir.name.replace("-", " ").replace("_", " ").title()
  88. # ============================================================================
  89. # PLACEHOLDER REPLACEMENT
  90. # ============================================================================
  91. def replace_placeholders(content: str, replacements: dict) -> str:
  92. """Replace all placeholders in content."""
  93. for placeholder, value in replacements.items():
  94. content = content.replace(placeholder, value)
  95. return content
  96. def copy_and_replace(source: Path, dest: Path, replacements: dict) -> None:
  97. """Copy file and replace placeholders."""
  98. content = source.read_text()
  99. updated = replace_placeholders(content, replacements)
  100. dest.parent.mkdir(parents=True, exist_ok=True)
  101. dest.write_text(updated)
  102. # Preserve executable permissions for shell scripts
  103. if source.suffix == '.sh':
  104. dest.chmod(dest.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
  105. # ============================================================================
  106. # CODEX DELEGATOR SETUP (SHARED LOCATION)
  107. # ============================================================================
  108. # Shared location for provider-delegator (installed once, used by all projects)
  109. SHARED_MCP_DIR = Path.home() / ".claude" / "mcp-servers" / "provider-delegator"
  110. def setup_provider_delegator() -> Path:
  111. """Set up provider-delegator in shared location (~/.claude/mcp-servers/provider-delegator/).
  112. This installs once and is reused by all projects.
  113. Returns path to venv python.
  114. """
  115. print("\n[0/8] Setting up provider-delegator (shared)...")
  116. source_dir = SCRIPT_DIR / "mcp-provider-delegator"
  117. venv_dir = SHARED_MCP_DIR / ".venv"
  118. venv_python = venv_dir / "bin" / "python"
  119. # Check if already installed in shared location
  120. if venv_python.exists():
  121. print(f" - Already installed at {SHARED_MCP_DIR}")
  122. return venv_python
  123. # Verify source exists
  124. if not source_dir.exists():
  125. print(f" ERROR: mcp-provider-delegator not found at {source_dir}")
  126. print(" Make sure you cloned the full lean-orchestration repo")
  127. return None
  128. # Check if uv is available
  129. if not shutil.which("uv"):
  130. print(" ERROR: 'uv' not found. Install with: curl -LsSf https://astral.sh/uv/install.sh | sh")
  131. return None
  132. # Create shared directory
  133. print(f" - Installing to {SHARED_MCP_DIR}")
  134. SHARED_MCP_DIR.mkdir(parents=True, exist_ok=True)
  135. # Copy source to shared location
  136. print(" - Copying source files...")
  137. for item in source_dir.iterdir():
  138. if item.name == ".venv":
  139. continue # Skip any existing venv in source
  140. dest = SHARED_MCP_DIR / item.name
  141. if item.is_dir():
  142. if dest.exists():
  143. shutil.rmtree(dest)
  144. shutil.copytree(item, dest)
  145. else:
  146. shutil.copy2(item, dest)
  147. # Create venv using uv
  148. print(" - Creating venv with uv...")
  149. result = subprocess.run(
  150. ["uv", "venv", str(venv_dir)],
  151. cwd=SHARED_MCP_DIR,
  152. capture_output=True,
  153. text=True
  154. )
  155. if result.returncode != 0:
  156. print(f" ERROR: Failed to create venv: {result.stderr}")
  157. return None
  158. # Install dependencies
  159. print(" - Installing dependencies...")
  160. result = subprocess.run(
  161. ["uv", "pip", "install", "-e", "."],
  162. cwd=SHARED_MCP_DIR,
  163. capture_output=True,
  164. text=True,
  165. env={**os.environ, "VIRTUAL_ENV": str(venv_dir)}
  166. )
  167. if result.returncode != 0:
  168. print(f" ERROR: Failed to install dependencies: {result.stderr}")
  169. return None
  170. print(f" DONE: provider-delegator installed at {SHARED_MCP_DIR}")
  171. return venv_python
  172. # ============================================================================
  173. # BEADS INSTALLATION
  174. # ============================================================================
  175. def install_beads(project_dir: Path, claude_only: bool = False) -> bool:
  176. """Install beads CLI and initialize .beads directory."""
  177. step = "[1/7]" if claude_only else "[1/8]"
  178. print(f"\n{step} Installing beads...")
  179. beads_dir = project_dir / ".beads"
  180. # Check if beads is already installed globally
  181. beads_installed = shutil.which("bd") is not None
  182. if not beads_installed:
  183. print(" - beads CLI (bd) not found, installing...")
  184. # Try installation methods in order of preference
  185. installed = False
  186. # Method 1: Homebrew (macOS)
  187. if shutil.which("brew") and sys.platform == "darwin":
  188. print(" - Trying Homebrew...")
  189. result = subprocess.run(
  190. ["brew", "install", "steveyegge/beads/bd"],
  191. capture_output=True,
  192. text=True
  193. )
  194. if result.returncode == 0:
  195. installed = True
  196. print(" - Installed via Homebrew")
  197. # Method 2: npm (cross-platform)
  198. if not installed and shutil.which("npm"):
  199. print(" - Trying npm...")
  200. result = subprocess.run(
  201. ["npm", "install", "-g", "@beads/bd"],
  202. capture_output=True,
  203. text=True
  204. )
  205. if result.returncode == 0:
  206. installed = True
  207. print(" - Installed via npm")
  208. # Method 3: curl install script (Linux/macOS/FreeBSD)
  209. if not installed and sys.platform != "win32":
  210. print(" - Trying curl install script...")
  211. result = subprocess.run(
  212. ["bash", "-c", "curl -fsSL https://raw.githubusercontent.com/steveyegge/beads/main/scripts/install.sh | bash"],
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 259 on GitHub
  213. capture_output=True,
  214. text=True
  215. )
  216. if result.returncode == 0:
  217. installed = True
  218. print(" - Installed via curl script")
  219. # Method 4: Go install (if Go is available)
  220. if not installed and shutil.which("go"):
  221. print(" - Trying go install...")
  222. result = subprocess.run(
  223. ["go", "install", "github.com/steveyegge/beads/cmd/bd@latest"],
  224. capture_output=True,
  225. text=True
  226. )
  227. if result.returncode == 0:
  228. installed = True
  229. print(" - Installed via go install")
  230. if not installed:
  231. print("\n ERROR: Could not install beads CLI (bd)")
  232. print(" The beads workflow requires the bd command.")
  233. print(" Please install manually: https://github.com/steveyegge/beads#-installation")
  234. print("\n Installation options:")
  235. print(" macOS: brew install steveyegge/beads/bd")
  236. print(" npm: npm install -g @beads/bd")
  237. print(" Go: go install github.com/steveyegge/beads/cmd/bd@latest")
  238. return False
  239. else:
  240. print(" - beads CLI already installed")
  241. beads_installed = True
  242. # Initialize .beads in project
  243. if not beads_dir.exists():
  244. print(" - Initializing .beads directory...")
  245. # Try bd init first
  246. if shutil.which("bd"):
  247. result = subprocess.run(
  248. ["bd", "init"],
  249. cwd=project_dir,
  250. capture_output=True,
  251. text=True
  252. )
  253. if result.returncode == 0:
  254. print(" - Initialized via 'bd init'")
  255. else:
  256. # Manual init as fallback
  257. _manual_beads_init(beads_dir)
  258. else:
  259. _manual_beads_init(beads_dir)
  260. else:
  261. print(" - .beads already exists")
  262. # Configure custom 'inreview' status for parallel work workflow
  263. if shutil.which("bd"):
  264. print(" - Configuring custom 'inreview' status...")
  265. result = subprocess.run(
  266. ["bd", "config", "set", "status.custom", "inreview"],
  267. cwd=project_dir,
  268. capture_output=True,
  269. text=True
  270. )
  271. if result.returncode == 0:
  272. print(" - Added 'inreview' custom status")
  273. else:
  274. print(f" - Warning: Could not add custom status: {result.stderr}")
  275. print(" DONE: beads setup complete")
  276. return True
  277. def _manual_beads_init(beads_dir: Path):
  278. """Manually create .beads directory structure."""
  279. beads_dir.mkdir(exist_ok=True)
  280. (beads_dir / "issues.jsonl").touch()
  281. # Create minimal config
  282. config = {
  283. "version": "1",
  284. "mode": "normal"
  285. }
  286. (beads_dir / "config.json").write_text(json.dumps(config, indent=2))
  287. print(" - Created .beads manually")
  288. def setup_memory(project_dir: Path) -> None:
  289. """Create .beads/memory/ directory with knowledge store and recall script."""
  290. memory_dir = project_dir / ".beads" / "memory"
  291. memory_dir.mkdir(parents=True, exist_ok=True)
  292. # Create empty knowledge store
  293. knowledge_file = memory_dir / "knowledge.jsonl"
  294. if not knowledge_file.exists():
  295. knowledge_file.touch()
  296. print(" - Created .beads/memory/knowledge.jsonl")
  297. # Copy recall script
  298. recall_src = TEMPLATES_DIR / "memory" / "recall.sh"
  299. recall_dest = memory_dir / "recall.sh"
  300. if recall_src.exists():
  301. shutil.copy2(recall_src, recall_dest)
  302. recall_dest.chmod(recall_dest.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
  303. print(" - Copied .beads/memory/recall.sh")
  304. else:
  305. print(" - WARNING: recall.sh template not found")
  306. # ============================================================================
  307. # RAMS INSTALLATION (Accessibility Review)
  308. # ============================================================================
  309. def install_rams() -> bool:
  310. """Install RAMS accessibility review tool if not already installed."""
  311. print("\n Checking RAMS (accessibility review tool)...")
  312. # Check if rams is already installed
  313. if shutil.which("rams"):
  314. print(" - RAMS already installed")
  315. return True
  316. print(" - RAMS not found, installing...")
  317. # Install via curl
  318. if sys.platform != "win32":
  319. result = subprocess.run(
  320. ["bash", "-c", "curl -fsSL https://rams.ai/install | bash"],
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 386 on GitHub
  321. capture_output=True,
  322. text=True
  323. )
  324. if result.returncode == 0:
  325. print(" - RAMS installed successfully")
  326. return True
  327. else:
  328. print(f" - Warning: Could not install RAMS: {result.stderr}")
  329. print(" - Frontend supervisors will still work but RAMS review enforcement may fail")
  330. print(" - Install manually: curl -fsSL https://rams.ai/install | bash")
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 396 on GitHub
  331. return False
  332. print(" - Warning: RAMS installation not supported on Windows")
  333. return False
  334. # ============================================================================
  335. # WEB INTERFACE GUIDELINES INSTALLATION
  336. # ============================================================================
  337. def install_web_interface_guidelines() -> bool:
  338. """Install Web Interface Guidelines review tool if not already installed."""
  339. print("\n Checking Web Interface Guidelines (design review tool)...")
  340. # Check if wig is already installed
  341. if shutil.which("wig"):
  342. print(" - Web Interface Guidelines already installed")
  343. return True
  344. print(" - Web Interface Guidelines not found, installing...")
  345. # Install via curl
  346. if sys.platform != "win32":
  347. result = subprocess.run(
  348. ["bash", "-c", "curl -fsSL https://vercel.com/design/guidelines/install | bash"],
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 421 on GitHub
  349. capture_output=True,
  350. text=True
  351. )
  352. if result.returncode == 0:
  353. print(" - Web Interface Guidelines installed successfully")
  354. return True
  355. else:
  356. print(f" - Warning: Could not install Web Interface Guidelines: {result.stderr}")
  357. print(" - Frontend supervisors will still work but WIG review enforcement may fail")
  358. print(" - Install manually: curl -fsSL https://vercel.com/design/guidelines/install | bash")
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 431 on GitHub
  359. return False
  360. print(" - Warning: Web Interface Guidelines installation not supported on Windows")
  361. return False
  362. # ============================================================================
  363. # AGENTS (TEMPLATE COPYING)
  364. # ============================================================================
  365. def copy_agents(project_dir: Path, project_name: str, claude_only: bool = False, with_kanban_ui: bool = False) -> list:
  366. """Copy core agent templates from templates/ directory.
  367. NOTE: Supervisors are NOT copied here - they are created dynamically
  368. by the discovery agent based on detected tech stack.
  369. """
  370. step = "[2/7]" if claude_only else "[2/8]"
  371. print(f"\n{step} Copying core agent templates...")
  372. agents_dir = project_dir / ".claude" / "agents"
  373. agents_dir.mkdir(parents=True, exist_ok=True)
  374. agents_template_dir = TEMPLATES_DIR / "agents"
  375. copied = []
  376. # Replacements for templates
  377. replacements = {
  378. "[Project]": project_name,
  379. }
  380. # Copy core agents ONLY (not supervisors)
  381. for agent_file in agents_template_dir.glob("*.md"):
  382. dest = agents_dir / agent_file.name
  383. copy_and_replace(agent_file, dest, replacements)
  384. copied.append(agent_file.name)
  385. print(f" - Copied {agent_file.name}")
  386. # Copy beads workflow injection snippet (used by discovery agent)
  387. # Select API version (with git fallback) or git-only version based on flag
  388. if with_kanban_ui:
  389. beads_workflow_src = TEMPLATES_DIR / "beads-workflow-injection-api.md"
  390. workflow_type = "API + git fallback"
  391. else:
  392. beads_workflow_src = TEMPLATES_DIR / "beads-workflow-injection-git.md"
  393. workflow_type = "git only"
  394. beads_workflow_dest = project_dir / ".claude" / "beads-workflow-injection.md"
  395. if beads_workflow_src.exists():
  396. shutil.copy2(beads_workflow_src, beads_workflow_dest)
  397. print(f" - Copied beads-workflow-injection.md ({workflow_type})")
  398. # Copy UI constraints (used by discovery agent for frontend supervisors)
  399. ui_constraints_src = TEMPLATES_DIR / "ui-constraints.md"
  400. ui_constraints_dest = project_dir / ".claude" / "ui-constraints.md"
  401. if ui_constraints_src.exists():
  402. shutil.copy2(ui_constraints_src, ui_constraints_dest)
  403. print(" - Copied ui-constraints.md")
  404. # Copy frontend reviews requirement (RAMS + Web Interface Guidelines)
  405. frontend_reviews_src = TEMPLATES_DIR / "frontend-reviews-requirement.md"
  406. frontend_reviews_dest = project_dir / ".claude" / "frontend-reviews-requirement.md"
  407. if frontend_reviews_src.exists():
  408. shutil.copy2(frontend_reviews_src, frontend_reviews_dest)
  409. print(" - Copied frontend-reviews-requirement.md")
  410. print(f" DONE: {len(copied)} core agents copied")
  411. print(" NOTE: Supervisors will be created by discovery agent based on tech stack")
  412. return copied
  413. # ============================================================================
  414. # SKILLS (TEMPLATE COPYING)
  415. # ============================================================================
  416. def copy_skills(project_dir: Path, claude_only: bool = False) -> list:
  417. """Copy skill templates from templates/ directory.
  418. Skills are copied so discovery agent can install them when tech stack is detected.
  419. """
  420. step = "[3/7]" if claude_only else "[3/8]"
  421. print(f"\n{step} Copying skill templates...")
  422. skills_template_dir = TEMPLATES_DIR / "skills"
  423. if not skills_template_dir.exists():
  424. print(" - No skill templates found, skipping")
  425. return []
  426. skills_dir = project_dir / ".claude" / "skills"
  427. skills_dir.mkdir(parents=True, exist_ok=True)
  428. copied = []
  429. for skill_dir in skills_template_dir.iterdir():
  430. if skill_dir.is_dir():
  431. dest_dir = skills_dir / skill_dir.name
  432. if dest_dir.exists():
  433. shutil.rmtree(dest_dir)
  434. shutil.copytree(skill_dir, dest_dir)
  435. copied.append(skill_dir.name)
  436. print(f" - Copied {skill_dir.name}/ skill")
  437. print(f" DONE: {len(copied)} skill templates copied")
  438. return copied
  439. # ============================================================================
  440. # HOOKS (TEMPLATE COPYING)
  441. # ============================================================================
  442. def copy_hooks(project_dir: Path, claude_only: bool = False) -> list:
  443. """Copy hook templates from templates/ directory.
  444. Args:
  445. project_dir: Target project directory
  446. claude_only: If True, skip provider delegation enforcement hooks
  447. """
  448. step = "[4/7]" if claude_only else "[4/8]"
  449. print(f"\n{step} Copying hook templates...")
  450. hooks_dir = project_dir / ".claude" / "hooks"
  451. hooks_dir.mkdir(parents=True, exist_ok=True)
  452. hooks_template_dir = TEMPLATES_DIR / "hooks"
  453. copied = []
  454. # Hooks to skip in claude-only mode (none currently - all hooks apply to both modes)
  455. skip_in_claude_only = set()
  456. for hook_file in hooks_template_dir.glob("*.sh"):
  457. # Skip provider enforcement hooks in claude-only mode
  458. if claude_only and hook_file.name in skip_in_claude_only:
  459. print(f" - Skipped {hook_file.name} (claude-only mode)")
  460. continue
  461. dest = hooks_dir / hook_file.name
  462. shutil.copy2(hook_file, dest)
  463. dest.chmod(dest.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
  464. copied.append(hook_file.name)
  465. print(f" - Copied {hook_file.name}")
  466. print(f" DONE: {len(copied)} hooks copied")
  467. return copied
  468. # ============================================================================
  469. # SETTINGS
  470. # ============================================================================
  471. def copy_settings(project_dir: Path, claude_only: bool = False) -> None:
  472. """Copy settings.json template, optionally removing provider enforcement hooks.
  473. Args:
  474. project_dir: Target project directory
  475. claude_only: If True, remove provider delegation enforcement from settings
  476. """
  477. step = "[5/7]" if claude_only else "[5/8]"
  478. print(f"\n{step} Copying settings...")
  479. settings_template = TEMPLATES_DIR / "settings.json"
  480. settings_dest = project_dir / ".claude" / "settings.json"
  481. # Settings are the same for both modes now (no provider-specific hooks)
  482. shutil.copy2(settings_template, settings_dest)
  483. if claude_only:
  484. print(" - Copied settings.json (claude-only mode)")
  485. else:
  486. print(" - Copied settings.json")
  487. print(" DONE: settings configured")
  488. # ============================================================================
  489. # CLAUDE.MD
  490. # ============================================================================
  491. def copy_claude_md(project_dir: Path, project_name: str, claude_only: bool = False) -> None:
  492. """Copy CLAUDE.md template with project name replacement."""
  493. step = "[6/7]" if claude_only else "[6/8]"
  494. print(f"\n{step} Copying CLAUDE.md...")
  495. claude_template = TEMPLATES_DIR / "CLAUDE.md"
  496. claude_dest = project_dir / "CLAUDE.md"
  497. replacements = {"[Project]": project_name}
  498. copy_and_replace(claude_template, claude_dest, replacements)
  499. print(" - Copied CLAUDE.md")
  500. print(" DONE: CLAUDE.md copied")
  501. # ============================================================================
  502. # GITIGNORE
  503. # ============================================================================
  504. def setup_gitignore(project_dir: Path, claude_only: bool = False) -> None:
  505. """Ensure .beads is in .gitignore. .claude/ is tracked (not ignored)."""
  506. step = "[7/7]" if claude_only else "[7/8]"
  507. print(f"\n{step} Setting up .gitignore...")
  508. gitignore_path = project_dir / ".gitignore"
  509. # Only ignore .beads/ (ephemeral task data) and .mcp.json (user-specific paths)
  510. # .claude/ is tracked so it survives git operations
  511. entries_to_add = [".beads/", ".mcp.json"]
  512. if gitignore_path.exists():
  513. content = gitignore_path.read_text()
  514. lines = content.splitlines()
  515. # Check which entries are missing
  516. missing = []
  517. for entry in entries_to_add:
  518. # Check for exact match or without trailing slash
  519. entry_no_slash = entry.rstrip("/")
  520. if entry not in lines and entry_no_slash not in lines:
  521. missing.append(entry)
  522. if missing:
  523. # Append missing entries
  524. with open(gitignore_path, "a") as f:
  525. # Add newline if file doesn't end with one
  526. if content and not content.endswith("\n"):
  527. f.write("\n")
  528. f.write("\n# Beads task tracking (ephemeral)\n")
  529. for entry in missing:
  530. f.write(f"{entry}\n")
  531. print(f" - Added {entry} to .gitignore")
  532. else:
  533. print(" - .beads/ and .mcp.json already in .gitignore")
  534. else:
  535. # Create new .gitignore
  536. content = """# Beads task tracking (ephemeral)
  537. .beads/
  538. # MCP config (user-specific paths)
  539. .mcp.json
  540. """
  541. gitignore_path.write_text(content)
  542. print(" - Created .gitignore with .beads/ and .mcp.json")
  543. print(" DONE: .gitignore configured")
  544. print(" NOTE: .claude/ is tracked (not ignored) to prevent accidental loss")
  545. # ============================================================================
  546. # MCP CONFIG
  547. # ============================================================================
  548. def create_mcp_config(project_dir: Path, venv_python: Path) -> None:
  549. """Add provider-delegator to .mcp.json, preserving existing servers."""
  550. print("\n[8/8] Configuring MCP...")
  551. mcp_dest = project_dir / ".mcp.json"
  552. # Load existing config or start fresh
  553. if mcp_dest.exists():
  554. try:
  555. existing = json.loads(mcp_dest.read_text())
  556. print(" - Found existing .mcp.json, merging...")
  557. except json.JSONDecodeError:
  558. print(" - Warning: Invalid .mcp.json, creating new one")
  559. existing = {}
  560. else:
  561. existing = {}
  562. # Ensure mcpServers key exists
  563. if "mcpServers" not in existing:
  564. existing["mcpServers"] = {}
  565. # Add/update provider_delegator
  566. existing["mcpServers"]["provider_delegator"] = {
  567. "type": "stdio",
  568. "command": str(venv_python),
  569. "args": ["-m", "mcp_provider_delegator.server"],
  570. "env": {
  571. "AGENT_TEMPLATES_PATH": ".claude/agents"
  572. }
  573. }
  574. mcp_dest.write_text(json.dumps(existing, indent=2))
  575. server_count = len(existing["mcpServers"])
  576. print(f" - Added provider-delegator to .mcp.json ({server_count} total servers)")
  577. print(f" Command: {venv_python}")
  578. print(f" Agents: .claude/agents (relative)")
  579. print(" DONE: MCP config updated")
  580. # ============================================================================
  581. # VERIFICATION
  582. # ============================================================================
  583. def verify_installation(project_dir: Path, claude_only: bool = False) -> bool:
  584. """Verify all components were installed correctly."""
  585. checks = {
  586. ".claude/hooks": "Hooks directory",
  587. ".claude/agents": "Agents directory",
  588. ".claude/settings.json": "Settings file",
  589. ".beads": "Beads directory",
  590. "CLAUDE.md": "CLAUDE.md",
  591. ".gitignore": ".gitignore",
  592. }
  593. # Only check for .mcp.json in external providers mode
  594. if not claude_only:
  595. checks[".mcp.json"] = "MCP config"
  596. print("\n=== Verification ===")
  597. all_good = True
  598. for path, description in checks.items():
  599. full_path = project_dir / path
  600. if full_path.exists():
  601. print(f" - {description}")
  602. else:
  603. print(f" X {description} MISSING")
  604. all_good = False
  605. # Count files
  606. hooks_dir = project_dir / ".claude/hooks"
  607. if hooks_dir.exists():
  608. hook_count = len(list(hooks_dir.glob("*.sh")))
  609. print(f" - Hooks: {hook_count}")
  610. agents_dir = project_dir / ".claude/agents"
  611. if agents_dir.exists():
  612. agent_count = len(list(agents_dir.glob("*.md")))
  613. print(f" - Agents: {agent_count}")
  614. skills_dir = project_dir / ".claude/skills"
  615. if skills_dir.exists():
  616. skill_count = len(list(skills_dir.iterdir()))
  617. if skill_count > 0:
  618. print(f" - Skills: {skill_count}")
  619. return all_good
  620. # ============================================================================
  621. # MAIN
  622. # ============================================================================
  623. def main():
  624. import argparse
  625. parser = argparse.ArgumentParser(description="Bootstrap beads-based orchestration")
  626. parser.add_argument("--project-name", default=None, help="Project name (auto-inferred if not provided)")
  627. parser.add_argument("--project-dir", default=".", help="Project directory")
  628. parser.add_argument("--external-providers", action="store_true",
  629. help="Use Codex/Gemini for delegation (default: Claude-only)")
  630. parser.add_argument("--with-kanban-ui", action="store_true",
  631. help="Use Beads Kanban UI API for worktree creation (with git fallback)")
  632. args = parser.parse_args()
  633. project_dir = Path(args.project_dir).resolve()
  634. claude_only = not args.external_providers # Default is now claude-only
  635. with_kanban_ui = args.with_kanban_ui
  636. # Ensure project directory exists
  637. project_dir.mkdir(parents=True, exist_ok=True)
  638. # Auto-infer project name if not provided
  639. if args.project_name:
  640. project_name = args.project_name
  641. else:
  642. project_name = infer_project_name(project_dir)
  643. print(f"Auto-inferred project name: {project_name}")
  644. mode_str = "CLAUDE-ONLY" if claude_only else "EXTERNAL PROVIDERS"
  645. worktree_str = "API + git fallback" if with_kanban_ui else "git only"
  646. print(f"\nBootstrapping beads orchestration for: {project_name}")
  647. print(f"Directory: {project_dir}")
  648. print(f"Mode: {mode_str}")
  649. print(f"Worktrees: {worktree_str}")
  650. print("=" * 60)
  651. # Verify templates exist
  652. if not TEMPLATES_DIR.exists():
  653. print(f"\nERROR: Templates directory not found: {TEMPLATES_DIR}")
  654. print("Make sure you cloned the full lean-orchestration repo")
  655. sys.exit(1)
  656. venv_python = None
  657. # Step 0: Setup bundled provider-delegator (skip in claude-only mode)
  658. if not claude_only:
  659. venv_python = setup_provider_delegator()
  660. if not venv_python:
  661. print("\nERROR: Failed to setup provider-delegator. Aborting.")
  662. sys.exit(1)
  663. # Run remaining steps with provider support
  664. if not install_beads(project_dir, claude_only=False):
  665. print("\nERROR: Beads CLI is required. Aborting bootstrap.")
  666. sys.exit(1)
  667. # Install frontend review tools (optional, won't block)
  668. install_rams()
  669. install_web_interface_guidelines()
  670. copy_agents(project_dir, project_name, claude_only=False, with_kanban_ui=with_kanban_ui)
  671. copy_skills(project_dir, claude_only=False)
  672. copy_hooks(project_dir, claude_only=False)
  673. copy_settings(project_dir, claude_only=False)
  674. copy_claude_md(project_dir, project_name, claude_only=False)
  675. setup_memory(project_dir)
  676. setup_gitignore(project_dir, claude_only=False)
  677. create_mcp_config(project_dir, venv_python)
  678. else:
  679. # Claude-only mode: skip provider setup
  680. print("\n[0/7] Skipping provider-delegator setup (claude-only mode)")
  681. if not install_beads(project_dir, claude_only=True):
  682. print("\nERROR: Beads CLI is required. Aborting bootstrap.")
  683. sys.exit(1)
  684. # Install frontend review tools (optional, won't block)
  685. install_rams()
  686. install_web_interface_guidelines()
  687. copy_agents(project_dir, project_name, claude_only=True, with_kanban_ui=with_kanban_ui)
  688. copy_skills(project_dir, claude_only=True)
  689. copy_hooks(project_dir, claude_only=True)
  690. copy_settings(project_dir, claude_only=True)
  691. copy_claude_md(project_dir, project_name, claude_only=True)
  692. setup_memory(project_dir)
  693. setup_gitignore(project_dir, claude_only=True)
  694. # Verify
  695. if not verify_installation(project_dir, claude_only):
  696. print("\nWARNING: Installation incomplete - check errors above")
  697. print("\n" + "=" * 60)
  698. print("BOOTSTRAP COMPLETE")
  699. print("=" * 60)
  700. if claude_only:
  701. print(f"""
  702. Mode: CLAUDE-ONLY (all agents use Claude Task)
  703. Next steps:
  704. 1. Restart Claude Code to load new hooks and agents
  705. 2. **REQUIRED: Run discovery to create supervisors**
  706. Discovery will scan your codebase and fetch specialist agents:
  707. Task(
  708. subagent_type="discovery",
  709. prompt="Detect tech stack and create supervisors for {project_name}"
  710. )
  711. 3. Create your first bead:
  712. bd create "First task"
  713. 4. Dispatch work to supervisors:
  714. Task(subagent_type="<supervisor-name>", prompt="BEAD_ID: BD-001\\n\\nImplement...")
  715. NOTE: All agents (scout, detective, architect, etc.) run via Claude Task().
  716. No external providers (Codex/Gemini) are configured.
  717. """)
  718. else:
  719. print(f"""
  720. Mode: EXTERNAL PROVIDERS (Codex → Gemini → Claude fallback)
  721. Next steps:
  722. 1. Restart Claude Code to load new hooks and agents
  723. 2. **REQUIRED: Run discovery to create supervisors**
  724. Discovery will scan your codebase and fetch specialist agents:
  725. Task(
  726. subagent_type="discovery",
  727. prompt="Detect tech stack and create supervisors for {project_name}"
  728. )
  729. This will:
  730. - Scan package.json, requirements.txt, Dockerfile, etc.
  731. - Fetch matching specialists from external agents directory
  732. - Inject beads workflow at the beginning of each agent
  733. - Write supervisors to .claude/agents/
  734. 3. Create your first bead:
  735. bd create "First task"
  736. 4. Dispatch work to supervisors:
  737. Task(subagent_type="<supervisor-name>", prompt="BEAD_ID: BD-001\\n\\nImplement...")
  738. NOTE: Read-only agents (scout, detective, architect, scribe, code-reviewer)
  739. are delegated via provider_delegator MCP (Codex → Gemini fallback).
  740. Supervisors are sourced from https://github.com/ayush-that/sub-agents.directory
  741. with beads workflow injected.
  742. """)
  743. if __name__ == "__main__":
  744. main()

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.