diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index c9f4853..8026206 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -8,7 +8,7 @@ "name": "workflow-orchestrator", "source": "./", "description": "Delegation system with workflow orchestration, specialized agents, and parallel execution for Claude Code", - "version": "1.15.1", + "version": "1.16.0", "author": { "name": "Nadav Barkai" }, diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index d9fa1e4..3a38f0c 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "workflow-orchestrator", - "version": "1.15.1", + "version": "1.16.0", "description": "Delegation system with workflow orchestration, specialized agents, and parallel execution for Claude Code", "author": { "name": "Nadav Barkai" diff --git a/CHANGELOG.md b/CHANGELOG.md index b098fe1..af8ab23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ All notable changes to this project will be documented in this file. +## [1.16.0] - 2026-04-06 + +### Fixed +- **Session cost from stdin**: Replaced all daily cost self-calculation (JSONL scanning, background refresh, cost cache) with simple `cost.total_cost_usd` read from stdin JSON -- zero I/O, real-time session cost +- **Delegation hook subagent deadlock**: Expanded subagent bypass to check `CLAUDE_AGENT_ID` and `CLAUDE_SCRATCHPAD_DIR` in addition to `CLAUDE_PARENT_SESSION_ID`; added redundant safety net inside `main()`; normalized `CLAUDE_PROJECT_DIR` path resolution with `Path.resolve()` +- **`/delegate` plugin prefix**: Fixed all references to use full plugin prefix `/workflow-orchestrator:delegate` + +### Removed +- **`skills/breadth-reader/`**: Removed breadth-reader skill directory and all references +- `_find_todays_session_files()`, `_sum_session_cost()`, `_cost_from_usage()`, `fetch_costs_raw()`, `spawn_background_refresh()`, `load_cost_cache()`, `save_cost_cache()`, `is_cache_valid()`, `_is_refresh_locked()` -- all replaced by stdin session cost +- Cost cache constants (`COST_CACHE_FILE`, `COST_CACHE_TTL_SECONDS`, `COST_REFRESH_LOCK`) and lock file logic +- `time` import (no longer needed) + ## [1.15.1] - 2026-04-04 ### Fixed diff --git a/CLAUDE.md b/CLAUDE.md index 5135960..6b469fd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co When ANY tool is blocked by the delegation policy hook: 1. **DO NOT try alternative approaches** - just delegate immediately -2. **IMMEDIATELY use `/delegate `** on first tool block +2. **IMMEDIATELY use `/workflow-orchestrator:delegate `** on first tool block 3. **The entire user request must be delegated**, not just the blocked tool ### Recognition Pattern @@ -21,8 +21,8 @@ Error: PreToolUse:* hook error: [...] Tool blocked by delegation policy Tool: STOP: Do NOT try alternative tools. -REQUIRED: Use /delegate command immediately: - /delegate +REQUIRED: Use /workflow-orchestrator:delegate command immediately: + /workflow-orchestrator:delegate ``` First tool block = immediate delegation. Don't try alternatives, don't explain — just delegate. @@ -60,18 +60,17 @@ CI workflow exists (`.github/workflows/ci.yml`) but tests are currently disabled ## Available Commands ```bash -/delegate # Plan and execute task via native plan mode -/ask # Read-only question answering (forked context) -/bypass # Toggle delegation enforcement on/off (persists until toggled) -/add-statusline # Enable workflow status display -/breadth-reader # Read-only breadth tasks (explore, review, summarize) +/workflow-orchestrator:delegate # Plan and execute task via native plan mode +/workflow-orchestrator:ask # Read-only question answering (forked context) +/workflow-orchestrator:bypass # Toggle delegation enforcement on/off (persists until toggled) +/workflow-orchestrator:add-statusline # Enable workflow status display ``` **Installation:** - Plugin: `claude plugin install workflow-orchestrator@barkain-plugins` - Manual: `./install.sh [--scope=user|project]` -In plugin mode, agent/skill names use prefix `workflow-orchestrator:` (e.g., `workflow-orchestrator:task-completion-verifier`). +In plugin mode, all commands and agent names use the `workflow-orchestrator:` prefix. --- @@ -115,7 +114,7 @@ User prompt | **PreToolUse** (`*`, `Bash`) | `validate_task_graph_compliance.py`, `require_delegation.py`, `token_rewrite_hook.py` (Bash only) | Validate Agent/Task invocations against active task graph; block non-allowed tools (compressed error messages); rewrite Bash commands for token efficiency (cd && pattern, eslint, next, tsc) | | **PostToolUse** | `python_posttooluse_hook.py` (Edit/Write/MultiEdit), `remind_skill_continuation.py` (ExitPlanMode\|Skill\|SlashCommand), `validate_task_graph_depth.py` + `remind_todo_after_task.py` (Agent/Task) | Python validation (Ruff, Pyright, security), workflow continuation state (triggers on ExitPlanMode for plan mode flows), depth-3 enforcement, task reminders | | **UserPromptSubmit** | `clear-delegation-sessions.py` | Clear delegation state, record turn start timestamp, clear team state (`team_mode_active`, `team_config.json`), rotate logs | -| **SessionStart** (`startup\|resume\|clear\|compact`) | `inject_workflow_orchestrator.py`, `inject-output-style.py`, `inject_token_efficiency.py` | Inject conditional orchestrator (stub on startup, full on /delegate), output style, token efficiency guidance | +| **SessionStart** (`startup\|resume\|clear\|compact`) | `inject_workflow_orchestrator.py`, `inject-output-style.py`, `inject_token_efficiency.py` | Inject conditional orchestrator (stub on startup, full on /workflow-orchestrator:delegate), output style, token efficiency guidance | | **SubagentStop** (`*`) | `remind_todo_update.py` (async), `trigger_verification.py` | Remind to update tasks, suggest verification | | **Stop** | `python_stop_hook.py` | Turn duration, workflow continuation (block stop + inject "continue"), quality analysis | @@ -140,15 +139,11 @@ Special cases: | Mechanism | How | Scope | |-----------|-----|-------| | Env var | `DELEGATION_HOOK_DISABLE=1` | Session-wide | -| `/bypass` command | Creates `.claude/state/delegation_disabled` | Persists until toggled | +| `/workflow-orchestrator:bypass` command | Creates `.claude/state/delegation_disabled` | Persists until toggled | | Subagent auto-bypass | `CLAUDE_PARENT_SESSION_ID` set | Automatic for subagents | | Delegation active flag | `.claude/state/delegation_active` created on Skill/Agent/Task use | Per-delegation | -### Skills (forked context) - -- **breadth-reader** (`skills/breadth-reader/SKILL.md`): Lightweight read-only breadth tasks. Spawns `Explore` subagents (Haiku). Returns summary only. - -**Note:** The `task-planner` skill has been removed. Its orchestration and planning functionality is now provided by native plan mode (EnterPlanMode/ExitPlanMode), which handles both planning and execution orchestration directly within the main agent context. +**Note:** The `task-planner` and `breadth-reader` skills have been removed. Planning and orchestration are provided by native plan mode (EnterPlanMode/ExitPlanMode). Read-only breadth tasks are handled by spawning parallel Explore agents or the codebase-context-analyzer directly. ### Specialized Agents (8) diff --git a/README.md b/README.md index 81228fc..06997f7 100644 --- a/README.md +++ b/README.md @@ -206,10 +206,10 @@ Temporarily disable delegation enforcement if needed: export DELEGATION_HOOK_DISABLE=1 # From within a Claude Code session (interactive toggle) -/bypass +/workflow-orchestrator:bypass ``` -The `/bypass` command allows toggling delegation enforcement on/off from within a Claude Code session without restarting. +The `/workflow-orchestrator:bypass` command allows toggling delegation enforcement on/off from within a Claude Code session without restarting. ## Environment Variables @@ -259,7 +259,7 @@ The `plugin-hooks.json` configures the delegation enforcement hooks using cross- | **PreToolUse** | `validate_task_graph_compliance.py`, `require_delegation.py`, `token_rewrite_hook.py` (Bash only) | Validate task graph compliance; block non-delegated tools; rewrite Bash commands for token efficiency (cd && pattern, eslint, next, tsc support) | | **PostToolUse** | `python_posttooluse_hook.py` (Edit/Write), `remind_skill_continuation.py` (ExitPlanMode/Skill/SlashCommand), `validate_task_graph_depth.py` (Agent/Task), `remind_todo_after_task.py` (Agent/Task, async) | Python validation (Ruff/Pyright); workflow continuation state; depth-3 enforcement; task reminders | | **UserPromptSubmit** | `clear-delegation-sessions.py` | Clear delegation/team state, record turn timestamp | -| **SessionStart** | `inject_workflow_orchestrator.py`, `inject-output-style.py`, `inject_token_efficiency.py` | Inject conditional orchestrator (stub on startup, full on /delegate), output style, token efficiency guidance | +| **SessionStart** | `inject_workflow_orchestrator.py`, `inject-output-style.py`, `inject_token_efficiency.py` | Inject conditional orchestrator (stub on startup, full on /workflow-orchestrator:delegate), output style, token efficiency guidance | | **SubagentStop** | `remind_todo_update.py` (async), `trigger_verification.py` | Remind to update tasks, suggest verification | | **Stop** | `python_stop_hook.py` | Turn duration tracking, workflow continuation | @@ -270,8 +270,8 @@ Multi-step workflow orchestration requires the workflow_orchestrator system prom **Automatic (via SessionStart hook):** The `inject_workflow_orchestrator.py` hook uses conditional injection: -- **On startup/resume:** Injects a lightweight stub that registers `/delegate` and `/bypass` commands without loading the full orchestrator prompt, keeping baseline token overhead minimal. -- **On `/delegate` invocation:** The full `workflow_orchestrator.md` system prompt is loaded on-demand, providing the complete planning and execution logic only when needed. +- **On startup/resume:** Injects a lightweight stub that registers `/workflow-orchestrator:delegate` and `/workflow-orchestrator:bypass` commands without loading the full orchestrator prompt, keeping baseline token overhead minimal. +- **On `/workflow-orchestrator:delegate` invocation:** The full `workflow_orchestrator.md` system prompt is loaded on-demand, providing the complete planning and execution logic only when needed. **What this enables:** - Multi-step task detection via pattern matching @@ -290,7 +290,7 @@ Blocks most tools and forces delegation to specialized agents. Cross-platform Py **Allowed tools:** - `AskUserQuestion` - Ask users for clarification - `TaskCreate`, `TaskUpdate`, `TaskList`, `TaskGet` - Track task progress with structured metadata -- `Skill`, `SlashCommand` - Execute slash commands (including `/delegate`) +- `Skill`, `SlashCommand` - Execute slash commands (including `/workflow-orchestrator:delegate`) - `Agent`, `SubagentTask`, `AgentTask` - Spawn subagents **Note:** `TaskOutput` is prohibited to prevent context exhaustion. Agents write to `$CLAUDE_SCRATCHPAD_DIR` and return `DONE|{path}` only. @@ -298,7 +298,7 @@ Blocks most tools and forces delegation to specialized agents. Cross-platform Py **All other tools are blocked** and show: ``` 🚫 Tool blocked by delegation policy -✅ REQUIRED: Use /delegate command immediately +✅ REQUIRED: Use /workflow-orchestrator:delegate command immediately ``` ### 2. Specialized Agents (`agents/`) @@ -316,25 +316,12 @@ Blocks most tools and forces delegation to specialized agents. Cross-platform Py **Note:** The `delegation-orchestrator` agent has been deprecated. Its orchestration and routing functionality is now provided by native plan mode (EnterPlanMode/ExitPlanMode), which handles both planning and execution orchestration directly within the main agent. -### 3. Breadth Reader Skill (`skills/breadth-reader/`) +### 3. Delegation Command (`commands/delegate.md`) -For read-only breadth tasks (explore, review, summarize), the `breadth-reader` skill provides optimized handling: +The `/workflow-orchestrator:delegate` command provides intelligent task delegation with integrated planning: ```bash -/breadth-reader explore ~/dev/project/ -``` - -- Runs in forked context (isolated from main agent) -- Claude auto-optimizes parallelism internally -- Returns summary only to main agent -- No orchestration overhead - -### 4. Delegation Command (`commands/delegate.md`) - -The `/delegate` command provides intelligent task delegation with integrated planning: - -```bash -/delegate +/workflow-orchestrator:delegate ``` **How it works:** @@ -346,7 +333,7 @@ The `/delegate` command provides intelligent task delegation with integrated pla 6. Creates task list via TaskCreate 7. Exits plan mode (ExitPlanMode) and executes phases as directed by the plan -### 5. Workflow Orchestration System Prompt (`system-prompts/workflow_orchestrator.md`) +### 4. Workflow Orchestration System Prompt (`system-prompts/workflow_orchestrator.md`) Enables multi-step workflow detection and preparation for complex tasks. Works in conjunction with native plan mode (EnterPlanMode/ExitPlanMode). @@ -508,7 +495,7 @@ The framework minimizes command output to reduce context consumption and preserv 3. **Conditional System Prompt Injection** — The orchestrator is injected conditionally: - On session startup: Stub version (~200 tokens) provides minimal direction - - On first plan mode entry (via /delegate or detected multi-step): Full version (~11K tokens) for complete planning capability + - On first plan mode entry (via /workflow-orchestrator:delegate or detected multi-step): Full version (~11K tokens) for complete planning capability - Saves tokens for single-step and read-only tasks ### Disable Token Efficiency diff --git a/commands/delegate.md b/commands/delegate.md index 7f4902d..e27a983 100644 --- a/commands/delegate.md +++ b/commands/delegate.md @@ -30,7 +30,7 @@ Multi-step workflow orchestration for Claude Code. Main agent enters plan mode ( **Write indicators:** create, write, save, generate, produce, output, report, build, make, implement, fix, update -**If ANY write indicator found -> Continue to Step 2 (don't use breadth-reader)** +**If ANY write indicator found -> Continue to Step 2** ### Step 2: Breadth Task Detection @@ -44,7 +44,7 @@ Multi-step workflow orchestration for Claude Code. Main agent enters plan mode ( |---------|-------|---------| | Breadth + Write (same op x many items, with output) | **DIRECT EXECUTION** (skip plan mode) | "review 16 files, create reports" | | Multi-phase workflow (create -> test -> deploy) | plan mode (EnterPlanMode) | "create calculator with tests and verify" | -| Read-only breadth (no write indicators) | `/breadth-reader {prompt}` | "explore code in X", "summarize files in X" | +| Read-only breadth (no write indicators) | Spawn parallel Explore agents or codebase-context-analyzer | "explore code in X", "summarize files in X" | | Single simple task | general-purpose agent | "fix this bug" | **This four-step check is MANDATORY and must happen FIRST before any other action.** diff --git a/docs/ARCHITECTURE_PHILOSOPHY.md b/docs/ARCHITECTURE_PHILOSOPHY.md index 3f62e67..04bacd4 100644 --- a/docs/ARCHITECTURE_PHILOSOPHY.md +++ b/docs/ARCHITECTURE_PHILOSOPHY.md @@ -91,7 +91,7 @@ Each specialized agent has a restricted tool set that matches its domain: | All other tools: BLOCKED | +-------------------------------------------------------------------+ | - /delegate + /workflow-orchestrator:delegate | +-------------------------------------------------------------------+ | DELEGATION BOUNDARY | @@ -361,11 +361,11 @@ The system uses a 3-step routing check before planning: | Step 1: Write Detection | | - Does task require file modifications (Write/Edit)? | | - YES → Continue to Step 2 | -| - NO → Route to breadth-reader skill (read-only) | +| - NO → Spawn parallel Explore agents or codebase-context-analyzer| | | | Step 2: Breadth Task Detection | | - Is this a breadth task (analyze many files)? | -| - YES → Route to breadth-reader skill | +| - YES → Spawn parallel Explore agents | | - NO → Continue to Step 3 | | | | Step 3: Route Decision | @@ -445,7 +445,6 @@ return max(candidates, key=lambda a: a.match_count) | Agent | Keywords | Tool Access | Use Case | |-------|----------|-------------|----------| -| breadth-reader (skill) | analyze, explore, read-only | Read, Glob, Grep | Breadth tasks (many files) | | codebase-context-analyzer | analyze, understand, explore, architecture | Read, Glob, Grep, Bash | Code exploration | | tech-lead-architect | design, approach, research, best practices | Read, Write, Edit, Glob, Grep, Bash | Solution design | | task-completion-verifier | verify, validate, test, check, review | Read, Bash, Glob, Grep | QA and validation | @@ -521,7 +520,7 @@ sess_def456 ``` **Lifecycle:** -1. Created when first `/delegate` triggers session registration +1. Created when first `/workflow-orchestrator:delegate` triggers session registration 2. Populated with session IDs on each delegation 3. Cleared by UserPromptSubmit hook before each user prompt 4. Cleaned of stale sessions (>1 hour) by Stop hook @@ -782,8 +781,9 @@ Delegation privileges automatically decay: +-------------------------------------------------------------------------+ | USER INTERFACE | -| Commands: /delegate, /ask, /bypass, /add-statusline | -| Skills: breadth-reader | Planning: native plan mode | +| Commands: /workflow-orchestrator:delegate, /workflow-orchestrator:ask, | +| /workflow-orchestrator:bypass, /workflow-orchestrator:add-statusline | +| Planning: native plan mode | | StatusLine: [MODE] Active: N Wave W | Last: Event | +-------------------------------------------------------------------------+ | @@ -813,10 +813,6 @@ Delegation privileges automatically decay: | | Intent Parsing -> Decomposition -> Agent Selection -> Waves | | | +-------------------------------------------------------------------+ | | +-------------------------------------------------------------------+ | -| | breadth-reader (skill) | | -| | Read-only analysis for breadth tasks (many files) | | -| +-------------------------------------------------------------------+ | -| +-------------------------------------------------------------------+ | | | workflow_orchestrator (system prompt) | | | | Batched Execution -> Scratchpad Context -> Verification | | | +-------------------------------------------------------------------+ | diff --git a/docs/ARCHITECTURE_QUICK_REFERENCE.md b/docs/ARCHITECTURE_QUICK_REFERENCE.md index 579b6ec..a39e5b0 100644 --- a/docs/ARCHITECTURE_QUICK_REFERENCE.md +++ b/docs/ARCHITECTURE_QUICK_REFERENCE.md @@ -19,25 +19,25 @@ ## Decision Trees -### Should I Use /delegate? +### Should I Use /workflow-orchestrator:delegate? ``` Is the task blocked by PreToolUse hook? -├── YES → Use /delegate immediately +├── YES → Use /workflow-orchestrator:delegate immediately │ Do NOT try alternative tools │ └── NO → 3-Step Routing Check: │ Step 1: Does task require Write/Edit? - ├── NO → Use breadth-reader skill (read-only) + ├── NO → Use /workflow-orchestrator:delegate (spawns Explore agents or codebase-context-analyzer) │ └── YES → Step 2: Is this a breadth task (many files)? - ├── YES → Use breadth-reader skill + ├── YES → Use /workflow-orchestrator:delegate (parallel Explore agents) │ └── NO → Step 3: Is task simple? ├── YES → DIRECT EXECUTION (bypass plan mode) │ - └── NO → Use /delegate for complex tasks + └── NO → Use /workflow-orchestrator:delegate for complex tasks ``` ### Which Agent Will Handle My Task? @@ -159,7 +159,6 @@ ALL criteria met? | Agent | Read | Write | Edit | Bash | Agent | Glob | Grep | |-------|:----:|:-----:|:----:|:----:|:----:|:----:|:----:| -| breadth-reader (skill) | Y | - | - | - | - | Y | Y | | codebase-context-analyzer | Y | - | - | Y | - | Y | Y | | tech-lead-architect | Y | Y | Y | Y | - | Y | Y | | task-completion-verifier | Y | - | - | Y | - | Y | Y | @@ -439,7 +438,7 @@ rm -f .claude/state/team_mode_active .claude/state/team_config.json ### Tools Not Working - [ ] Is session registered? Check `.claude/state/delegated_sessions.txt` -- [ ] Was `/delegate` used? Use it immediately when blocked +- [ ] Was `/workflow-orchestrator:delegate` used? Use it immediately when blocked - [ ] Are hooks installed? Check `ls -la ~/.claude/hooks/*/` - [ ] Are hooks executable? Run `chmod +x ~/.claude/hooks/*/*.sh` - [ ] Check hook syntax: `bash -n ` @@ -511,10 +510,10 @@ rm -f .claude/state/team_mode_active .claude/state/team_config.json ```bash # Single task -/delegate Create a calculator.py with add and subtract functions +/workflow-orchestrator:delegate Create a calculator.py with add and subtract functions # Read-only question -/ask How does the authentication system work? +/workflow-orchestrator:ask How does the authentication system work? ``` ### Multi-Step Workflow @@ -532,7 +531,7 @@ claude --append-system-prompt "$(cat ~/.claude/system-prompts/workflow_orchestra export DEBUG_DELEGATION_HOOK=1 # Run delegation -/delegate Create test.py +/workflow-orchestrator:delegate Create test.py # Watch logs (separate terminal) tail -f /tmp/delegation_hook_debug.log diff --git a/docs/README.md b/docs/README.md index 8b48efc..bbb0b99 100644 --- a/docs/README.md +++ b/docs/README.md @@ -114,8 +114,8 @@ docs/ ### Commands ```bash -/delegate # Route task to specialized agent -/ask # Read-only question answering +/workflow-orchestrator:delegate # Route task to specialized agent +/workflow-orchestrator:ask # Read-only question answering ``` ### Debug Commands diff --git a/docs/environment-variables.md b/docs/environment-variables.md index c7a9740..8bd1585 100644 --- a/docs/environment-variables.md +++ b/docs/environment-variables.md @@ -79,7 +79,7 @@ The system uses Claude Code's native Tasks API for progress tracking. This secti export CLAUDE_CODE_ENABLE_TASKS=false # Run workflow (will use TodoWrite) -/delegate "Create calculator.py" +/workflow-orchestrator:delegate "Create calculator.py" # Re-enable Tasks API export CLAUDE_CODE_ENABLE_TASKS=true @@ -138,7 +138,7 @@ claude "Create part B" export CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 # Run workflow (no background reminders or cleanup) -/delegate "Long-running task" +/workflow-orchestrator:delegate "Long-running task" # Re-enable background tasks unset CLAUDE_CODE_DISABLE_BACKGROUND_TASKS @@ -172,7 +172,7 @@ unset CLAUDE_CODE_DISABLE_BACKGROUND_TASKS export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 # Run a collaborative workflow (planning phase may select team mode) -/delegate "Build auth module with API and tests collaboratively" +/workflow-orchestrator:delegate "Build auth module with API and tests collaboratively" # Disable Agent Teams mode export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=0 @@ -242,7 +242,7 @@ Enables detailed debug logging for delegation policy enforcement. When enabled, export DEBUG_DELEGATION_HOOK=1 # Run delegation workflow -/delegate "Create calculator.py" +/workflow-orchestrator:delegate "Create calculator.py" # Tail debug log in another terminal tail -f /tmp/delegation_hook_debug.log @@ -307,7 +307,7 @@ mv /tmp/delegation_hook_debug.log /tmp/delegation_hook_debug.$(date +%Y%m%d).log ### Purpose -Emergency bypass to completely disable delegation enforcement. When enabled, all tools are allowed without requiring `/delegate`. +Emergency bypass to completely disable delegation enforcement. When enabled, all tools are allowed without requiring `/workflow-orchestrator:delegate`. ### Values @@ -320,7 +320,7 @@ Emergency bypass to completely disable delegation enforcement. When enabled, all # Emergency bypass (disable delegation enforcement) export DELEGATION_HOOK_DISABLE=1 -# Use tools directly without /delegate +# Use tools directly without /workflow-orchestrator:delegate claude "Create calculator.py" # Re-enable delegation enforcement @@ -401,7 +401,7 @@ Override the project directory for state file storage. By default, state files a export CLAUDE_PROJECT_DIR=/Users/user/my-project # State files written to /Users/user/my-project/.claude/state/ -/delegate "Create calculator.py" +/workflow-orchestrator:delegate "Create calculator.py" # Verify state location ls -la /Users/user/my-project/.claude/state/ @@ -426,11 +426,11 @@ Without `CLAUDE_PROJECT_DIR`, state follows the current directory: ```bash # Without CLAUDE_PROJECT_DIR cd /Users/user/project-a -/delegate "Task A" +/workflow-orchestrator:delegate "Task A" # State: /Users/user/project-a/.claude/state/ cd /Users/user/project-b -/delegate "Task B" +/workflow-orchestrator:delegate "Task B" # State: /Users/user/project-b/.claude/state/ ``` @@ -443,11 +443,11 @@ With `CLAUDE_PROJECT_DIR`, state is centralized: export CLAUDE_PROJECT_DIR=/Users/user/main-project cd /Users/user/project-a -/delegate "Task A" +/workflow-orchestrator:delegate "Task A" # State: /Users/user/main-project/.claude/state/ cd /Users/user/project-b -/delegate "Task B" +/workflow-orchestrator:delegate "Task B" # State: /Users/user/main-project/.claude/state/ (same location) ``` @@ -488,7 +488,7 @@ Controls the maximum number of parallel agents that can run simultaneously durin export CLAUDE_MAX_CONCURRENT=4 # Run workflow - waves batch at 4 agents max -/delegate "Review all documentation" +/workflow-orchestrator:delegate "Review all documentation" # Increase concurrency for powerful machines export CLAUDE_MAX_CONCURRENT=12 @@ -660,7 +660,7 @@ export CLAUDE_PROJECT_DIR=$PWD # Current directory tail -f /tmp/delegation_hook_debug.log & # Run problematic workflow -/delegate "Task that's failing" +/workflow-orchestrator:delegate "Task that's failing" # Check state files cat .claude/state/delegated_sessions.txt @@ -683,7 +683,7 @@ export DELEGATION_HOOK_DISABLE=0 # Investigate root cause export DEBUG_DELEGATION_HOOK=1 -/delegate "Test delegation" +/workflow-orchestrator:delegate "Test delegation" tail /tmp/delegation_hook_debug.log ``` @@ -777,11 +777,11 @@ ls -la ~/.claude/tasks/ The delegation system provides an interactive in-session mechanism for toggling delegation enforcement without requiring environment variables. -### The /bypass Command +### The /workflow-orchestrator:bypass Command **Usage:** ```bash -/bypass +/workflow-orchestrator:bypass ``` Toggles delegation enforcement on/off from within a Claude Code session. Uses an interactive prompt to let you choose between: @@ -803,7 +803,7 @@ Toggles delegation enforcement on/off from within a Claude Code session. Uses an ### Comparison with DELEGATION_HOOK_DISABLE -| Aspect | DELEGATION_HOOK_DISABLE | /bypass | +| Aspect | DELEGATION_HOOK_DISABLE | /workflow-orchestrator:bypass | |--------|------------------------|---------| | Type | Environment variable | Flag file | | Set from | Outside session (bash) | Inside session (interactive) | diff --git a/docs/plan-explore-parallel-processing.md b/docs/plan-explore-parallel-processing.md index 1863926..036dc0d 100644 --- a/docs/plan-explore-parallel-processing.md +++ b/docs/plan-explore-parallel-processing.md @@ -1,6 +1,6 @@ # Parallel Explore Agents for Large Data Processing -**Status:** Implemented via `breadth-reader` skill and 3-step routing in `workflow_orchestrator.md`. +**Status:** Implemented via 3-step routing in `workflow_orchestrator.md`. Read-only breadth tasks are handled by spawning parallel Explore agents or codebase-context-analyzer directly. ## Background @@ -215,15 +215,10 @@ Example Task invocation for Explore: ### Implementation (Completed) -1. **`breadth-reader` skill** (`skills/breadth-reader/SKILL.md`) - - `context: fork` property for isolated execution - - Receives read/explore/review prompts - - Returns summary only to main agent - -2. **3-step routing in `workflow_orchestrator.md`** - - Step 1: Write detection (skip breadth-reader if write indicators found) +1. **3-step routing in `workflow_orchestrator.md`** + - Step 1: Write detection (skip direct Explore routing if write indicators found) - Step 2: Breadth task detection (single verb + broad scope) - - Step 3: Route decision (breadth-reader, plan mode, or direct execution) + - Step 3: Route decision (parallel Explore agents, plan mode, or direct execution) 3. **Direct execution for breadth+write tasks** - Spawns multiple general-purpose agents in a single message diff --git a/docs/statusline-system.md b/docs/statusline-system.md index cae415a..54239e9 100644 --- a/docs/statusline-system.md +++ b/docs/statusline-system.md @@ -342,7 +342,7 @@ cat .claude/state/active_delegations.json | jq . watch -n 1 ~/.claude/scripts/statusline.sh # Terminal 2: Run workflow -/delegate "Analyze auth system AND design payment API" +/workflow-orchestrator:delegate "Analyze auth system AND design payment API" ``` **StatusLine progression:** @@ -545,7 +545,7 @@ cat .claude/state/active_delegations.json | jq '.active_delegations[] | select(. rm -f .claude/state/active_delegations.json rm -f .claude/state/delegated_sessions.txt # Start fresh - /delegate "Your task" + /workflow-orchestrator:delegate "Your task" ``` ### StatusLine Script Errors diff --git a/hooks/PreToolUse/require_delegation.py b/hooks/PreToolUse/require_delegation.py index 221a128..579306d 100644 --- a/hooks/PreToolUse/require_delegation.py +++ b/hooks/PreToolUse/require_delegation.py @@ -5,7 +5,7 @@ """ PreToolUse Hook: Require Delegation (cross-platform) -Block tools unless /delegate was used, but ALWAYS allow delegation tools. +Block tools unless /workflow-orchestrator:delegate was used, but ALWAYS allow delegation tools. Tool name is passed via stdin as JSON. This Python version works on Windows, macOS, and Linux. @@ -36,28 +36,6 @@ _handler.setFormatter(logging.Formatter("%(message)s")) logger.addHandler(_handler) -# P0 FIX: Skip hook entirely for subagents -# Subagents have CLAUDE_PARENT_SESSION_ID set, main agent does not -parent_session_id = os.environ.get("CLAUDE_PARENT_SESSION_ID", "") -if parent_session_id: - # Subagent - allow all tools EXCEPT TeamCreate (no nested teams) - try: - stdin_data = sys.stdin.read() - data = json.loads(stdin_data) if stdin_data else {} - tool_name = str(data.get("tool_name", "")) - if tool_name == "TeamCreate": - logger.warning( - "Nested teams not supported. Teammates cannot create teams.", - ) - sys.exit(2) - except Exception as exc: # noqa: BLE001 - # Can't parse stdin; allow tool to avoid breaking subagents - logger.warning( - "subagent TeamCreate guard failed to parse stdin: %s", - exc, - ) - sys.exit(0) - # Debug mode DEBUG_HOOK = os.environ.get("DEBUG_DELEGATION_HOOK", "0") == "1" DEBUG_FILE = ( @@ -78,8 +56,8 @@ def debug_log(message: str) -> None: def get_state_dir() -> Path: - """Get the state directory path.""" - project_dir = Path(os.environ.get("CLAUDE_PROJECT_DIR", Path.cwd())) + """Get the state directory path, with normalized path resolution.""" + project_dir = Path(os.environ.get("CLAUDE_PROJECT_DIR", str(Path.cwd()))).resolve() state_dir = project_dir / ".claude" / "state" state_dir.mkdir(parents=True, exist_ok=True) return state_dir @@ -119,7 +97,7 @@ def get_state_dir() -> Path: def block_tool(tool_name: str) -> int: """Block a tool and print the error message.""" name = tool_name or "" - msg = f"Tool blocked: {name}. Use /delegate immediately. Do NOT retry other tools." + msg = f"Tool blocked: {name}. Use /workflow-orchestrator:delegate immediately. Do NOT retry other tools." logger.warning("%s", msg) return 2 @@ -128,6 +106,32 @@ def main() -> int: """Main entry point.""" debug_log("=== PreToolUse Hook START ===") + # Skip hook entirely for subagents + # Multiple signals indicate subagent context — check all of them. + # It's better to accidentally allow a subagent tool call than to deadlock. + _is_subagent = bool( + os.environ.get("CLAUDE_PARENT_SESSION_ID") or os.environ.get("CLAUDE_AGENT_ID") + ) + if _is_subagent: + # Subagent - allow all tools EXCEPT TeamCreate (no nested teams) + try: + stdin_data = sys.stdin.read() + data = json.loads(stdin_data) if stdin_data else {} + tool_name = str(data.get("tool_name", "")) + if tool_name == "TeamCreate": + logger.warning( + "Nested teams not supported. Teammates cannot create teams.", + ) + return 2 + except Exception as exc: # noqa: BLE001 + # Can't parse stdin; allow tool to avoid breaking subagents + logger.warning( + "subagent TeamCreate guard failed to parse stdin: %s", + exc, + ) + debug_log("ALLOWED: Subagent detected (env var)") + return 0 + state_dir = get_state_dir() delegation_disabled_file = state_dir / "delegation_disabled" diff --git a/hooks/SessionStart/inject_workflow_orchestrator.py b/hooks/SessionStart/inject_workflow_orchestrator.py index 6806a23..01b1ccd 100644 --- a/hooks/SessionStart/inject_workflow_orchestrator.py +++ b/hooks/SessionStart/inject_workflow_orchestrator.py @@ -7,7 +7,7 @@ This hook runs on session startup/resume/clear/compact and injects the orchestrator_stub.md routing prompt into Claude's context. The full -workflow_orchestrator.md is loaded on-demand by /delegate. +workflow_orchestrator.md is loaded on-demand by /workflow-orchestrator:delegate. This Python version works on Windows, macOS, and Linux. """ @@ -58,7 +58,7 @@ def find_orchestrator_file() -> Path | None: 3. Repository src/ location (for development) 4. Local .claude directory (project-specific override) - The full workflow_orchestrator.md is loaded on-demand by /delegate. + The full workflow_orchestrator.md is loaded on-demand by /workflow-orchestrator:delegate. """ plugin_dir = get_plugin_root() project_dir = Path(os.environ.get("CLAUDE_PROJECT_DIR", Path.cwd())) diff --git a/hooks/UserPromptSubmit/clear-delegation-sessions.py b/hooks/UserPromptSubmit/clear-delegation-sessions.py index ac309b8..01027ad 100644 --- a/hooks/UserPromptSubmit/clear-delegation-sessions.py +++ b/hooks/UserPromptSubmit/clear-delegation-sessions.py @@ -4,7 +4,7 @@ Purpose: Clear stale delegation session state on every user prompt. This hook ensures that delegation state doesn't persist across user -interactions, forcing explicit /delegate usage for each workflow. +interactions, forcing explicit /workflow-orchestrator:delegate usage for each workflow. Timing: Fires BEFORE each user message is processed by Claude Code diff --git a/output-styles/technical-adaptive.md b/output-styles/technical-adaptive.md index 29c9680..53bc54d 100644 --- a/output-styles/technical-adaptive.md +++ b/output-styles/technical-adaptive.md @@ -8,7 +8,7 @@ keep-coding-instructions: true ## Always on Delegation Mode 1. Any incoming request from the user that requires doing any work or using a Tool MUST be delegated to a general purpose agent unless there's a specific domain expert agent available. -2. You must use the /delegate tool for that. +2. You must use the /workflow-orchestrator:delegate tool for that. 3. When spawning multiple agents and `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` is set, ALWAYS use TeamCreate first, then Agent(team_name=...) for each agent. Never use isolated parallel subagents when teams are available. ## User Prompt Styling diff --git a/scripts/statusline.py b/scripts/statusline.py index c2c09d6..4e87592 100755 --- a/scripts/statusline.py +++ b/scripts/statusline.py @@ -14,15 +14,9 @@ import subprocess import sys import tempfile -import time -from datetime import datetime, timedelta +from datetime import datetime from pathlib import Path -# Cache configuration -COST_CACHE_TTL_SECONDS = 300 # Cache costs for 5 minutes (cost data changes slowly) -COST_CACHE_FILE = Path(tempfile.gettempdir()) / "statusline_cost_cache.json" -COST_REFRESH_LOCK = Path(tempfile.gettempdir()) / "statusline_cost_refresh.lock" # noqa: S108 - # Force UTF-8 output on Windows (fixes emoji encoding errors) if sys.platform == "win32": sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace") @@ -291,313 +285,6 @@ def get_git_branch(cwd: str | None = None) -> str: return "no-git" -def load_cost_cache() -> dict: - """Load cost cache from file. - - Returns: - Cache dictionary with 'daily_cost', 'session_cost', 'timestamp', 'cwd' keys, - or empty dict if cache doesn't exist or is invalid. - """ - try: - if COST_CACHE_FILE.exists(): - return json.loads(COST_CACHE_FILE.read_text(encoding="utf-8")) - except (json.JSONDecodeError, OSError): - pass - return {} - - -def save_cost_cache( - daily_cost: str, - session_cost: str, - cwd: str, - daily_cost_val: float = 0.0, - weekly_cost_val: float = 0.0, -) -> None: - """Save cost values to cache file. - - Args: - daily_cost: Formatted daily cost string. - session_cost: Formatted session cost string. - cwd: Current working directory (for cache invalidation). - daily_cost_val: Raw daily cost value for percentage calculations. - weekly_cost_val: Raw weekly cost value for percentage calculations. - """ - cache = { - "daily_cost": daily_cost, - "session_cost": session_cost, - "daily_cost_val": daily_cost_val, - "weekly_cost_val": weekly_cost_val, - "timestamp": time.time(), - "cwd": cwd, - } - try: - COST_CACHE_FILE.write_text(json.dumps(cache), encoding="utf-8") - except OSError: - pass - - -def is_cache_valid(cache: dict, cwd: str) -> bool: - """Check if cache is still valid. - - Args: - cache: Cache dictionary from load_cost_cache(). - cwd: Current working directory to check against cached cwd. - - Returns: - True if cache is fresh and for the same directory, False otherwise. - """ - if not cache: - return False - cache_time = cache.get("timestamp", 0) - cache_cwd = cache.get("cwd", "") - age = time.time() - cache_time - return age < COST_CACHE_TTL_SECONDS and cache_cwd == cwd - - -def fetch_costs_raw(cwd: str) -> tuple[str, str, float, float]: - """Fetch daily, session, and weekly costs from ccusage calls. - - Uses the `-i` flag which returns per-project breakdown that also includes - daily totals, allowing both values to be extracted from one response. - Also fetches weekly data for usage percentage calculation. - - Args: - cwd: Current working directory, used to identify the project. - - Returns: - Tuple of (daily_cost, session_cost, daily_cost_val, weekly_cost_val) - where daily_cost/session_cost are formatted strings like "$X.XX" - and daily_cost_val/weekly_cost_val are raw float values. - """ - today = datetime.now().strftime("%Y%m%d") - - # Convert cwd to project name format (replace / with -) - project_name = cwd.replace("/", "-").replace("\\", "-") if cwd else "" - - daily_cost_val = 0.0 - weekly_cost_val = 0.0 - - # Try bunx (bun) first, then npx - single call with -i flag gets both values - for cmd in [["bunx", "ccusage@latest"], ["npx", "ccusage@latest"]]: - try: - # Fetch today's costs - result = subprocess.run( # noqa: S603, S607 - [*cmd, "daily", "--json", "--since", today, "-i"], - capture_output=True, - text=True, - timeout=30, - ) - if result.returncode == 0 and result.stdout.strip(): - data = json.loads(result.stdout) - - # Extract daily total from the same response - daily_cost_val = data.get("totals", {}).get("totalCost", 0) - daily_cost = f"${daily_cost_val:.2f}" - - # Extract session/project cost - session_cost = "$0.00" - if project_name: - projects = data.get("projects", {}) - if project_name in projects: - project_data = projects[project_name] - if project_data and len(project_data) > 0: - total_cost = sum( - entry.get("totalCost", 0) for entry in project_data - ) - session_cost = f"${total_cost:.2f}" - - # Fetch weekly costs (last 7 days) - week_ago = (datetime.now() - timedelta(days=6)).strftime("%Y%m%d") - weekly_result = subprocess.run( # noqa: S603, S607 - [*cmd, "daily", "--json", "--since", week_ago, "-i"], - capture_output=True, - text=True, - timeout=30, - ) - if weekly_result.returncode == 0 and weekly_result.stdout.strip(): - weekly_data = json.loads(weekly_result.stdout) - weekly_cost_val = weekly_data.get("totals", {}).get("totalCost", 0) - - return daily_cost, session_cost, daily_cost_val, weekly_cost_val - except ( - subprocess.TimeoutExpired, - FileNotFoundError, - json.JSONDecodeError, - OSError, - ): - continue - - return "$0.00", "$0.00", 0.0, 0.0 - - -def _is_refresh_locked() -> bool: - """Check if a background refresh is already running. - - Uses a lock file with a 60-second staleness check to prevent concurrent - refreshes while not permanently blocking if a refresh process dies. - - Returns: - True if a refresh is currently in progress, False otherwise. - """ - try: - if COST_REFRESH_LOCK.exists(): - lock_age = time.time() - COST_REFRESH_LOCK.stat().st_mtime - # Consider lock stale after 60 seconds (refresh should finish in ~15s) - if lock_age < 60: - return True - # Stale lock, remove it - COST_REFRESH_LOCK.unlink(missing_ok=True) - except OSError: - pass - return False - - -def spawn_background_refresh(cwd: str) -> None: - """Spawn a background process to refresh the cost cache. - - Uses subprocess.Popen to run a small Python script that: - 1. Creates a lock file to prevent concurrent refreshes - 2. Runs the ccusage command - 3. Parses the result and writes to the cache file - 4. Removes the lock file - - Args: - cwd: Current working directory for session cost lookup. - """ - if _is_refresh_locked(): - debug_log("Background refresh already running, skipping") - return - - debug_log("Spawning background refresh process") - - # Build the inline Python script for background execution - refresh_script = f""" -import json, subprocess, time, sys -from pathlib import Path -from datetime import datetime, timedelta - -lock_file = Path({str(COST_REFRESH_LOCK)!r}) -cache_file = Path({str(COST_CACHE_FILE)!r}) -cwd = {cwd!r} - -try: - # Create lock file - lock_file.write_text(str(time.time())) - - today = datetime.now().strftime("%Y%m%d") - week_ago = (datetime.now() - timedelta(days=6)).strftime("%Y%m%d") - project_name = cwd.replace("/", "-").replace("\\\\", "-") if cwd else "" - - daily_cost = "$0.00" - session_cost = "$0.00" - daily_cost_val = 0.0 - weekly_cost_val = 0.0 - - for cmd in [["bunx", "ccusage@latest"], ["npx", "ccusage@latest"]]: - try: - result = subprocess.run( - [*cmd, "daily", "--json", "--since", today, "-i"], - capture_output=True, text=True, timeout=30, - ) - if result.returncode == 0 and result.stdout.strip(): - data = json.loads(result.stdout) - daily_cost_val = data.get("totals", {{}}).get("totalCost", 0) - daily_cost = f"${{daily_cost_val:.2f}}" - if project_name: - projects = data.get("projects", {{}}) - if project_name in projects: - project_data = projects[project_name] - if project_data and len(project_data) > 0: - total_cost = sum(e.get("totalCost", 0) for e in project_data) - session_cost = f"${{total_cost:.2f}}" - - # Fetch weekly costs - weekly_result = subprocess.run( - [*cmd, "daily", "--json", "--since", week_ago, "-i"], - capture_output=True, text=True, timeout=30, - ) - if weekly_result.returncode == 0 and weekly_result.stdout.strip(): - weekly_data = json.loads(weekly_result.stdout) - weekly_cost_val = weekly_data.get("totals", {{}}).get("totalCost", 0) - - break - except Exception: - continue - - cache = {{ - "daily_cost": daily_cost, - "session_cost": session_cost, - "daily_cost_val": daily_cost_val, - "weekly_cost_val": weekly_cost_val, - "timestamp": time.time(), - "cwd": cwd, - }} - cache_file.write_text(json.dumps(cache)) -finally: - lock_file.unlink(missing_ok=True) -""" - - try: - subprocess.Popen( # noqa: S603 - [sys.executable, "-c", refresh_script], # noqa: S603 - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - start_new_session=True, - ) - except OSError as e: - debug_log(f"Failed to spawn background refresh: {e}") - - -def get_costs_cached(cwd: str) -> tuple[str, str, float, float]: - """Get daily and session costs with non-blocking cache refresh. - - Returns cached values immediately. If the cache is expired, returns stale - values (or "$..." placeholders on first run) and spawns a background process - to refresh the cache. This ensures the statusline always returns in <0.1s. - - Cache TTL is 300 seconds. - - Args: - cwd: Current working directory for session cost lookup. - - Returns: - Tuple of (daily_cost, session_cost, daily_cost_val, weekly_cost_val). - """ - cache = load_cost_cache() - - if is_cache_valid(cache, cwd): - debug_log( - f"Using cached costs (age: {time.time() - cache.get('timestamp', 0):.1f}s)" - ) - return ( - cache.get("daily_cost", "$0.00"), - cache.get("session_cost", "$0.00"), - cache.get("daily_cost_val", 0.0), - cache.get("weekly_cost_val", 0.0), - ) - - # Cache is stale or missing - return immediately with stale/placeholder values - if cache: - stale_daily = cache.get("daily_cost", "$...") - stale_session = cache.get("session_cost", "$...") - stale_daily_val = cache.get("daily_cost_val", 0.0) - stale_weekly_val = cache.get("weekly_cost_val", 0.0) - debug_log( - f"Cache expired, returning stale values: daily={stale_daily}, session={stale_session}" - ) - else: - stale_daily = "$..." - stale_session = "$..." - stale_daily_val = 0.0 - stale_weekly_val = 0.0 - debug_log("No cache exists, returning placeholders") - - # Spawn background refresh (fire and forget) - spawn_background_refresh(cwd) - - return stale_daily, stale_session, stale_daily_val, stale_weekly_val - - def get_claude_version() -> str: """Get the Claude Code version.""" try: @@ -741,11 +428,17 @@ def main() -> None: # Prefer cwd from stdin JSON (reflects worktrees) over os.getcwd() raw_cwd = input_data.get("cwd") if isinstance(input_data, dict) else None effective_cwd = raw_cwd if isinstance(raw_cwd, str) and raw_cwd else os.getcwd() - full_cwd = effective_cwd - # Get daily and session costs (with caching for fast statusline refresh) - daily_cost, session_cost, daily_cost_val, weekly_cost_val = get_costs_cached( - full_cwd + # Session cost from stdin JSON (real-time, no I/O needed) + session_cost_usd = 0.0 + stdin_cost = input_data.get("cost", {}) if isinstance(input_data, dict) else {} + if isinstance(stdin_cost, dict): + raw_val = stdin_cost.get("total_cost_usd") + if isinstance(raw_val, (int, float)): + session_cost_usd = float(raw_val) + + cost_str = ( + f"\U0001f4b0 ${session_cost_usd:.2f}" if session_cost_usd else "\U0001f4b0 $..." ) # Get Claude version @@ -770,9 +463,8 @@ def main() -> None: # Get turn duration if available turn_duration = get_turn_duration() - # Format costs: daily cost only - daily_amount = daily_cost - cost_display = f"{GREEN}\U0001f4b0 {daily_amount}{RESET}" + # Format cost display + cost_display = f"{GREEN}{cost_str}{RESET}" # Extract rate limits from statusLine JSON input rate_limits = input_data.get("rate_limits", {}) diff --git a/skills/breadth-reader/SKILL.md b/skills/breadth-reader/SKILL.md deleted file mode 100644 index 999f1da..0000000 --- a/skills/breadth-reader/SKILL.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: breadth-reader -description: Forked skill for breadth tasks (explore, review, summarize) -context: fork -allowed-tools: Read, Glob, Grep, Bash, Task ---- - -# Breadth Reader - -Read-only skill for exploring/reviewing/summarizing large data sources. - -## When to Use - -Single-verb breadth tasks: -- "explore ~/dev/project/" -- "review the code in src/" -- "summarize all files in docs/" - -## Behavior - -- Runs in **forked context** (isolated from main agent) -- Claude auto-optimizes parallelism internally -- Returns **summary only** to main agent -- No orchestration overhead - -## Parallel Exploration - -For large data sources, spawn multiple `Explore` subagents (Haiku, cheap, fast): -- `subagent_type: Explore` with thoroughness: quick/medium/thorough - -## Output - -Return a structured summary. Do NOT return raw file contents. diff --git a/system-prompts/orchestrator_stub.md b/system-prompts/orchestrator_stub.md index 20b030c..094d280 100644 --- a/system-prompts/orchestrator_stub.md +++ b/system-prompts/orchestrator_stub.md @@ -18,7 +18,7 @@ The hook system pre-checks `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS`. You do NOT ne ### Step 0: Team/Collaboration Detection **Team indicators:** team, collaborate, agent team, teammate, work together, different angles, multiple perspectives, devil's advocate, brainstorm together -If ANY found: use `/delegate` to plan and execute. +If ANY found: use `/workflow-orchestrator:delegate` to plan and execute. ### Step 1: Write Detection **Write indicators:** create, write, save, generate, produce, output, report, build, make, implement, fix, update @@ -32,16 +32,16 @@ If ANY found: Continue to Step 2. | Pattern | Route | |---------|-------| -| Breadth + Write (same op x many items, with output) | `/delegate` | -| Multi-phase workflow (create, test, deploy) | `/delegate` | -| Read-only breadth (no write indicators) | `/breadth-reader {prompt}` | -| Single simple task | `/delegate` | +| Breadth + Write (same op x many items, with output) | `/workflow-orchestrator:delegate` | +| Multi-phase workflow (create, test, deploy) | `/workflow-orchestrator:delegate` | +| Read-only breadth (no write indicators) | `/workflow-orchestrator:delegate` (spawns parallel Explore agents or codebase-context-analyzer) | +| Single simple task | `/workflow-orchestrator:delegate` | ## Always-On Delegation Mode -1. Any user request requiring work MUST be delegated to agents via `/delegate `. +1. Any user request requiring work MUST be delegated to agents via `/workflow-orchestrator:delegate `. 2. Main agent NEVER executes tools directly (except Tasks API and AskUserQuestion). -3. Full orchestrator instructions (planning, execution, agent assignment, wave scheduling) are loaded by `/delegate`. +3. Full orchestrator instructions (planning, execution, agent assignment, wave scheduling) are loaded by `/workflow-orchestrator:delegate`. **Agent Teams (MANDATORY when available):** If `TeamCreate` is in your available tools, ALWAYS use TeamCreate + Agent(team_name=...) for multi-agent work. Do NOT fall back to isolated parallel subagents. Teammates share context and can coordinate via SendMessage. diff --git a/system-prompts/workflow_orchestrator.md b/system-prompts/workflow_orchestrator.md index 04f1325..e182755 100644 --- a/system-prompts/workflow_orchestrator.md +++ b/system-prompts/workflow_orchestrator.md @@ -24,7 +24,7 @@ Multi-step workflow orchestration for Claude Code. Main agent enters plan mode ( **Write indicators:** create, write, save, generate, produce, output, report, build, make, implement, fix, update -**If ANY write indicator found → Continue to Step 2 (don't use breadth-reader)** +**If ANY write indicator found → Continue to Step 2** ### Step 2: Breadth Task Detection @@ -38,7 +38,7 @@ Multi-step workflow orchestration for Claude Code. Main agent enters plan mode ( |---------|-------|---------| | Breadth + Write (same op × many items, with output) | **DIRECT EXECUTION** (skip plan mode) | "review 16 files, create reports" | | Multi-phase workflow (create → test → deploy) | plan mode (EnterPlanMode) | "create calculator with tests and verify" | -| Read-only breadth (no write indicators) | `/breadth-reader {prompt}` | "explore code in X", "summarize files in X" | +| Read-only breadth (no write indicators) | Spawn parallel Explore agents or codebase-context-analyzer | "explore code in X", "summarize files in X" | | Single simple task | general-purpose agent | "fix this bug" | **This four-step check is MANDATORY and must happen FIRST before any other action.**