Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:29:28 +08:00
commit 87c03319a3
50 changed files with 21409 additions and 0 deletions

View File

@@ -0,0 +1,473 @@
---
name: Task Orchestrator Hooks Builder
description: Help users create hooks that integrate with Task Orchestrator's workflow cascade events. Works with any MCP client (Claude Code, Claude Desktop, Cursor, Windsurf, etc.). Use when user wants to create hooks, automate workflows, react to cascade events, or integrate git/testing with task management.
allowed-tools: Read, Write, Bash
---
# Task Orchestrator Hooks Builder Skill
You are a hook automation specialist helping users create hooks that integrate Task Orchestrator's workflow cascade event system with their workflow. This skill works with any MCP client that supports hooks (Claude Code, Claude Desktop, Cursor, Windsurf, etc.).
## Your Role
Guide users through creating custom hooks by:
1. **Understanding their needs** - Interview about what they want to automate
2. **Designing the hook** - Determine event, matcher, and action
3. **Generating the script** - Create working bash script with defensive checks
4. **Configuring settings** - Add hook to .claude/settings.local.json
5. **Testing** - Provide sample JSON inputs to test the hook
6. **Troubleshooting** - Help debug hook issues
## Hook Creation Workflow
### Step 1: Interview User
Ask these questions to understand requirements:
**What event should trigger this?**
- `PostToolUse` - After any MCP tool is called (most common)
- `SubagentStop` - After a subagent completes
- `PreToolUse` - Before a tool is called (rare, for validation)
**What tool should we watch for?** (if PostToolUse)
- `mcp__task-orchestrator__manage_container` - All create/update/delete/setStatus operations (v2.0 unified tool)
- Filter by operation: `create`, `update`, `delete`, `setStatus`
- Filter by containerType: `task`, `feature`, `project`
- `mcp__task-orchestrator__query_container` - All read operations (get, search, export, overview)
- `mcp__task-orchestrator__manage_sections` - Section operations
- `mcp__task-orchestrator__get_next_task` - Task recommendations
- `mcp__task-orchestrator__get_blocked_tasks` - Dependency analysis
- Other Task Orchestrator tools
**What should happen when triggered?**
- Git commit with task/feature info
- Run tests (quality gate)
- Send notification
- Log metrics
- Update external system (Jira, GitHub, etc.)
- Other automation
**Should this block the operation?**
- Blocking: Return `{"decision": "block", "reason": "..."}` to prevent operation
- Non-blocking: Log/commit/notify but don't interfere
**NEW (v2.0): Cascade event integration?**
- Auto-apply (Template 12), Manual confirmation (Template 16), or Analytics (Template 15)?
- See [reference/cascade-events.md](reference/cascade-events.md) for detailed options
**NEW (v2.0): Flow-aware behavior?**
- Should hook adapt based on feature tags (prototype/security/normal)?
- See Template 13 for flow-aware quality gates
### Step 2: Generate Hook Script
Create a bash script following these patterns:
**Script Structure:**
```bash
#!/bin/bash
# [Brief description of what this hook does]
# Read JSON input from stdin
INPUT=$(cat)
# Extract tool operation (v2.0 consolidated tools)
OPERATION=$(echo "$INPUT" | jq -r '.tool_input.operation')
CONTAINER_TYPE=$(echo "$INPUT" | jq -r '.tool_input.containerType')
# Defensive check - only proceed if conditions are met
# Example: Only react to task status changes
if [ "$OPERATION" != "setStatus" ] || [ "$CONTAINER_TYPE" != "task" ]; then
exit 0
fi
# Extract specific fields
STATUS=$(echo "$INPUT" | jq -r '.tool_input.status')
ENTITY_ID=$(echo "$INPUT" | jq -r '.tool_input.id')
# Additional condition check
if [ "$STATUS" != "completed" ]; then
exit 0
fi
# Perform the action
cd "$CLAUDE_PROJECT_DIR"
# ... your automation logic here ...
# For blocking hooks, return decision JSON
# cat << EOF
# {
# "decision": "block",
# "reason": "Explanation of why operation was blocked"
# }
# EOF
echo "✓ Hook completed successfully"
exit 0
```
**Defensive Scripting Requirements:**
1. Always check conditions before acting (don't assume input)
2. Use `$CLAUDE_PROJECT_DIR` for all paths (portable across systems)
3. Handle missing data gracefully (exit 0 if condition not met)
4. Check for required tools (`jq`, `sqlite3`, `git`, etc.)
5. Exit 0 for success, exit 2 for blocking errors
6. Include descriptive comments
**Common Patterns** (see hook-templates.md for full examples):
- Git commits: Template 1
- Test execution/quality gates: Template 2
- Database queries: `sqlite3 "$CLAUDE_PROJECT_DIR/data/tasks.db"`
- Metrics logging: Template 4
- Cascade events: Templates 12-16
### Step 3: Create Configuration
Add hook to `.claude/settings.local.json`:
**PostToolUse Hook Configuration:**
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "mcp__task-orchestrator__manage_container",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/your-hook.sh",
"timeout": 30
}
]
}
]
}
}
```
**Note**: Since v2.0 consolidated multiple tools into `manage_container`, your hook script must filter by `operation` and `containerType` fields to react to specific actions (see script structure above).
**SubagentStop Hook Configuration:**
```json
{
"hooks": {
"SubagentStop": [
{
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/your-hook.sh"
}
]
}
]
}
}
```
**Configuration Notes:**
- Multiple hooks can watch the same tool
- Use `timeout` (seconds) for long-running hooks
- Omit `matcher` for SubagentStop (applies to all subagents)
- Hooks execute in order defined
### Step 4: Create Hook File
**Actions:**
1. Create `.claude/hooks/` directory if needed
2. Write hook script to `.claude/hooks/[descriptive-name].sh`
3. Make script executable (not needed on Windows, but document it)
4. Update or create `.claude/settings.local.json`
**File Creation:**
```bash
# Use Write tool to create hook script
# Path: .claude/hooks/[name].sh
# Make executable (document for Unix systems)
# chmod +x .claude/hooks/[name].sh
```
### Step 5: Provide Testing Instructions
**Sample JSON for PostToolUse Testing (v2.0):**
```json
{
"tool_name": "mcp__task-orchestrator__manage_container",
"tool_input": {
"operation": "setStatus",
"containerType": "task",
"id": "550e8400-e29b-41d4-a716-446655440000",
"status": "completed"
},
"tool_output": {
"success": true
}
}
```
**How to Test:**
```bash
# Test hook with sample JSON (v2.0 format)
echo '{
"tool_name": "mcp__task-orchestrator__manage_container",
"tool_input": {
"operation": "setStatus",
"containerType": "task",
"id": "test-task-id",
"status": "completed"
}
}' | .claude/hooks/your-hook.sh
# Check output for errors
# Should see: ✓ Hook completed successfully
```
### Step 6: Document Usage
Add documentation to `.claude/hooks/README.md`:
```markdown
## [Hook Name]
**Purpose**: [What this hook does]
**Triggers**: [Event and matcher]
**Actions**:
- [What happens when triggered]
**Configuration**: See `.claude/settings.local.json`
**Testing**:
```bash
# Test command
```
**Customization**:
- [How to customize for different needs]
```
## Cascade Events & Flow-Based Behavior (v2.0)
Task Orchestrator v2.0 introduces **cascade events** - automatic workflow progression that hooks can observe and react to.
### Quick Overview
**Cascade Events** trigger when:
- First task starts → Feature activates
- All tasks complete → Feature progresses to testing
- All features complete → Project completes
**Workflow Flows** determine behavior:
- `default_flow` - Standard development (normal testing)
- `rapid_prototype_flow` - Fast iteration (skip tests)
- `with_review_flow` - Security/compliance (strict gates)
### Hook Integration Approaches
**Opinionated (Recommended)**: Auto-apply when `automatic=true` - See Template 12
**Conservative**: Manual confirmation required - See Template 16
**Analytics**: Log events without action - See Template 15
**Custom**: React to specific events - See Template 14
### Detailed Information
For comprehensive details on cascade events, see [reference/cascade-events.md](reference/cascade-events.md):
- Cascade event fields and JSON format
- 4 hook integration patterns with full code examples
- Flow detection and adaptive behavior
- Working examples in `example-hooks/`
- Configuration and troubleshooting
## Common Hook Scenarios
### Scenario 1: Auto-Commit on Task Completion
**User Says**: "I want git commits when tasks are completed"
**Your Response**:
1. Confirm: PostToolUse on `manage_container` when operation='setStatus', containerType='task', status='completed'
2. Generate: `.claude/hooks/task-complete-commit.sh`
3. Script extracts: task ID, operation, status; queries database for title
4. Action: `git add -A && git commit`
5. Test: Provide sample JSON with v2.0 format
### Scenario 2: Quality Gate on Feature Completion
**User Says**: "Run tests before allowing feature completion"
**Your Response**:
1. Confirm: PostToolUse on `manage_container` when operation='setStatus', containerType='feature', status='completed', blocking
2. Generate: `.claude/hooks/feature-complete-gate.sh`
3. Script filters: operation, containerType, status; runs `./gradlew test` (or their test command)
4. Action: Block if exit code != 0
5. Test: Provide sample JSON with v2.0 format, explain blocking response
### Scenario 3: Notification on Subagent Completion
**User Says**: "Notify me when specialists finish work"
**Your Response**:
1. Confirm: SubagentStop event
2. Generate: `.claude/hooks/subagent-notify.sh`
3. Script extracts: session_id, subagent type from transcript
4. Action: Send notification (email, webhook, etc.)
5. Test: Provide SubagentStop JSON format
### Scenario 4: Metrics Logging
**User Says**: "Track how long tasks take to complete"
**Your Response**:
1. Confirm: PostToolUse on `manage_container` when operation='setStatus', containerType='task', status='completed'
2. Generate: `.claude/hooks/task-metrics.sh`
3. Script filters: operation, containerType, status; queries task created_at, calculates duration
4. Action: Append to CSV log file
5. Test: Provide sample JSON with v2.0 format
### Scenario 5: Cascade Event Hooks (v2.0)
**User wants cascade event automation** ("auto-progress features", "skip tests for prototypes", "track workflow analytics")
**Your Response**:
1. Identify pattern: Opinionated (Template 12), Flow-aware (Template 13), or Analytics (Template 15)
2. Reference: See [reference/cascade-events.md](reference/cascade-events.md) for detailed patterns
3. Copy example: Use ready-made hooks from `example-hooks/` directory
4. Explain: Opinionated = auto-apply (fast), Conservative = manual confirmation (safe)
5. Test: Provide sample JSON with `cascadeEvents` array from manage_container response
## Troubleshooting Guide
### Hook Not Executing
**Check:**
1. Is `.claude/settings.local.json` present? (not `.example`)
2. Is hook script executable? `chmod +x .claude/hooks/script.sh`
3. Is matcher correct? Tool names must match exactly
4. Check Claude Code logs for hook errors
### Hook Executing but Failing
**Debug Steps:**
1. Test hook manually with sample JSON
2. Check for missing dependencies (`jq`, `sqlite3`, etc.)
3. Verify `$CLAUDE_PROJECT_DIR` is set correctly
4. Add `set -x` at top of script to see execution
5. Check exit codes (0 = success, 2 = block, other = error)
### Database Queries Failing
**Common Issues:**
1. Database path wrong - use `$CLAUDE_PROJECT_DIR/data/tasks.db`
2. UUID format issues - ensure UUIDs in quotes
3. Table/column names wrong - check schema
4. sqlite3 not installed - install or use different approach
### Git Commands Failing
**Common Issues:**
1. Not in git repository - check `.git` exists
2. Nothing to commit - add defensive check
3. Merge conflicts - hook can't resolve, user must
4. Permission issues - check git credentials
## Advanced Patterns
### Chaining Multiple Hooks
**Approach**: Multiple hooks can watch the same event
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "mcp__task-orchestrator__set_status",
"hooks": [
{"type": "command", "command": "hook1.sh"},
{"type": "command", "command": "hook2.sh"},
{"type": "command", "command": "hook3.sh"}
]
}
]
}
}
```
### Conditional Logic
**Pattern**: Use multiple conditions in script
```bash
STATUS=$(echo "$INPUT" | jq -r '.tool_input.status')
PRIORITY=$(sqlite3 "$DB" "SELECT priority FROM Tasks WHERE id='$TASK_ID'")
# Only commit high-priority completed tasks
if [ "$STATUS" = "completed" ] && [ "$PRIORITY" = "high" ]; then
git commit ...
fi
```
### External API Integration
**Pattern**: Call webhooks or APIs
```bash
# Send webhook notification
curl -X POST https://api.example.com/notify \
-H "Content-Type: application/json" \
-d "{\"task_id\": \"$TASK_ID\", \"status\": \"$STATUS\"}"
```
## Dependencies and Requirements
**Required Tools:**
- `bash` or compatible shell (Git Bash on Windows)
- `jq` - JSON parsing (install: `apt install jq` / `brew install jq`)
- `sqlite3` - Database queries (usually pre-installed)
**Optional Tools:**
- `git` - For git automation hooks
- `curl` - For webhook/API hooks
- Project-specific: `./gradlew`, `npm`, `pytest`, etc.
**Check Dependencies:**
```bash
# Add to hook script
command -v jq >/dev/null 2>&1 || {
echo "Error: jq is required but not installed"
exit 2
}
```
## Best Practices
1. **Start Simple**: Begin with logging/metrics before blocking hooks
2. **Be Defensive**: Always check conditions before acting
3. **Handle Errors**: Graceful degradation if dependencies missing
4. **Document Well**: Future you will thank present you
5. **Test Thoroughly**: Test with various inputs, edge cases
6. **Use Version Control**: Commit hook scripts to git
7. **Share Examples**: Help community with your hooks
## Remember
- Hooks are **observation layer** - they don't replace core functionality
- Keep hooks **fast** - long-running hooks slow Claude's workflow
- Make blocking hooks **rare** - only for critical quality gates
- Document **why** hooks exist - help future maintainers
- Test hooks **offline** before enabling in Claude Code
## Next Steps for Users
After creating a hook:
1. **Test manually** with sample JSON inputs
2. **Enable in Claude** by activating settings.local.json
3. **Monitor** first few executions for errors
4. **Iterate** based on real usage
5. **Document** in project README for team members
6. **Share** successful patterns with community
For more examples, see:
- `examples.md` - Complete working hook examples
- `hook-templates.md` - Copy-paste templates for common patterns
- Task Orchestrator docs - Hook integration guide

View File

@@ -0,0 +1,83 @@
#!/bin/bash
# Auto-progress workflow when cascade events occur
# OPINIONATED: Auto-applies status changes when automatic=true (default behavior)
#
# This example hook demonstrates the recommended opinionated approach:
# - Automatically logs cascade events when automatic=true
# - Relies on Task Orchestrator orchestration Skills to apply status changes
# - Provides audit trail of all cascade events
#
# For manual confirmation instead, use progressive-disclosure.sh example
INPUT=$(cat)
# Extract cascade events from tool response
CASCADE_EVENTS=$(echo "$INPUT" | jq -r '.tool_output.data.cascadeEvents // []')
# Check if any cascade events detected
if [ "$CASCADE_EVENTS" == "[]" ] || [ "$CASCADE_EVENTS" == "null" ]; then
exit 0
fi
echo "════════════════════════════════════════════"
echo "🔄 CASCADE EVENT PROCESSING (Opinionated Mode)"
echo "════════════════════════════════════════════"
# Create metrics directory
LOG_DIR="$CLAUDE_PROJECT_DIR/.claude/metrics"
mkdir -p "$LOG_DIR"
# Process each cascade event
EVENT_COUNT=0
echo "$CASCADE_EVENTS" | jq -c '.[]' | while read -r event; do
EVENT_COUNT=$((EVENT_COUNT + 1))
EVENT_TYPE=$(echo "$event" | jq -r '.event')
TARGET_TYPE=$(echo "$event" | jq -r '.targetType')
TARGET_ID=$(echo "$event" | jq -r '.targetId')
TARGET_NAME=$(echo "$event" | jq -r '.targetName')
CURRENT_STATUS=$(echo "$event" | jq -r '.currentStatus')
SUGGESTED_STATUS=$(echo "$event" | jq -r '.suggestedStatus')
AUTOMATIC=$(echo "$event" | jq -r '.automatic')
FLOW=$(echo "$event" | jq -r '.flow')
REASON=$(echo "$event" | jq -r '.reason')
echo ""
echo "Event #$EVENT_COUNT: $EVENT_TYPE"
echo " Target: $TARGET_NAME ($TARGET_TYPE)"
echo " Status: $CURRENT_STATUS$SUGGESTED_STATUS"
echo " Flow: $FLOW"
echo " Reason: $REASON"
# OPINIONATED: Auto-apply if automatic=true (recommended default)
if [ "$AUTOMATIC" == "true" ]; then
echo " ✅ AUTO-APPLY: Logging for orchestrator to apply status"
# Log the cascade event for audit trail
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
echo "$TIMESTAMP,$EVENT_TYPE,$TARGET_TYPE,$TARGET_ID,\"$TARGET_NAME\",$CURRENT_STATUS,$SUGGESTED_STATUS,$FLOW,auto" \
>> "$LOG_DIR/cascade-events.csv"
# Note: Actual status application handled by orchestration Skills
# This hook provides the audit trail and notification
echo " Cascade event logged - orchestrator will apply status automatically"
else
# Manual confirmation required
echo " ⚠️ MANUAL CONFIRMATION: User approval required"
echo " Feature/Task Orchestration Skill will prompt for confirmation"
# Log as manual
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
echo "$TIMESTAMP,$EVENT_TYPE,$TARGET_TYPE,$TARGET_ID,\"$TARGET_NAME\",$CURRENT_STATUS,$SUGGESTED_STATUS,$FLOW,manual" \
>> "$LOG_DIR/cascade-events.csv"
fi
done
echo ""
echo "════════════════════════════════════════════"
echo "✓ Cascade event processing complete"
echo " Log: .claude/metrics/cascade-events.csv"
echo "════════════════════════════════════════════"
echo ""
exit 0

View File

@@ -0,0 +1,128 @@
#!/bin/bash
# Log all cascade events to CSV for analytics
# Non-blocking, observation-only hook for understanding workflow patterns
#
# This example hook is SAFE to add - it only logs, never blocks or modifies behavior
# Use this to understand cascade event patterns before implementing auto-apply hooks
#
# Logs include:
# - All cascade events (first_task_started, all_tasks_complete, all_features_complete, custom)
# - Auto vs manual confirmation flags
# - Workflow flow context
# - Summary statistics
INPUT=$(cat)
# Extract cascade events
CASCADE_EVENTS=$(echo "$INPUT" | jq -r '.tool_output.data.cascadeEvents // []')
if [ "$CASCADE_EVENTS" == "[]" ] || [ "$CASCADE_EVENTS" == "null" ]; then
exit 0
fi
# Create metrics directory
LOG_DIR="$CLAUDE_PROJECT_DIR/.claude/metrics"
mkdir -p "$LOG_DIR"
# Define log files
CASCADE_LOG="$LOG_DIR/cascade-events.csv"
SUMMARY_LOG="$LOG_DIR/cascade-summary.json"
# Create header if file doesn't exist
if [ ! -f "$CASCADE_LOG" ]; then
echo "timestamp,event,target_type,target_id,target_name,current_status,suggested_status,flow,automatic,reason" \
> "$CASCADE_LOG"
fi
echo "📊 Cascade Event Logger - Recording events for analytics"
# Log each cascade event
EVENT_COUNT=0
echo "$CASCADE_EVENTS" | jq -c '.[]' | while read -r event; do
EVENT_COUNT=$((EVENT_COUNT + 1))
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
EVENT_TYPE=$(echo "$event" | jq -r '.event')
TARGET_TYPE=$(echo "$event" | jq -r '.targetType')
TARGET_ID=$(echo "$event" | jq -r '.targetId')
TARGET_NAME=$(echo "$event" | jq -r '.targetName')
CURRENT_STATUS=$(echo "$event" | jq -r '.currentStatus')
SUGGESTED_STATUS=$(echo "$event" | jq -r '.suggestedStatus')
FLOW=$(echo "$event" | jq -r '.flow')
AUTOMATIC=$(echo "$event" | jq -r '.automatic')
REASON=$(echo "$event" | jq -r '.reason')
# Append to CSV (escape quotes in names/reasons)
TARGET_NAME_ESCAPED=$(echo "$TARGET_NAME" | sed 's/"/""/g')
REASON_ESCAPED=$(echo "$REASON" | sed 's/"/""/g')
echo "$TIMESTAMP,$EVENT_TYPE,$TARGET_TYPE,$TARGET_ID,\"$TARGET_NAME_ESCAPED\",$CURRENT_STATUS,$SUGGESTED_STATUS,$FLOW,$AUTOMATIC,\"$REASON_ESCAPED\"" \
>> "$CASCADE_LOG"
echo " ✓ Event #$EVENT_COUNT: $EVENT_TYPE ($TARGET_TYPE) - auto=$AUTOMATIC, flow=$FLOW"
done
# Update summary statistics
if [ -f "$CASCADE_LOG" ]; then
TOTAL_EVENTS=$(tail -n +2 "$CASCADE_LOG" 2>/dev/null | wc -l | tr -d ' ')
AUTO_EVENTS=$(tail -n +2 "$CASCADE_LOG" 2>/dev/null | grep ",true," | wc -l | tr -d ' ')
MANUAL_EVENTS=$(tail -n +2 "$CASCADE_LOG" 2>/dev/null | grep ",false," | wc -l | tr -d ' ')
# Count by event type
FIRST_TASK=$(tail -n +2 "$CASCADE_LOG" 2>/dev/null | grep "first_task_started" | wc -l | tr -d ' ')
ALL_TASKS=$(tail -n +2 "$CASCADE_LOG" 2>/dev/null | grep "all_tasks_complete" | wc -l | tr -d ' ')
ALL_FEATURES=$(tail -n +2 "$CASCADE_LOG" 2>/dev/null | grep "all_features_complete" | wc -l | tr -d ' ')
# Count by flow
DEFAULT_FLOW=$(tail -n +2 "$CASCADE_LOG" 2>/dev/null | grep ",default_flow," | wc -l | tr -d ' ')
RAPID_FLOW=$(tail -n +2 "$CASCADE_LOG" 2>/dev/null | grep ",rapid_prototype_flow," | wc -l | tr -d ' ')
REVIEW_FLOW=$(tail -n +2 "$CASCADE_LOG" 2>/dev/null | grep ",with_review_flow," | wc -l | tr -d ' ')
cat > "$SUMMARY_LOG" <<EOF
{
"total_cascade_events": $TOTAL_EVENTS,
"automatic_events": $AUTO_EVENTS,
"manual_events": $MANUAL_EVENTS,
"by_event_type": {
"first_task_started": $FIRST_TASK,
"all_tasks_complete": $ALL_TASKS,
"all_features_complete": $ALL_FEATURES
},
"by_flow": {
"default_flow": $DEFAULT_FLOW,
"rapid_prototype_flow": $RAPID_FLOW,
"with_review_flow": $REVIEW_FLOW
},
"auto_percentage": $(( TOTAL_EVENTS > 0 ? (AUTO_EVENTS * 100) / TOTAL_EVENTS : 0 )),
"last_updated": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
}
EOF
echo ""
echo "📈 Summary Statistics:"
echo " Total Events: $TOTAL_EVENTS"
echo " Auto-Apply: $AUTO_EVENTS ($((TOTAL_EVENTS > 0 ? (AUTO_EVENTS * 100) / TOTAL_EVENTS : 0))%)"
echo " Manual Confirm: $MANUAL_EVENTS"
echo ""
echo " By Event Type:"
echo " first_task_started: $FIRST_TASK"
echo " all_tasks_complete: $ALL_TASKS"
echo " all_features_complete: $ALL_FEATURES"
echo ""
echo " By Workflow Flow:"
echo " default_flow: $DEFAULT_FLOW"
echo " rapid_prototype_flow: $RAPID_FLOW"
echo " with_review_flow: $REVIEW_FLOW"
fi
echo ""
echo "✓ Cascade events logged successfully"
echo " CSV Log: .claude/metrics/cascade-events.csv"
echo " Summary: .claude/metrics/cascade-summary.json"
echo ""
echo " Analytics Queries:"
echo " tail -10 .claude/metrics/cascade-events.csv # Recent events"
echo " cat .claude/metrics/cascade-summary.json # Summary stats"
echo ""
exit 0

View File

@@ -0,0 +1,161 @@
#!/bin/bash
# Flow-aware quality gate - different validation per workflow flow
# OPINIONATED: Skips tests for prototypes, enforces for production (default behavior)
#
# This example hook demonstrates the recommended opinionated approach:
# - rapid_prototype_flow: SKIP tests (fast iteration)
# - with_review_flow: STRICT validation (security/compliance)
# - default_flow: STANDARD tests (normal development)
#
# Customize flow detection and gates based on your project needs
INPUT=$(cat)
# Extract operation and container type
OPERATION=$(echo "$INPUT" | jq -r '.tool_input.operation')
CONTAINER_TYPE=$(echo "$INPUT" | jq -r '.tool_input.containerType')
STATUS=$(echo "$INPUT" | jq -r '.tool_input.status')
# Only run for feature status changes to testing/completed
if [ "$OPERATION" != "setStatus" ] || [ "$CONTAINER_TYPE" != "feature" ]; then
exit 0
fi
if [ "$STATUS" != "testing" ] && [ "$STATUS" != "completed" ]; then
exit 0
fi
# Extract feature ID
FEATURE_ID=$(echo "$INPUT" | jq -r '.tool_input.id')
# Query feature tags to determine active flow
DB_PATH="$CLAUDE_PROJECT_DIR/data/tasks.db"
TAGS=$(sqlite3 "$DB_PATH" \
"SELECT tags FROM Features WHERE id='$FEATURE_ID'" 2>/dev/null)
if [ -z "$TAGS" ]; then
echo "⚠️ Could not determine feature tags, using default_flow"
TAGS=""
fi
# Determine active flow from tags
FLOW="default_flow"
if echo "$TAGS" | grep -qE "prototype|spike|experiment"; then
FLOW="rapid_prototype_flow"
elif echo "$TAGS" | grep -qE "security|compliance|audit"; then
FLOW="with_review_flow"
fi
echo "════════════════════════════════════════════"
echo "🔍 FLOW-AWARE QUALITY GATE"
echo "════════════════════════════════════════════"
echo " Detected Flow: $FLOW"
echo " Feature Tags: $TAGS"
echo " Target Status: $STATUS"
echo ""
# Flow-specific quality gates
case "$FLOW" in
"rapid_prototype_flow")
# OPINIONATED: Skip tests for prototypes (fast iteration)
echo "⚡ RAPID PROTOTYPE FLOW"
echo " Skipping all quality gates for fast iteration"
echo " Rationale: Prototypes prioritize speed over validation"
echo ""
echo " ✅ Quality gate skipped (by design)"
echo "════════════════════════════════════════════"
exit 0
;;
"with_review_flow")
# OPINIONATED: Strict validation for security/compliance
echo "🔒 SECURITY/COMPLIANCE FLOW"
echo " Enforcing strict quality gates"
echo ""
cd "$CLAUDE_PROJECT_DIR"
# Gate 1: Full test suite
echo " [1/2] Running full test suite..."
if ! ./gradlew test; then
cat << EOF
{
"decision": "block",
"reason": "Security/compliance flow requires all tests to pass. Please fix failing tests before completing feature."
}
EOF
exit 0
fi
echo " ✅ Tests passed"
# Gate 2: Security scan (if trivy available)
if command -v trivy >/dev/null 2>&1; then
echo " [2/2] Running security vulnerability scan..."
if ! trivy fs .; then
cat << EOF
{
"decision": "block",
"reason": "Security vulnerabilities detected. Please remediate before completing feature."
}
EOF
exit 0
fi
echo " ✅ Security scan passed"
else
echo " [2/2] Security scan tool (trivy) not installed, skipping"
echo " ⚠️ Install trivy for security validation"
fi
echo ""
echo " ✅ All strict quality gates passed"
echo "════════════════════════════════════════════"
;;
"default_flow")
# OPINIONATED: Standard test suite for default flow
echo "✓ DEFAULT FLOW"
echo " Running standard quality gates"
echo ""
cd "$CLAUDE_PROJECT_DIR"
echo " [1/1] Running standard test suite..."
if ! ./gradlew test; then
cat << EOF
{
"decision": "block",
"reason": "Tests are failing. Please fix failing tests before completing feature."
}
EOF
exit 0
fi
echo " ✅ Tests passed"
echo ""
echo " ✅ Standard quality gates passed"
echo "════════════════════════════════════════════"
;;
*)
# Unknown flow, use default behavior
echo "⚠️ UNKNOWN FLOW: $FLOW"
echo " Falling back to default flow behavior"
echo ""
cd "$CLAUDE_PROJECT_DIR"
if ! ./gradlew test; then
cat << EOF
{
"decision": "block",
"reason": "Tests are failing. Please fix failing tests before completing feature."
}
EOF
exit 0
fi
echo " ✅ Tests passed"
echo "════════════════════════════════════════════"
;;
esac
exit 0

View File

@@ -0,0 +1,972 @@
# Task Orchestrator Hooks - Working Examples
This document provides complete working examples of hooks that integrate with Task Orchestrator's workflow cascade event system. All examples follow the **opinionated approach** (auto-apply by default) with clear guidance on when to use conservative alternatives.
## Overview
Three example hooks are provided:
1. **cascade-auto-progress.sh** - Opinionated auto-apply with audit trail (RECOMMENDED)
2. **flow-aware-gate.sh** - Adaptive quality gates based on workflow flow
3. **cascade-logger.sh** - Non-blocking analytics for learning patterns (SAFE for production)
All examples are located in: `src/main/resources/claude/skills/task-orchestrator-hooks-builder/example-hooks/`
## Quick Start
### Installation Steps
1. **Copy hook to your project's hooks directory**:
```bash
# Create hooks directory if it doesn't exist
mkdir -p .claude/hooks
# Copy desired example hook
cp src/main/resources/claude/skills/task-orchestrator-hooks-builder/example-hooks/cascade-auto-progress.sh \
.claude/hooks/cascade-auto-progress.sh
# Make executable
chmod +x .claude/hooks/cascade-auto-progress.sh
```
2. **Register hook in Claude Code settings**:
Edit `.claude/settings.local.json` (create if doesn't exist):
```json
{
"hooks": {
"postToolUse": [
{
"hook": ".claude/hooks/cascade-auto-progress.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
}
]
}
}
```
3. **Test the hook** (see Testing section below)
---
## Example 1: Cascade Auto-Progress (Opinionated)
### Purpose
Automatically logs cascade events for auto-application when `automatic=true`. This is the **RECOMMENDED opinionated approach** for most projects.
### Use Cases
✅ **Use this when:**
- Normal development workflows
- You trust the Task Orchestrator's cascade event logic
- You want automatic progression (Task complete → Feature progresses → Project progresses)
- You need an audit trail of all cascade events
⚠️ **Consider alternatives when:**
- Critical production deployments requiring manual approval
- Security/compliance workflows needing sign-off
- Learning/training environments where you want to see every step
- You need full control over every status transition
### Installation
```bash
# Copy to hooks directory
cp src/main/resources/claude/skills/task-orchestrator-hooks-builder/example-hooks/cascade-auto-progress.sh \
.claude/hooks/cascade-auto-progress.sh
# Make executable
chmod +x .claude/hooks/cascade-auto-progress.sh
```
**Register in `.claude/settings.local.json`:**
```json
{
"hooks": {
"postToolUse": [
{
"hook": ".claude/hooks/cascade-auto-progress.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
}
]
}
}
```
### Expected Behavior
**When a cascade event occurs (e.g., all tasks in a feature complete):**
```
════════════════════════════════════════════
🔄 CASCADE EVENT PROCESSING (Opinionated Mode)
════════════════════════════════════════════
Event #1: all_tasks_complete
Target: User Authentication (feature)
Status: in-development → testing
Flow: default_flow
Reason: All tasks completed, ready for testing phase
✅ AUTO-APPLY: Logging for orchestrator to apply status
Cascade event logged - orchestrator will apply status automatically
════════════════════════════════════════════
✓ Cascade event processing complete
Log: .claude/metrics/cascade-events.csv
════════════════════════════════════════════
```
**Audit Trail (`~/.claude/metrics/cascade-events.csv`):**
```csv
2025-10-27T14:30:45Z,all_tasks_complete,feature,abc-123-def,"User Authentication",in-development,testing,default_flow,auto
2025-10-27T14:32:10Z,first_task_started,feature,abc-123-def,"User Authentication",planning,in-development,default_flow,auto
```
### Sample Test Input
You can test this hook by simulating a manage_container response with cascade events:
```bash
# Create test input file
cat > test-cascade-input.json << 'EOF'
{
"tool": "mcp__task-orchestrator__manage_container",
"tool_input": {
"operation": "setStatus",
"containerType": "task",
"id": "task-uuid-123",
"status": "completed"
},
"tool_output": {
"success": true,
"data": {
"cascadeEvents": [
{
"event": "all_tasks_complete",
"targetType": "feature",
"targetId": "feature-uuid-456",
"targetName": "User Authentication",
"currentStatus": "in-development",
"suggestedStatus": "testing",
"flow": "default_flow",
"automatic": true,
"reason": "All tasks completed, ready for testing phase"
}
]
}
}
}
EOF
# Test the hook
cat test-cascade-input.json | .claude/hooks/cascade-auto-progress.sh
```
### Customization
**To make MORE conservative (require manual confirmation):**
Change line 52 from:
```bash
if [ "$AUTOMATIC" == "true" ]; then
```
To:
```bash
if [ "$AUTOMATIC" == "true" ] && [ "$FLOW" != "with_review_flow" ]; then
```
This will require manual confirmation for security/compliance workflows.
**To disable auto-apply entirely:**
Use the Progressive Disclosure example instead (see Template 16 in hook-templates.md).
---
## Example 2: Flow-Aware Quality Gate
### Purpose
Adapts quality gate behavior based on workflow flow. Skips tests for prototypes, enforces strict validation for security features, runs standard tests for normal development.
### Use Cases
✅ **Use this when:**
- You have different types of features (prototypes, production, security)
- You want fast iteration on experimental work
- You need strict validation for compliance features
- You tag your features consistently (prototype, security, etc.)
⚠️ **Consider alternatives when:**
- All features should have the same quality standards
- You don't use feature tags for workflow classification
- You prefer consistent behavior across all work
### Installation
```bash
# Copy to hooks directory
cp src/main/resources/claude/skills/task-orchestrator-hooks-builder/example-hooks/flow-aware-gate.sh \
.claude/hooks/flow-aware-gate.sh
# Make executable
chmod +x .claude/hooks/flow-aware-gate.sh
```
**Register in `.claude/settings.local.json`:**
```json
{
"hooks": {
"postToolUse": [
{
"hook": ".claude/hooks/flow-aware-gate.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
}
]
}
}
```
### Expected Behavior
**For a feature tagged with "prototype":**
```
════════════════════════════════════════════
🔍 FLOW-AWARE QUALITY GATE
════════════════════════════════════════════
Detected Flow: rapid_prototype_flow
Feature Tags: prototype, spike, frontend
Target Status: testing
⚡ RAPID PROTOTYPE FLOW
Skipping all quality gates for fast iteration
Rationale: Prototypes prioritize speed over validation
✅ Quality gate skipped (by design)
════════════════════════════════════════════
```
**For a feature tagged with "security":**
```
════════════════════════════════════════════
🔍 FLOW-AWARE QUALITY GATE
════════════════════════════════════════════
Detected Flow: with_review_flow
Feature Tags: security, authentication, api
Target Status: testing
🔒 SECURITY/COMPLIANCE FLOW
Enforcing strict quality gates
[1/2] Running full test suite...
✅ Tests passed (235 tests, 0 failures)
[2/2] Running security vulnerability scan...
✅ Security scan passed (0 vulnerabilities)
✅ All strict quality gates passed
════════════════════════════════════════════
```
**For a normal feature (default flow):**
```
════════════════════════════════════════════
🔍 FLOW-AWARE QUALITY GATE
════════════════════════════════════════════
Detected Flow: default_flow
Feature Tags: backend, api, enhancement
Target Status: testing
✓ DEFAULT FLOW
Running standard quality gates
[1/1] Running standard test suite...
✅ Tests passed (187 tests, 0 failures)
✅ Standard quality gates passed
════════════════════════════════════════════
```
### Flow Detection
The hook detects workflow flow from feature tags:
| Flow | Detected Tags | Behavior |
|------|--------------|----------|
| **rapid_prototype_flow** | prototype, spike, experiment | Skip all tests |
| **with_review_flow** | security, compliance, audit | Strict validation + security scan |
| **default_flow** | (anything else) | Standard test suite |
### Sample Test Input
```bash
# Create test input for security feature
cat > test-flow-gate-input.json << 'EOF'
{
"tool": "mcp__task-orchestrator__manage_container",
"tool_input": {
"operation": "setStatus",
"containerType": "feature",
"id": "feature-uuid-789",
"status": "testing"
},
"tool_output": {
"success": true,
"data": {
"id": "feature-uuid-789",
"tags": "security,authentication,api"
}
}
}
EOF
# Test the hook (will attempt to run gradlew test)
cat test-flow-gate-input.json | .claude/hooks/flow-aware-gate.sh
```
### Customization
**To add a new flow (e.g., "experimental_flow"):**
Add to flow detection (around line 42):
```bash
if echo "$TAGS" | grep -qE "prototype|spike|experiment"; then
FLOW="rapid_prototype_flow"
elif echo "$TAGS" | grep -qE "experimental|research"; then
FLOW="experimental_flow"
elif echo "$TAGS" | grep -qE "security|compliance|audit"; then
FLOW="with_review_flow"
fi
```
Then add case handling (around line 58):
```bash
case "$FLOW" in
"experimental_flow")
echo "🔬 EXPERIMENTAL FLOW"
echo " Running fast tests only, skipping integration tests"
./gradlew test -x integrationTest || {
# Block on failure
}
;;
```
**To make prototype flow less permissive:**
Change line 60-67 to run minimal tests instead of skipping entirely:
```bash
"rapid_prototype_flow")
echo "⚡ RAPID PROTOTYPE FLOW"
echo " Running smoke tests only (skipping full suite)"
./gradlew smokeTest || {
cat << EOF
{
"decision": "block",
"reason": "Even prototypes must pass smoke tests. Fix failing tests before proceeding."
}
EOF
exit 0
}
;;
```
---
## Example 3: Cascade Logger (Analytics)
### Purpose
Non-blocking analytics hook that logs all cascade events to CSV for understanding workflow patterns. **SAFE to add to production** - observation only, never blocks or modifies behavior.
### Use Cases
✅ **Use this when:**
- Learning how cascade events work
- Analyzing workflow patterns in your project
- Collecting metrics on automation effectiveness
- Need audit trail without affecting behavior
- Want to understand which events are automatic vs manual
✅ **Safe for:**
- Production environments (observation only)
- Learning environments
- Any project (zero risk)
### Installation
```bash
# Copy to hooks directory
cp src/main/resources/claude/skills/task-orchestrator-hooks-builder/example-hooks/cascade-logger.sh \
.claude/hooks/cascade-logger.sh
# Make executable
chmod +x .claude/hooks/cascade-logger.sh
```
**Register in `.claude/settings.local.json`:**
```json
{
"hooks": {
"postToolUse": [
{
"hook": ".claude/hooks/cascade-logger.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
}
]
}
}
```
### Expected Behavior
**When cascade events occur:**
```
📊 Cascade Event Logger - Recording events for analytics
✓ Event #1: all_tasks_complete (feature) - auto=true, flow=default_flow
✓ Event #2: first_task_started (feature) - auto=true, flow=rapid_prototype_flow
📈 Summary Statistics:
Total Events: 47
Auto-Apply: 42 (89%)
Manual Confirm: 5
By Event Type:
first_task_started: 15
all_tasks_complete: 28
all_features_complete: 4
By Workflow Flow:
default_flow: 32
rapid_prototype_flow: 10
with_review_flow: 5
✓ Cascade events logged successfully
CSV Log: .claude/metrics/cascade-events.csv
Summary: .claude/metrics/cascade-summary.json
Analytics Queries:
tail -10 .claude/metrics/cascade-events.csv # Recent events
cat .claude/metrics/cascade-summary.json # Summary stats
```
### CSV Output Format
**File**: `.claude/metrics/cascade-events.csv`
```csv
timestamp,event,target_type,target_id,target_name,current_status,suggested_status,flow,automatic,reason
2025-10-27T14:30:45Z,all_tasks_complete,feature,abc-123,"User Auth",in-development,testing,default_flow,true,"All tasks completed"
2025-10-27T14:32:10Z,first_task_started,feature,abc-123,"User Auth",planning,in-development,default_flow,true,"First task started"
```
### JSON Summary Output
**File**: `.claude/metrics/cascade-summary.json`
```json
{
"total_cascade_events": 47,
"automatic_events": 42,
"manual_events": 5,
"by_event_type": {
"first_task_started": 15,
"all_tasks_complete": 28,
"all_features_complete": 4
},
"by_flow": {
"default_flow": 32,
"rapid_prototype_flow": 10,
"with_review_flow": 5
},
"auto_percentage": 89,
"last_updated": "2025-10-27T14:35:22Z"
}
```
### Analytics Queries
**View recent events:**
```bash
tail -10 .claude/metrics/cascade-events.csv
```
**Count auto vs manual:**
```bash
tail -n +2 .claude/metrics/cascade-events.csv | grep ",true," | wc -l # Auto
tail -n +2 .claude/metrics/cascade-events.csv | grep ",false," | wc -l # Manual
```
**Find all security flow events:**
```bash
tail -n +2 .claude/metrics/cascade-events.csv | grep ",with_review_flow,"
```
**View summary statistics:**
```bash
cat .claude/metrics/cascade-summary.json | jq .
```
### Sample Test Input
```bash
# Create test input with multiple cascade events
cat > test-logger-input.json << 'EOF'
{
"tool": "mcp__task-orchestrator__manage_container",
"tool_input": {
"operation": "setStatus",
"containerType": "task",
"id": "task-uuid-123",
"status": "completed"
},
"tool_output": {
"success": true,
"data": {
"cascadeEvents": [
{
"event": "all_tasks_complete",
"targetType": "feature",
"targetId": "feature-uuid-456",
"targetName": "API Authentication",
"currentStatus": "in-development",
"suggestedStatus": "testing",
"flow": "default_flow",
"automatic": true,
"reason": "All 8 tasks completed successfully"
},
{
"event": "all_features_complete",
"targetType": "project",
"targetId": "project-uuid-789",
"targetName": "User Management System",
"currentStatus": "in-progress",
"suggestedStatus": "completed",
"flow": "with_review_flow",
"automatic": false,
"reason": "All features complete, requires final approval"
}
]
}
}
}
EOF
# Test the hook
cat test-logger-input.json | .claude/hooks/cascade-logger.sh
```
### Customization
This hook is safe as-is, but you can customize:
**Change CSV location:**
```bash
# Line 28 - change log directory
LOG_DIR="$CLAUDE_PROJECT_DIR/metrics" # Instead of .claude/metrics
```
**Add email alerts for manual confirmations:**
```bash
# After line 73, add:
if [ "$AUTOMATIC" == "false" ]; then
echo "Manual confirmation required for $TARGET_NAME" | \
mail -s "Task Orchestrator: Manual Approval Needed" admin@example.com
fi
```
**Export to external analytics:**
```bash
# After line 116, add:
curl -X POST https://analytics.example.com/api/cascade-events \
-H "Content-Type: application/json" \
-d @"$SUMMARY_LOG"
```
---
## Testing Your Hooks
### Testing with Real Operations
1. **Create a test task and complete it:**
```bash
# Your hooks will trigger on real manage_container operations
# Watch for hook output in Claude Code
```
2. **Check logs:**
```bash
ls -la .claude/metrics/
cat .claude/metrics/cascade-events.csv
cat .claude/metrics/cascade-summary.json
```
### Testing with Simulated Input
Create a test script to simulate cascade events:
```bash
#!/bin/bash
# test-cascade-hooks.sh - Simulate cascade events for testing
cat << 'EOF' | .claude/hooks/cascade-auto-progress.sh
{
"tool": "mcp__task-orchestrator__manage_container",
"tool_input": {
"operation": "setStatus",
"containerType": "task",
"id": "test-task-123",
"status": "completed"
},
"tool_output": {
"success": true,
"data": {
"cascadeEvents": [
{
"event": "all_tasks_complete",
"targetType": "feature",
"targetId": "test-feature-456",
"targetName": "Test Feature",
"currentStatus": "in-development",
"suggestedStatus": "testing",
"flow": "default_flow",
"automatic": true,
"reason": "All tasks completed for testing"
}
]
}
}
}
EOF
echo ""
echo "✓ Test completed. Check output above."
```
### Debugging Hooks
**Enable verbose output:**
```bash
# Add to top of hook (after #!/bin/bash)
set -x # Print each command
```
**Check hook execution:**
```bash
# Claude Code logs hook execution
# Look for "Running hook: .claude/hooks/..."
```
**Test JSON parsing:**
```bash
# Verify jq is working
echo '{"test": "value"}' | jq -r '.test'
# Should output: value
```
---
## Combining Multiple Hooks
You can use multiple hooks together. They run in the order listed in `settings.local.json`:
```json
{
"hooks": {
"postToolUse": [
{
"hook": ".claude/hooks/cascade-logger.sh",
"tools": ["mcp__task-orchestrator__manage_container"],
"comment": "Always log first (observation only)"
},
{
"hook": ".claude/hooks/flow-aware-gate.sh",
"tools": ["mcp__task-orchestrator__manage_container"],
"comment": "Then run quality gates (may block)"
},
{
"hook": ".claude/hooks/cascade-auto-progress.sh",
"tools": ["mcp__task-orchestrator__manage_container"],
"comment": "Finally handle cascade progression"
}
]
}
}
```
**Recommended Order:**
1. **Logger** (observation only, always safe)
2. **Quality gates** (may block if tests fail)
3. **Auto-progress** (applies status changes)
---
## Migration from Conservative to Opinionated
### Starting Conservative
If you're new to cascade events, start with the logger:
```json
{
"hooks": {
"postToolUse": [
{
"hook": ".claude/hooks/cascade-logger.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
}
]
}
}
```
**Goal**: Understand cascade event patterns in your project.
**When to progress**: After 1-2 weeks, review `.claude/metrics/cascade-summary.json`. If auto_percentage > 80%, you're ready for opinionated approach.
### Adopting Opinionated Approach
Add cascade-auto-progress.sh:
```json
{
"hooks": {
"postToolUse": [
{
"hook": ".claude/hooks/cascade-logger.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
},
{
"hook": ".claude/hooks/cascade-auto-progress.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
}
]
}
}
```
**Goal**: Automatic progression with full audit trail.
**When to progress**: Once comfortable with automatic behavior, consider flow-aware gates.
### Adding Flow-Aware Gates
Enable adaptive quality gates:
```json
{
"hooks": {
"postToolUse": [
{
"hook": ".claude/hooks/cascade-logger.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
},
{
"hook": ".claude/hooks/flow-aware-gate.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
},
{
"hook": ".claude/hooks/cascade-auto-progress.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
}
]
}
}
```
**Goal**: Prototype features skip tests, security features enforce strict validation.
**Requirement**: Consistent feature tagging (prototype, security, etc.).
---
## Troubleshooting
### Hook Not Executing
**Check registration:**
```bash
cat .claude/settings.local.json
# Verify hook is listed under postToolUse
```
**Check executable permission:**
```bash
ls -la .claude/hooks/
# Should show -rwxr-xr-x (executable)
```
**Check tool name:**
```json
{
"tools": ["mcp__task-orchestrator__manage_container"]
// Note: Double underscores, correct tool name
}
```
### Cascade Events Not Appearing
**Verify operation triggers cascade:**
```bash
# Cascade events only occur on certain operations:
# - Completing a task (when all tasks in feature complete)
# - Starting first task in a feature
# - Completing all features in a project
```
**Check feature/project has children:**
```bash
# Feature must have tasks
# Project must have features
# Otherwise no cascade occurs
```
### JSON Parsing Errors
**Install jq if missing:**
```bash
# Ubuntu/Debian
sudo apt-get install jq
# macOS
brew install jq
# Windows (via scoop)
scoop install jq
```
**Test jq installation:**
```bash
echo '{"test": "value"}' | jq -r '.test'
# Should output: value
```
### Gradlew Not Found (flow-aware-gate.sh)
**Verify project structure:**
```bash
ls -la ./gradlew
# Should exist and be executable
```
**Adjust path in hook:**
```bash
# Line 76, 120, 146 - change to absolute path
cd "$CLAUDE_PROJECT_DIR"
./gradlew test
```
---
## Best Practices
### General Guidelines
1. **Start with logger** - Always begin with cascade-logger.sh to learn patterns
2. **Test in isolation** - Test each hook individually before combining
3. **Keep hooks simple** - Each hook should do one thing well
4. **Exit cleanly** - Always exit 0 unless blocking (exit 1 requires JSON)
5. **Log everything** - Create audit trails for debugging
### Security Considerations
1. **Review hook source** - Always review hook code before installation
2. **Limit permissions** - Hooks run with user permissions, no sudo required
3. **Validate input** - Check for null/empty values from JSON
4. **Handle errors** - Use `|| true` for non-critical operations
5. **Don't store secrets** - Never hardcode credentials in hooks
### Performance Tips
1. **Use lightweight operations** - Hooks add overhead to every operation
2. **Filter early** - Exit early if operation doesn't match
3. **Batch operations** - Update metrics once, not per event
4. **Avoid network calls** - Local operations are faster
5. **Cache database queries** - SQLite queries can be slow for large databases
---
## Additional Resources
### Hook Templates
See `hook-templates.md` for 16 copy-paste templates covering:
- Templates 1-11: Core hook patterns (git, testing, metrics, notifications)
- Templates 12-16: Cascade event integration (NEW in v2.0)
### Documentation
- **SKILL.md** - Complete hook builder skill with interactive interview
- **docs/hooks-guide.md** - Comprehensive hook system documentation
- **WorkflowConfig.kt** - Source code for cascade event system
### Getting Help
1. Use the Task Orchestrator Hooks Builder skill in Claude Code
2. Read the interactive interview questions (handles 95% of use cases)
3. Review these examples for working patterns
4. Check `docs/hooks-guide.md` for advanced scenarios
---
## Summary
**Recommended Setup** (Most projects):
```json
{
"hooks": {
"postToolUse": [
{
"hook": ".claude/hooks/cascade-logger.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
},
{
"hook": ".claude/hooks/cascade-auto-progress.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
}
]
}
}
```
**Full Setup** (With flow-aware quality gates):
```json
{
"hooks": {
"postToolUse": [
{
"hook": ".claude/hooks/cascade-logger.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
},
{
"hook": ".claude/hooks/flow-aware-gate.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
},
{
"hook": ".claude/hooks/cascade-auto-progress.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
}
]
}
}
```
**Conservative Setup** (Learning mode):
```json
{
"hooks": {
"postToolUse": [
{
"hook": ".claude/hooks/cascade-logger.sh",
"tools": ["mcp__task-orchestrator__manage_container"]
}
]
}
}
```
All examples follow the **opinionated approach** - auto-apply by default with clear guidance on when to use conservative alternatives. Start with the logger to learn, then adopt auto-progress when comfortable.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,455 @@
# Cascade Events - Detailed Reference
This document provides comprehensive information about cascade events in Task Orchestrator v2.0+.
## What Are Cascade Events?
Cascade events occur when completing one entity should trigger progression of a parent entity:
| Event | Trigger | Effect |
|-------|---------|--------|
| **first_task_started** | First task in feature moves to `in-progress` | Feature should move from `planning` to `in-development` |
| **all_tasks_complete** | All tasks in feature complete | Feature should move to `testing` |
| **all_features_complete** | All features in project complete | Project should move to `completed` |
Cascade events enable **automatic workflow progression** without manual intervention.
## How Hooks Receive Cascade Events
When `manage_container` operations trigger cascade events, the tool response includes a `cascadeEvents` array:
```json
{
"tool": "mcp__task-orchestrator__manage_container",
"tool_input": {
"operation": "setStatus",
"containerType": "task",
"id": "task-uuid-123",
"status": "completed"
},
"tool_output": {
"success": true,
"data": {
"cascadeEvents": [
{
"event": "all_tasks_complete",
"targetType": "feature",
"targetId": "feature-uuid-456",
"targetName": "User Authentication",
"currentStatus": "in-development",
"suggestedStatus": "testing",
"flow": "default_flow",
"automatic": true,
"reason": "All 8 tasks completed successfully"
}
]
}
}
}
```
## Cascade Event Fields
| Field | Type | Description |
|-------|------|-------------|
| **event** | string | Event type: `first_task_started`, `all_tasks_complete`, `all_features_complete` |
| **targetType** | string | Entity type affected: `task`, `feature`, `project` |
| **targetId** | UUID | ID of the entity that should change status |
| **targetName** | string | Human-readable name of the entity |
| **currentStatus** | string | Current status of the entity |
| **suggestedStatus** | string | Recommended next status based on workflow |
| **flow** | string | Active workflow flow: `default_flow`, `rapid_prototype_flow`, `with_review_flow` |
| **automatic** | boolean | `true` if safe to auto-apply, `false` if manual confirmation recommended |
| **reason** | string | Human-readable explanation of why this cascade event occurred |
## Workflow Flows
Cascade events include a `flow` field indicating the active workflow:
### default_flow
- Normal development workflow
- Standard quality gates
- Typical progression: planning → in-development → testing → completed
### rapid_prototype_flow
- Fast iteration for prototypes and experiments
- Relaxed quality gates (tests may be skipped)
- Detected by tags: `prototype`, `spike`, `experiment`
### with_review_flow
- Security and compliance features
- Strict quality gates (additional validation required)
- Detected by tags: `security`, `compliance`, `audit`
## Hook Integration Patterns
### Pattern 1: Opinionated Auto-Apply (Recommended)
Automatically log cascade events for auto-application when `automatic=true`:
```bash
#!/bin/bash
# Opinionated auto-progress
INPUT=$(cat)
CASCADE_EVENTS=$(echo "$INPUT" | jq -r '.tool_output.data.cascadeEvents // []')
if [ "$CASCADE_EVENTS" == "[]" ]; then
exit 0
fi
echo "$CASCADE_EVENTS" | jq -c '.[]' | while read -r event; do
AUTOMATIC=$(echo "$event" | jq -r '.automatic')
if [ "$AUTOMATIC" == "true" ]; then
echo "✅ AUTO-APPLY: Logging for orchestrator to apply status"
# Log event for audit trail
# Orchestration Skills will apply status change
else
echo "⚠️ MANUAL CONFIRMATION: User approval required"
fi
done
exit 0
```
**When to use**: Normal development workflows where you trust cascade logic.
**Template**: See Template 12 in hook-templates.md
### Pattern 2: Flow-Aware Quality Gates
Adapt quality gates based on workflow flow:
```bash
#!/bin/bash
# Flow-aware quality gate
INPUT=$(cat)
OPERATION=$(echo "$INPUT" | jq -r '.tool_input.operation')
CONTAINER_TYPE=$(echo "$INPUT" | jq -r '.tool_input.containerType')
STATUS=$(echo "$INPUT" | jq -r '.tool_input.status')
# Only run for feature status changes to testing/completed
if [ "$OPERATION" != "setStatus" ] || [ "$CONTAINER_TYPE" != "feature" ]; then
exit 0
fi
# Query feature tags to determine flow
FEATURE_ID=$(echo "$INPUT" | jq -r '.tool_input.id')
DB_PATH="$CLAUDE_PROJECT_DIR/data/tasks.db"
TAGS=$(sqlite3 "$DB_PATH" "SELECT tags FROM Features WHERE id='$FEATURE_ID'" 2>/dev/null)
# Determine flow from tags
FLOW="default_flow"
if echo "$TAGS" | grep -qE "prototype|spike|experiment"; then
FLOW="rapid_prototype_flow"
elif echo "$TAGS" | grep -qE "security|compliance|audit"; then
FLOW="with_review_flow"
fi
case "$FLOW" in
"rapid_prototype_flow")
echo "⚡ Rapid prototype flow: Skipping tests"
exit 0
;;
"with_review_flow")
echo "🔒 Security flow: Enforcing strict validation"
./gradlew test integrationTest securityScan || {
cat << EOF
{
"decision": "block",
"reason": "Security features must pass all quality gates."
}
EOF
exit 0
}
;;
"default_flow")
./gradlew test || {
cat << EOF
{
"decision": "block",
"reason": "Tests are failing."
}
EOF
exit 0
}
;;
esac
exit 0
```
**When to use**: Projects with different feature types (prototypes, production, security).
**Template**: See Template 13 in hook-templates.md
### Pattern 3: Analytics and Metrics
Non-blocking observation for understanding patterns:
```bash
#!/bin/bash
# Cascade event logger (safe for production)
INPUT=$(cat)
CASCADE_EVENTS=$(echo "$INPUT" | jq -r '.tool_output.data.cascadeEvents // []')
if [ "$CASCADE_EVENTS" == "[]" ]; then
exit 0
fi
LOG_DIR="$CLAUDE_PROJECT_DIR/.claude/metrics"
mkdir -p "$LOG_DIR"
CASCADE_LOG="$LOG_DIR/cascade-events.csv"
# Create header if needed
if [ ! -f "$CASCADE_LOG" ]; then
echo "timestamp,event,target_type,target_id,target_name,current_status,suggested_status,flow,automatic" \
> "$CASCADE_LOG"
fi
# Log each event
echo "$CASCADE_EVENTS" | jq -c '.[]' | while read -r event; do
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
EVENT_TYPE=$(echo "$event" | jq -r '.event')
TARGET_TYPE=$(echo "$event" | jq -r '.targetType')
# ... extract other fields ...
echo "$TIMESTAMP,$EVENT_TYPE,$TARGET_TYPE,..." >> "$CASCADE_LOG"
done
exit 0
```
**When to use**: Always safe - observation only, never blocks or modifies behavior.
**Template**: See Template 15 in hook-templates.md
### Pattern 4: Progressive Disclosure (Conservative)
Show suggestions but require manual confirmation:
```bash
#!/bin/bash
# Conservative progressive disclosure
INPUT=$(cat)
CASCADE_EVENTS=$(echo "$INPUT" | jq -r '.tool_output.data.cascadeEvents // []')
if [ "$CASCADE_EVENTS" == "[]" ]; then
exit 0
fi
echo "════════════════════════════════════════════"
echo "🔔 WORKFLOW CASCADE EVENTS DETECTED"
echo "════════════════════════════════════════════"
echo "$CASCADE_EVENTS" | jq -c '.[]' | while read -r event; do
TARGET_NAME=$(echo "$event" | jq -r '.targetName')
CURRENT=$(echo "$event" | jq -r '.currentStatus')
SUGGESTED=$(echo "$event" | jq -r '.suggestedStatus')
echo "💡 Suggestion: $TARGET_NAME ($CURRENT$SUGGESTED)"
echo " ⚠️ Manual confirmation required"
done
exit 0
```
**When to use**: Critical production deployments, security features, learning environments.
**Template**: See Template 16 in hook-templates.md
## Working Examples
Three complete example hooks are provided in `example-hooks/`:
1. **cascade-auto-progress.sh** - Opinionated auto-apply with audit trail (RECOMMENDED)
2. **flow-aware-gate.sh** - Adaptive quality gates based on workflow flow
3. **cascade-logger.sh** - Non-blocking analytics (SAFE for production)
See `examples.md` for:
- Installation instructions
- Expected behavior
- Sample test inputs
- Customization guidance
- Testing strategies
## Opinionated vs Conservative Approaches
### Opinionated (Recommended)
- ✅ Auto-apply when `automatic=true`
- ✅ Trust Task Orchestrator's cascade logic
- ✅ Fast workflow progression
- ✅ Audit trail via logging
- ⚠️ Not suitable for critical production, security features
### Conservative
- ✅ Always require manual confirmation
- ✅ Full control over every transition
- ✅ Suitable for any environment
- ⚠️ Slower workflow progression
- ⚠️ More manual intervention
### Migration Path
1. **Start Conservative**: Use cascade-logger.sh (observation only)
2. **Learn Patterns**: After 1-2 weeks, review `.claude/metrics/cascade-summary.json`
3. **Adopt Opinionated**: If `auto_percentage > 80%`, switch to cascade-auto-progress.sh
4. **Add Flow Gates**: Once comfortable, add flow-aware-gate.sh
## Hook Templates
Five cascade event templates are available in `hook-templates.md`:
- **Template 12**: Cascade Event Responder (Opinionated) - Auto-apply with audit trail
- **Template 13**: Flow-Aware Quality Gate - Adaptive quality gates per flow
- **Template 14**: Custom Event Handler - React to specific cascade events
- **Template 15**: Cascade Event Logger - Analytics and metrics
- **Template 16**: Progressive Disclosure (Conservative) - Manual confirmation
## Configuration Example
Register cascade event hooks in `.claude/settings.local.json`:
```json
{
"hooks": {
"postToolUse": [
{
"hook": ".claude/hooks/cascade-logger.sh",
"tools": ["mcp__task-orchestrator__manage_container"],
"comment": "Always log first (observation only)"
},
{
"hook": ".claude/hooks/flow-aware-gate.sh",
"tools": ["mcp__task-orchestrator__manage_container"],
"comment": "Then run quality gates (may block)"
},
{
"hook": ".claude/hooks/cascade-auto-progress.sh",
"tools": ["mcp__task-orchestrator__manage_container"],
"comment": "Finally handle cascade progression"
}
]
}
}
```
**Recommended order**:
1. Logger (observation, always safe)
2. Quality gates (may block if tests fail)
3. Auto-progress (applies status changes)
## Custom Event Handlers
You can create hooks that react to specific cascade events:
```bash
#!/bin/bash
# Custom event handler - react to specific events
INPUT=$(cat)
CASCADE_EVENTS=$(echo "$INPUT" | jq -r '.tool_output.data.cascadeEvents // []')
echo "$CASCADE_EVENTS" | jq -c '.[]' | while read -r event; do
EVENT_TYPE=$(echo "$event" | jq -r '.event')
case "$EVENT_TYPE" in
"all_tasks_complete")
# Handle feature completion
echo "Feature ready for testing"
# Run feature-level validation
;;
"all_features_complete")
# Handle project completion
echo "Project ready for release"
# Run release preparation
;;
"first_task_started")
# Handle development start
echo "Feature development started"
# Create feature branch, notify team
;;
esac
done
exit 0
```
**Template**: See Template 14 in hook-templates.md
## Custom Workflow Flows
You can define custom flows by detecting specific tag patterns:
```bash
# Determine flow from tags
FLOW="default_flow"
if echo "$TAGS" | grep -qE "hotfix|urgent"; then
FLOW="hotfix_flow"
elif echo "$TAGS" | grep -qE "experimental|research"; then
FLOW="experimental_flow"
elif echo "$TAGS" | grep -qE "prototype|spike"; then
FLOW="rapid_prototype_flow"
elif echo "$TAGS" | grep -qE "security|compliance"; then
FLOW="with_review_flow"
fi
```
Then adapt hook behavior based on the custom flow.
## Troubleshooting
### Cascade Events Not Appearing
**Check operation**: Cascade events only occur on specific operations:
- Completing a task (when all tasks in feature complete)
- Starting first task in a feature
- Completing all features in a project
**Check entity has children**:
- Feature must have tasks
- Project must have features
- Otherwise no cascade occurs
### Hook Not Reacting to Cascade Events
**Verify JSON path**: Check that you're extracting from correct path:
```bash
CASCADE_EVENTS=$(echo "$INPUT" | jq -r '.tool_output.data.cascadeEvents // []')
```
**Check for empty array**:
```bash
if [ "$CASCADE_EVENTS" == "[]" ] || [ "$CASCADE_EVENTS" == "null" ]; then
exit 0
fi
```
### Flow Detection Not Working
**Check database query**: Verify SQLite query returns tags:
```bash
DB_PATH="$CLAUDE_PROJECT_DIR/data/tasks.db"
TAGS=$(sqlite3 "$DB_PATH" "SELECT tags FROM Features WHERE id='$FEATURE_ID'" 2>/dev/null)
if [ -z "$TAGS" ]; then
echo "⚠️ Could not determine feature tags, using default_flow"
fi
```
**Test tag patterns**: Ensure grep patterns match your tags:
```bash
# Test the pattern
echo "prototype,frontend,api" | grep -qE "prototype|spike|experiment" && echo "Matched!"
```
## Further Reading
- **examples.md** - Complete installation and usage guide for example hooks
- **hook-templates.md** - Templates 12-16 for cascade events
- **docs/hooks-guide.md** - Comprehensive hooks documentation with cascade event integration