Shell
chore: Sync all hooks including agentic and pipeline directories
Eddie Belaval8c8595d71c86
diff --git a/hooks/agentic/AGENTIC-PATTERNS.md b/hooks/agentic/AGENTIC-PATTERNS.mdnew file mode 100644index 0000000..a88bb2d--- /dev/null+++ b/hooks/agentic/AGENTIC-PATTERNS.md@@ -0,0 +1,89 @@+# Agentic Architecture Patterns++These hooks implement patterns from the "17 Agentic Architectures" to improve how Claude Code works.++## Implemented Patterns++### 1. Reflection (`reflection-gate.sh`)+**Trigger:** After Write/Edit of significant code files (50+ lines)+**What it does:** Signals that self-critique should occur before presenting final code+**Inspired by:** Architecture #1 - Reflection Pattern++```+Generate → Critique → Refine → Present+```++### 2. PEV Verification (`pev-verification.sh`)+**Trigger:** Before/after Bash commands, especially commits and deployments+**What it does:** Runs verification checks (types, lint, tests, security)+**Inspired by:** Architecture #6 - Plan-Execute-Verify++```+Plan → Execute → Verify → If Failed: Re-plan+```++**Checks performed:**+- TypeScript type errors (`tsc --noEmit`)+- Lint issues (`npm run lint`)+- Test failures (`npm test`)+- Git sanity (merge conflicts, large diffs)+- Security (exposed secrets in staged changes)++### 3. Metacognitive (`metacognitive-check.sh`)+**Trigger:** On user prompt submit+**What it does:** Detects high-stakes or speculative requests, prompts confidence signaling+**Inspired by:** Architecture #17 - Reflexive Metacognitive++**Detection keywords:**+- High-stakes: production, security, payment, medical, legal, compliance, HIPAA, GDPR+- Speculative: best practice, should I, recommend, opinion, predict++## Instructions (in CLAUDE.md)++In addition to hooks, behavioral instructions are added to CLAUDE.md:++1. **Pattern 1: Reflection** - Self-critique significant code before presenting+2. **Pattern 2: PEV** - Verify outcomes before commits+3. **Pattern 3: Metacognitive** - Express confidence levels, say "I don't know"+4. **Pattern 4: Tree of Thoughts** - Multiple approaches for complex problems+5. **Pattern 5: Ensemble** - Multi-perspective analysis for important decisions++## Hook Registration++Hooks are registered in `~/.claude/hooks.json`:++```json+{+ "post-tool": {+ "Write": ["agentic/reflection-gate.sh", ...],+ "Edit": ["agentic/reflection-gate.sh", ...],+ "Bash": ["agentic/pev-verification.sh"]+ },+ "user-prompt-submit": [+ "agentic/metacognitive-check.sh",+ ...+ ],+ "pre-tool": {+ "Bash": ["agentic/pev-verification.sh"]+ }+}+```++## Debugging++Logs are written to:+- `~/.claude/debug/reflection-gate.log`+- `~/.claude/debug/pev-verification.log`+- `~/.claude/debug/metacognitive.log`++Session state files:+- `~/.claude/session-env/pending-reflection.json`+- `~/.claude/session-env/pev-report.json`+- `~/.claude/session-env/confidence-context.json`++## Source Material++These patterns are based on:+- Repository: `~/Development/all-agentic-architectures/`+- Notebooks: 01_reflection.ipynb, 06_PEV.ipynb, 17_reflexive_metacognitive.ipynb+- Original author: Fareed Khandiff --git a/hooks/agentic/metacognitive-check.sh b/hooks/agentic/metacognitive-check.shnew file mode 100755index 0000000..8df3819--- /dev/null+++ b/hooks/agentic/metacognitive-check.sh@@ -0,0 +1,166 @@+#!/bin/bash+# =============================================================================+# METACOGNITIVE CHECK HOOK+# Agentic Architecture Pattern #17: Reflexive Metacognitive+#+# Prompts confidence assessment for complex or ambiguous requests.+# Encourages "I don't know" when appropriate.+# =============================================================================++HOOK_DIR="$(dirname "$0")"+LOG_FILE="$HOME/.claude/debug/metacognitive.log"+CONFIDENCE_FILE="$HOME/.claude/session-env/confidence-context.json"++mkdir -p "$(dirname "$LOG_FILE")"+mkdir -p "$(dirname "$CONFIDENCE_FILE")"++log() {+ echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"+}++# Get the user's message from stdin or environment+USER_MESSAGE="${CLAUDE_USER_MESSAGE:-}"++# If no message provided, try to read from stdin+if [[ -z "$USER_MESSAGE" ]]; then+ if [[ -p /dev/stdin ]]; then+ USER_MESSAGE=$(cat)+ fi+fi++# Skip if no message+if [[ -z "$USER_MESSAGE" ]]; then+ exit 0+fi++log "Analyzing message for metacognitive signals..."++# =============================================================================+# DETECT HIGH-UNCERTAINTY PATTERNS+# =============================================================================++# Keywords that suggest high-stakes decisions+HIGH_STAKES_KEYWORDS=(+ "production"+ "deploy"+ "security"+ "authentication"+ "payment"+ "financial"+ "medical"+ "legal"+ "compliance"+ "HIPAA"+ "GDPR"+ "PCI"+ "delete all"+ "drop table"+ "migrate"+)++# Keywords that suggest speculation or uncertainty is appropriate+SPECULATIVE_KEYWORDS=(+ "best practice"+ "should I"+ "is it better"+ "what's the right way"+ "how would you"+ "opinion"+ "recommend"+ "future"+ "predict"+ "trend"+ "will this work"+)++# Keywords that suggest the user expects certainty+CERTAINTY_EXPECTED=(+ "exactly"+ "precisely"+ "guarantee"+ "always"+ "never"+ "definitely"+ "100%"+ "for sure"+)++# =============================================================================+# ANALYZE MESSAGE+# =============================================================================++CONFIDENCE_LEVEL="high"+CONFIDENCE_SIGNALS=()+METACOGNITIVE_PROMPT=""++MESSAGE_LOWER=$(echo "$USER_MESSAGE" | tr '[:upper:]' '[:lower:]')++# Check for high-stakes keywords+for keyword in "${HIGH_STAKES_KEYWORDS[@]}"; do+ if [[ "$MESSAGE_LOWER" == *"$keyword"* ]]; then+ CONFIDENCE_SIGNALS+=("high-stakes-domain:$keyword")+ CONFIDENCE_LEVEL="requires-verification"+ log "Detected high-stakes keyword: $keyword"+ fi+done++# Check for speculative keywords+for keyword in "${SPECULATIVE_KEYWORDS[@]}"; do+ if [[ "$MESSAGE_LOWER" == *"$keyword"* ]]; then+ CONFIDENCE_SIGNALS+=("speculative-request:$keyword")+ if [[ "$CONFIDENCE_LEVEL" != "requires-verification" ]]; then+ CONFIDENCE_LEVEL="medium"+ fi+ log "Detected speculative keyword: $keyword"+ fi+done++# Check for certainty expectations+for keyword in "${CERTAINTY_EXPECTED[@]}"; do+ if [[ "$MESSAGE_LOWER" == *"$keyword"* ]]; then+ CONFIDENCE_SIGNALS+=("certainty-expected:$keyword")+ log "Detected certainty expectation: $keyword"+ fi+done++# =============================================================================+# GENERATE METACOGNITIVE GUIDANCE+# =============================================================================++case "$CONFIDENCE_LEVEL" in+ "requires-verification")+ METACOGNITIVE_PROMPT="METACOGNITIVE_ALERT: This request involves high-stakes domain ($keyword). Express confidence levels explicitly. If uncertain, say so. Consider: 'I'm confident about X, but less certain about Y because...'"+ ;;+ "medium")+ METACOGNITIVE_PROMPT="METACOGNITIVE_NOTE: This appears to be a speculative or opinion-based question. Consider offering multiple perspectives and expressing uncertainty where appropriate."+ ;;+ *)+ # No special guidance needed+ METACOGNITIVE_PROMPT=""+ ;;+esac++# =============================================================================+# SAVE CONTEXT FOR CLAUDE+# =============================================================================++SIGNALS_JSON=$(printf '%s\n' "${CONFIDENCE_SIGNALS[@]}" | jq -R . | jq -s .)++cat > "$CONFIDENCE_FILE" << EOF+{+ "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",+ "confidence_level": "$CONFIDENCE_LEVEL",+ "signals": $SIGNALS_JSON,+ "metacognitive_prompt": "$METACOGNITIVE_PROMPT"+}+EOF++# =============================================================================+# OUTPUT TO CLAUDE+# =============================================================================++if [[ -n "$METACOGNITIVE_PROMPT" ]]; then+ echo "$METACOGNITIVE_PROMPT"+fi++exit 0diff --git a/hooks/agentic/pev-verification.sh b/hooks/agentic/pev-verification.shnew file mode 100755index 0000000..fc1601a--- /dev/null+++ b/hooks/agentic/pev-verification.sh@@ -0,0 +1,196 @@+#!/bin/bash+# =============================================================================+# PEV VERIFICATION HOOK+# Agentic Architecture Pattern #6: Plan → Execute → Verify+#+# Verifies outcomes before commits and deployments.+# Catches errors that would otherwise propagate to production.+# =============================================================================++HOOK_DIR="$(dirname "$0")"+LOG_FILE="$HOME/.claude/debug/pev-verification.log"+VERIFICATION_REPORT="$HOME/.claude/session-env/pev-report.json"++mkdir -p "$(dirname "$LOG_FILE")"+mkdir -p "$(dirname "$VERIFICATION_REPORT")"++log() {+ echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"+}++# Detect what kind of operation is happening+OPERATION="${CLAUDE_OPERATION:-unknown}"+CONTEXT="${CLAUDE_CONTEXT:-}"++log "PEV verification triggered for operation: $OPERATION"++# Initialize verification results+VERIFICATION_PASSED=true+ISSUES=()+WARNINGS=()++# =============================================================================+# VERIFICATION CHECKS+# =============================================================================++# Check 1: TypeScript/JavaScript type errors+check_types() {+ if [[ -f "package.json" ]] && grep -q "typescript" package.json 2>/dev/null; then+ log "Running TypeScript check..."+ if command -v npx &>/dev/null; then+ TSC_OUTPUT=$(npx tsc --noEmit 2>&1 || true)+ if echo "$TSC_OUTPUT" | grep -q "error TS"; then+ ERROR_COUNT=$(echo "$TSC_OUTPUT" | grep -c "error TS" || echo "0")+ ISSUES+=("TypeScript: $ERROR_COUNT type errors detected")+ VERIFICATION_PASSED=false+ log "TypeScript check FAILED: $ERROR_COUNT errors"+ else+ log "TypeScript check PASSED"+ fi+ fi+ fi+}++# Check 2: Lint errors+check_lint() {+ if [[ -f "package.json" ]] && grep -q '"lint"' package.json 2>/dev/null; then+ log "Running lint check..."+ LINT_OUTPUT=$(npm run lint 2>&1 || true)+ if echo "$LINT_OUTPUT" | grep -qE "(error|Error:)"; then+ ERROR_COUNT=$(echo "$LINT_OUTPUT" | grep -cE "(error|Error:)" || echo "0")+ WARNINGS+=("Lint: $ERROR_COUNT lint issues detected")+ log "Lint check found issues: $ERROR_COUNT"+ else+ log "Lint check PASSED"+ fi+ fi+}++# Check 3: Test failures+check_tests() {+ if [[ -f "package.json" ]] && grep -q '"test"' package.json 2>/dev/null; then+ log "Running quick test check..."+ # Run tests with short timeout to catch obvious failures+ TEST_OUTPUT=$(timeout 60 npm test 2>&1 || true)+ if echo "$TEST_OUTPUT" | grep -qE "(FAIL|failed|Error:)"; then+ FAIL_COUNT=$(echo "$TEST_OUTPUT" | grep -c "FAIL" || echo "?")+ ISSUES+=("Tests: $FAIL_COUNT test suites failing")+ VERIFICATION_PASSED=false+ log "Test check FAILED"+ else+ log "Test check PASSED"+ fi+ fi+}++# Check 4: Git status sanity+check_git_status() {+ if git rev-parse --git-dir &>/dev/null; then+ log "Checking git status..."++ # Check for merge conflicts+ if git diff --name-only --diff-filter=U | grep -q .; then+ ISSUES+=("Git: Unresolved merge conflicts detected")+ VERIFICATION_PASSED=false+ log "Git check FAILED: merge conflicts"+ fi++ # Check for large uncommitted changes+ CHANGED_FILES=$(git diff --name-only | wc -l | tr -d ' ')+ if [[ "$CHANGED_FILES" -gt 20 ]]; then+ WARNINGS+=("Git: $CHANGED_FILES files changed - consider smaller commits")+ log "Git check WARNING: many changed files"+ fi++ log "Git check completed"+ fi+}++# Check 5: Security scan (basic)+check_security() {+ log "Running basic security scan..."++ # Check for exposed secrets+ if git rev-parse --git-dir &>/dev/null; then+ SECRET_PATTERNS='(API_KEY|SECRET|PASSWORD|TOKEN|PRIVATE_KEY).*=.*["\047][^"\047]{8,}'+ EXPOSED=$(git diff --cached 2>/dev/null | grep -E "$SECRET_PATTERNS" || true)+ if [[ -n "$EXPOSED" ]]; then+ ISSUES+=("Security: Potential secrets detected in staged changes")+ VERIFICATION_PASSED=false+ log "Security check FAILED: potential secrets"+ else+ log "Security check PASSED"+ fi+ fi+}++# =============================================================================+# RUN VERIFICATIONS BASED ON OPERATION TYPE+# =============================================================================++case "$OPERATION" in+ "pre-commit"|"commit")+ check_types+ check_lint+ check_git_status+ check_security+ ;;+ "pre-deploy"|"deploy")+ check_types+ check_lint+ check_tests+ check_security+ ;;+ "pre-pr"|"pr")+ check_types+ check_lint+ check_tests+ check_git_status+ check_security+ ;;+ *)+ # Default: run basic checks+ check_types+ check_git_status+ ;;+esac++# =============================================================================+# GENERATE REPORT+# =============================================================================++ISSUE_JSON=$(printf '%s\n' "${ISSUES[@]}" | jq -R . | jq -s .)+WARNING_JSON=$(printf '%s\n' "${WARNINGS[@]}" | jq -R . | jq -s .)++cat > "$VERIFICATION_REPORT" << EOF+{+ "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",+ "operation": "$OPERATION",+ "verification_passed": $VERIFICATION_PASSED,+ "issues": $ISSUE_JSON,+ "warnings": $WARNING_JSON+}+EOF++# =============================================================================+# OUTPUT TO CLAUDE+# =============================================================================++if [[ "$VERIFICATION_PASSED" == "false" ]]; then+ echo "PEV_VERIFICATION_FAILED: Verification detected critical issues:"+ for issue in "${ISSUES[@]}"; do+ echo " - $issue"+ done+ echo "RECOMMENDATION: Address these issues before proceeding."+ exit 1+elif [[ ${#WARNINGS[@]} -gt 0 ]]; then+ echo "PEV_VERIFICATION_WARNING: Verification passed with warnings:"+ for warning in "${WARNINGS[@]}"; do+ echo " - $warning"+ done+ echo "RECOMMENDATION: Consider addressing these warnings."+ exit 0+else+ echo "PEV_VERIFICATION_PASSED: All checks passed."+ exit 0+fidiff --git a/hooks/agentic/reflection-gate.sh b/hooks/agentic/reflection-gate.shnew file mode 100755index 0000000..f319ea8--- /dev/null+++ b/hooks/agentic/reflection-gate.sh@@ -0,0 +1,72 @@+#!/bin/bash+# =============================================================================+# REFLECTION GATE HOOK+# Agentic Architecture Pattern #1: Reflection+#+# Triggers self-critique and refinement for significant code outputs.+# Based on: Generate → Critique → Refine pattern+# =============================================================================++HOOK_DIR="$(dirname "$0")"+LOG_FILE="$HOME/.claude/debug/reflection-gate.log"++# Ensure log directory exists+mkdir -p "$(dirname "$LOG_FILE")"++log() {+ echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"+}++# Get the file that was just written/edited+FILE_PATH="${CLAUDE_FILE_PATH:-$1}"+TOOL_NAME="${CLAUDE_TOOL_NAME:-Write}"++# Skip if no file path+if [[ -z "$FILE_PATH" ]]; then+ exit 0+fi++# Get file extension+EXT="${FILE_PATH##*.}"++# Only trigger reflection for significant code files+SIGNIFICANT_EXTENSIONS="ts tsx js jsx py rs go java kt swift"+if [[ ! " $SIGNIFICANT_EXTENSIONS " =~ " $EXT " ]]; then+ exit 0+fi++# Check file size - only reflect on substantial changes (>50 lines)+if [[ -f "$FILE_PATH" ]]; then+ LINE_COUNT=$(wc -l < "$FILE_PATH" | tr -d ' ')+ if [[ "$LINE_COUNT" -lt 50 ]]; then+ log "Skipping reflection for $FILE_PATH ($LINE_COUNT lines - below threshold)"+ exit 0+ fi+fi++# Check if this is a new file or significant edit+CHANGE_TYPE="modified"+if [[ "$TOOL_NAME" == "Write" ]]; then+ CHANGE_TYPE="created"+fi++log "Reflection gate triggered for $FILE_PATH ($CHANGE_TYPE, $LINE_COUNT lines)"++# Signal to Claude that reflection should occur+# This creates a marker file that Claude's instructions will check+REFLECTION_MARKER="$HOME/.claude/session-env/pending-reflection.json"++cat > "$REFLECTION_MARKER" << EOF+{+ "file": "$FILE_PATH",+ "change_type": "$CHANGE_TYPE",+ "line_count": "$LINE_COUNT",+ "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",+ "reflection_requested": true+}+EOF++# Output to Claude (this becomes part of the hook response)+echo "REFLECTION_TRIGGER: Significant code change detected in $FILE_PATH ($LINE_COUNT lines). Consider self-critique before proceeding."++exit 0diff --git a/hooks/pipeline/pipeline-activity-tracker.sh b/hooks/pipeline/pipeline-activity-tracker.shnew file mode 100755index 0000000..4249c86--- /dev/null+++ b/hooks/pipeline/pipeline-activity-tracker.sh@@ -0,0 +1,136 @@+#!/bin/bash+# ═══════════════════════════════════════════════════════════════════════════════+# ID8Pipeline Activity Tracker+# ═══════════════════════════════════════════════════════════════════════════════+# Runs as a post-tool hook to automatically document work done.+# Detects significant changes and updates PIPELINE_STATUS.md accordingly.+#+# Hook triggers: Edit, Write (file operations)+# ═══════════════════════════════════════════════════════════════════════════════++set -euo pipefail++# Get the file that was modified from stdin or argument+MODIFIED_FILE="${1:-}"+TOOL_NAME="${CLAUDE_TOOL_NAME:-unknown}"+PIPELINE_BRAIN="$HOME/.claude/hooks/pipeline/pipeline-brain.sh"++# Find PIPELINE_STATUS.md+find_pipeline_status() {+ local dir="${PWD}"+ while [[ "$dir" != "/" ]]; do+ if [[ -f "$dir/PIPELINE_STATUS.md" ]]; then+ echo "$dir/PIPELINE_STATUS.md"+ return 0+ fi+ dir=$(dirname "$dir")+ done+ return 1+}++# Detect what type of work was done based on file modified+detect_work_type() {+ local file="$1"++ case "$file" in+ *.test.* | *.spec.* | */__tests__/* | */tests/*)+ echo "testing"+ ;;+ *.md | *.mdx | */docs/*)+ echo "documentation"+ ;;+ */components/* | */ui/* | *.tsx | *.jsx)+ echo "ui"+ ;;+ */api/* | */routes/* | */server/*)+ echo "backend"+ ;;+ */migrations/* | *.sql | */schema/*)+ echo "database"+ ;;+ package.json | *.config.* | tsconfig.json | next.config.*)+ echo "configuration"+ ;;+ .env* | */env/*)+ echo "environment"+ ;;+ *)+ echo "general"+ ;;+ esac+}++# Update the activity log in PIPELINE_STATUS.md+update_activity_log() {+ local status_file="$1"+ local work_type="$2"+ local file_changed="$3"++ local timestamp=$(date "+%Y-%m-%d %H:%M")+ local relative_file=$(basename "$file_changed")++ # Check if Activity Log section exists+ if ! grep -q "## Activity Log" "$status_file"; then+ # Add Activity Log section before Override Log+ sed -i.bak '/## Override Log/i\+## Activity Log\+\+| Time | Type | File | Notes |\+|------|------|------|-------|\+\+---\+' "$status_file"+ rm -f "${status_file}.bak"+ fi++ # Add new activity entry (insert after the header row)+ # This is a bit tricky with sed, so we use a temp approach+ local activity_line="| $timestamp | $work_type | \`$relative_file\` | Auto-logged |"++ # Use awk to insert after the Activity Log table header+ awk -v line="$activity_line" '+ /## Activity Log/ { found=1 }+ found && /^\|---/ { print; print line; found=0; next }+ { print }+ ' "$status_file" > "${status_file}.tmp" && mv "${status_file}.tmp" "$status_file"+}++# Touch the PIPELINE_STATUS.md to update modification time+touch_pipeline() {+ local status_file="$1"+ touch "$status_file"+}++# Main logic+main() {+ # Skip if no file was modified+ if [[ -z "$MODIFIED_FILE" ]]; then+ exit 0+ fi++ # Find pipeline status file+ local status_file+ if ! status_file=$(find_pipeline_status); then+ # No pipeline, nothing to do+ exit 0+ fi++ # Detect work type+ local work_type=$(detect_work_type "$MODIFIED_FILE")++ # Update activity log+ update_activity_log "$status_file" "$work_type" "$MODIFIED_FILE"++ # Touch to reset staleness timer+ touch_pipeline "$status_file"++ # Log to pipeline brain+ if [[ -x "$PIPELINE_BRAIN" ]]; then+ "$PIPELINE_BRAIN" log "Activity: $work_type on $MODIFIED_FILE" 2>/dev/null || true+ fi++ # Output for Claude to see+ echo "Pipeline: Logged $work_type activity"+}++main "$@"diff --git a/hooks/pipeline/pipeline-brain.sh b/hooks/pipeline/pipeline-brain.shnew file mode 100755index 0000000..19ebc15--- /dev/null+++ b/hooks/pipeline/pipeline-brain.sh@@ -0,0 +1,533 @@+#!/bin/bash+# ═══════════════════════════════════════════════════════════════════════════════+# ID8Pipeline Brain - The Living Pipeline Core+# ═══════════════════════════════════════════════════════════════════════════════+# This is the central intelligence of the pipeline system.+# It detects state, calculates staleness, and provides contextual guidance.+#+# Usage:+# ./pipeline-brain.sh status - Get full pipeline status+# ./pipeline-brain.sh stage - Get current stage only+# ./pipeline-brain.sh staleness - Check if work is stale+# ./pipeline-brain.sh next-action - Get recommended next action+# ./pipeline-brain.sh teach - Get contextual teaching for current stage+# ./pipeline-brain.sh log <message> - Log activity to pipeline history+# ═══════════════════════════════════════════════════════════════════════════════++set -euo pipefail++# Configuration+STALENESS_THRESHOLD_HOURS=24 # 1 day+PIPELINE_MEMORY_DIR="$HOME/.claude/pipeline-memory"+PIPELINE_LOG="$PIPELINE_MEMORY_DIR/activity.log"+PATTERNS_FILE="$PIPELINE_MEMORY_DIR/patterns.json"++# Colors+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+BLUE='\033[0;34m'+CYAN='\033[0;36m'+MAGENTA='\033[0;35m'+BOLD='\033[1m'+NC='\033[0m'++# Ensure directories exist+mkdir -p "$PIPELINE_MEMORY_DIR"++# ─────────────────────────────────────────────────────────────────────────────+# Stage Teaching Content - Contextual education for each stage+# ─────────────────────────────────────────────────────────────────────────────+get_stage_teaching() {+ local stage="$1"++ case $stage in+ 1)+ echo ""+ echo -e "${CYAN}★ Stage 1: Concept Lock - Why This Matters${NC}"+ echo ""+ echo "The one-liner forces clarity. If you can't explain it in one sentence,"+ echo "you don't understand it yet. This isn't about marketing—it's about focus."+ echo ""+ echo -e "${YELLOW}Common Pitfalls:${NC}"+ echo "• Too vague: \"A platform for productivity\" (what does that mean?)"+ echo "• Too ambitious: \"An AI that replaces all software\" (scope creep begins here)"+ echo "• Feature-focused: \"A todo app with reminders\" (describes HOW, not WHY)"+ echo ""+ echo -e "${GREEN}Good Examples:${NC}"+ echo "• \"Helps freelancers get paid faster by automating invoice follow-ups\""+ echo "• \"Lets parents track school photos without downloading another app\""+ echo ""+ echo -e "${MAGENTA}Your Checkpoint:${NC} \"What's the one-liner?\""+ ;;+ 2)+ echo ""+ echo -e "${CYAN}★ Stage 2: Scope Fence - Why This Matters${NC}"+ echo ""+ echo "The 'not yet' list is more important than the 'yes' list. Every feature"+ echo "you exclude is energy saved for the features that matter."+ echo ""+ echo -e "${YELLOW}The 5-Feature Rule:${NC}"+ echo "If you can't get v1 down to 5 core features, you're building too much."+ echo "Each additional feature multiplies complexity, not adds to it."+ echo ""+ echo -e "${GREEN}Power Move:${NC}"+ echo "Write your 'not yet' list FIRST. Get excited about v2 features, then"+ echo "consciously set them aside. This creates motivation for shipping v1."+ echo ""+ echo -e "${MAGENTA}Your Checkpoint:${NC} \"What are we NOT building?\""+ ;;+ 3)+ echo ""+ echo -e "${CYAN}★ Stage 3: Architecture Sketch - Why This Matters${NC}"+ echo ""+ echo "This isn't about picking the perfect stack—it's about seeing the system"+ echo "as a whole before writing code. Bad architecture decisions compound."+ echo ""+ echo -e "${YELLOW}Key Questions:${NC}"+ echo "• Where does data live? How does it flow?"+ echo "• What's the minimal stack that works?"+ echo "• What will be painful to change later?"+ echo ""+ echo -e "${GREEN}Sketch, Don't Plan:${NC}"+ echo "Boxes and arrows on paper beat detailed documents. You're building"+ echo "intuition, not a contract. The sketch should fit on one page."+ echo ""+ echo -e "${MAGENTA}Your Checkpoint:${NC} \"Draw me the boxes and arrows.\""+ ;;+ 4)+ echo ""+ echo -e "${CYAN}★ Stage 4: Foundation Pour - Why This Matters${NC}"+ echo ""+ echo "This is the 'can we deploy nothing' test. If your empty shell can't"+ echo "reach production, you'll hit deployment bugs at the worst time."+ echo ""+ echo -e "${YELLOW}Must-Haves:${NC}"+ echo "• CI/CD pipeline that deploys on push"+ echo "• Database connected and migrating"+ echo "• Auth flow working (even if basic)"+ echo "• Environment variables flowing"+ echo ""+ echo -e "${GREEN}The Empty Shell Deploy:${NC}"+ echo "Deploy a page that says 'Coming Soon'. This proves your entire"+ echo "infrastructure works before you add complexity."+ echo ""+ echo -e "${MAGENTA}Your Checkpoint:${NC} \"Can we deploy an empty shell?\""+ ;;+ 5)+ echo ""+ echo -e "${CYAN}★ Stage 5: Feature Blocks - Why This Matters${NC}"+ echo ""+ echo "Vertical slices beat horizontal layers. Build one complete feature"+ echo "before starting another. This keeps momentum and proves value early."+ echo ""+ echo -e "${YELLOW}What 'Complete' Means:${NC}"+ echo "• UI exists and works"+ echo "• Backend handles the request"+ echo "• Data persists correctly"+ echo "• Errors are caught"+ echo "• Edge cases considered"+ echo ""+ echo -e "${GREEN}The Demo Test:${NC}"+ echo "After each feature, you should be able to demo it to someone."+ echo "If you can't demo it, it's not done."+ echo ""+ echo -e "${MAGENTA}Your Checkpoint:${NC} \"Does this feature work completely, right now?\""+ ;;+ 6)+ echo ""+ echo -e "${CYAN}★ Stage 6: Integration Pass - Why This Matters${NC}"+ echo ""+ echo "Individual features working doesn't mean they work together."+ echo "This stage catches the gaps between your building blocks."+ echo ""+ echo -e "${YELLOW}Look For:${NC}"+ echo "• State inconsistencies between features"+ echo "• Data that doesn't flow where expected"+ echo "• UX discontinuities (jarring transitions)"+ echo "• Race conditions and timing issues"+ echo ""+ echo -e "${GREEN}Integration Testing:${NC}"+ echo "Write tests that cross feature boundaries. The bugs are in the seams."+ echo ""+ echo -e "${MAGENTA}Your Checkpoint:${NC} \"Do all the pieces talk to each other?\""+ ;;+ 7)+ echo ""+ echo -e "${CYAN}★ Stage 7: Polish & Harden - Why This Matters${NC}"+ echo ""+ echo "This is where good products become great products. Every loading"+ echo "state, error message, and edge case is a user's experience."+ echo ""+ echo -e "${YELLOW}The Stupid User Test:${NC}"+ echo "• What happens if I double-click everything?"+ echo "• What if I'm offline?"+ echo "• What if my session expires mid-action?"+ echo "• What if I hit back/forward/refresh?"+ echo ""+ echo -e "${GREEN}Polish Checklist:${NC}"+ echo "Loading states, empty states, error states, success feedback,"+ echo "keyboard navigation, mobile responsiveness."+ echo ""+ echo -e "${MAGENTA}Your Checkpoint:${NC} \"What breaks if I do something stupid?\""+ ;;+ 8)+ echo ""+ echo -e "${CYAN}★ Stage 8: Launch Prep - Why This Matters${NC}"+ echo ""+ echo "The product is ready, but is the launch? This stage is about"+ echo "everything outside the code."+ echo ""+ echo -e "${YELLOW}The Stranger Test:${NC}"+ echo "Give the URL to someone who's never seen it. Watch them without"+ echo "helping. Every question they ask is a gap in your onboarding."+ echo ""+ echo -e "${GREEN}Launch Checklist:${NC}"+ echo "• Landing page that explains the value"+ echo "• Onboarding that doesn't need instructions"+ echo "• Analytics to learn what users actually do"+ echo "• Way for users to give feedback"+ echo ""+ echo -e "${MAGENTA}Your Checkpoint:${NC} \"Could a stranger use this without asking me questions?\""+ ;;+ 9)+ echo ""+ echo -e "${CYAN}★ Stage 9: Ship - Why This Matters${NC}"+ echo ""+ echo "Shipping is a skill. The longer you wait, the harder it gets."+ echo "A shipped product beats a perfect product that never launches."+ echo ""+ echo -e "${YELLOW}Ship Mindset:${NC}"+ echo "• Done is better than perfect"+ echo "• You can iterate after launch"+ echo "• Real user feedback > your assumptions"+ echo "• The goal is learning, not perfection"+ echo ""+ echo -e "${GREEN}Ship Actions:${NC}"+ echo "• Deploy to production"+ echo "• Announce it (even to a small audience)"+ echo "• Turn on monitoring"+ echo "• Be ready to respond"+ echo ""+ echo -e "${MAGENTA}Your Checkpoint:${NC} \"Is it live and are people using it?\""+ ;;+ 10)+ echo ""+ echo -e "${CYAN}★ Stage 10: Listen & Iterate - Why This Matters${NC}"+ echo ""+ echo "The product is live—now the real learning begins. User behavior"+ echo "will surprise you. That's the point."+ echo ""+ echo -e "${YELLOW}Listen For:${NC}"+ echo "• What features are actually used?"+ echo "• Where do users get stuck?"+ echo "• What do they ask for?"+ echo "• What do they ignore?"+ echo ""+ echo -e "${GREEN}Iterate Wisely:${NC}"+ echo "Not every request deserves action. Look for patterns."+ echo "One user's request is an opinion. Ten users' request is data."+ echo ""+ echo -e "${MAGENTA}Your Checkpoint:${NC} \"What did we learn?\""+ ;;+ *)+ echo "No teaching content for stage $stage"+ ;;+ esac+}++# ─────────────────────────────────────────────────────────────────────────────+# Helper Functions+# ─────────────────────────────────────────────────────────────────────────────++find_pipeline_status() {+ # Search for PIPELINE_STATUS.md in current directory and up+ local dir="$PWD"+ while [[ "$dir" != "/" ]]; do+ if [[ -f "$dir/PIPELINE_STATUS.md" ]]; then+ echo "$dir/PIPELINE_STATUS.md"+ return 0+ fi+ dir=$(dirname "$dir")+ done+ return 1+}++get_project_name() {+ local status_file="$1"+ local project_dir=$(dirname "$status_file")+ basename "$project_dir"+}++get_current_stage() {+ local status_file="$1"+ # Look for "Current Stage: X" pattern+ grep -oE "Current Stage: ([0-9]+)" "$status_file" 2>/dev/null | grep -oE "[0-9]+" | head -1 || echo "0"+}++get_stage_name() {+ local stage_num="$1"+ case $stage_num in+ 1) echo "Concept Lock" ;;+ 2) echo "Scope Fence" ;;+ 3) echo "Architecture Sketch" ;;+ 4) echo "Foundation Pour" ;;+ 5) echo "Feature Blocks" ;;+ 6) echo "Integration Pass" ;;+ 7) echo "Polish & Harden" ;;+ 8) echo "Launch Prep" ;;+ 9) echo "Ship" ;;+ 10) echo "Listen & Iterate" ;;+ *) echo "Unknown" ;;+ esac+}++get_checkpoint_question() {+ local stage_num="$1"+ case $stage_num in+ 1) echo "What's the one-liner?" ;;+ 2) echo "What are we NOT building?" ;;+ 3) echo "Draw me the boxes and arrows." ;;+ 4) echo "Can we deploy an empty shell?" ;;+ 5) echo "Does this feature work completely, right now?" ;;+ 6) echo "Do all the pieces talk to each other?" ;;+ 7) echo "What breaks if I do something stupid?" ;;+ 8) echo "Could a stranger use this without asking me questions?" ;;+ 9) echo "Is it live and are people using it?" ;;+ 10) echo "What did we learn?" ;;+ *) echo "No checkpoint defined" ;;+ esac+}++get_last_activity_time() {+ local status_file="$1"+ # Get last modified time of PIPELINE_STATUS.md+ if [[ -f "$status_file" ]]; then+ stat -f "%m" "$status_file" 2>/dev/null || stat -c "%Y" "$status_file" 2>/dev/null || echo "0"+ else+ echo "0"+ fi+}++calculate_staleness_hours() {+ local last_activity="$1"+ local current_time=$(date +%s)+ local diff=$((current_time - last_activity))+ echo $((diff / 3600))+}++is_stale() {+ local status_file="$1"+ local last_activity=$(get_last_activity_time "$status_file")+ local hours_since=$(calculate_staleness_hours "$last_activity")++ if [[ $hours_since -ge $STALENESS_THRESHOLD_HOURS ]]; then+ return 0 # true, is stale+ else+ return 1 # false, not stale+ fi+}++log_activity() {+ local message="$1"+ local timestamp=$(date "+%Y-%m-%d %H:%M:%S")+ local project=$(basename "$PWD")+ echo "[$timestamp] [$project] $message" >> "$PIPELINE_LOG"+}++# ─────────────────────────────────────────────────────────────────────────────+# Main Commands+# ─────────────────────────────────────────────────────────────────────────────++cmd_status() {+ local status_file+ if ! status_file=$(find_pipeline_status); then+ echo -e "${RED}No PIPELINE_STATUS.md found${NC}"+ echo "Create one from the template: ~/.claude/PIPELINE_STATUS_TEMPLATE.md"+ return 1+ fi++ local project=$(get_project_name "$status_file")+ local stage=$(get_current_stage "$status_file")+ local stage_name=$(get_stage_name "$stage")+ local checkpoint=$(get_checkpoint_question "$stage")+ local last_activity=$(get_last_activity_time "$status_file")+ local hours_since=$(calculate_staleness_hours "$last_activity")++ echo ""+ echo -e "${BOLD}═══════════════════════════════════════════════════════════════${NC}"+ echo -e "${BOLD} ID8Pipeline Status: ${CYAN}$project${NC}"+ echo -e "${BOLD}═══════════════════════════════════════════════════════════════${NC}"+ echo ""+ echo -e " ${BOLD}Current Stage:${NC} $stage - $stage_name"+ echo ""+ echo -e " ${BOLD}Next Checkpoint:${NC}"+ echo -e " ${YELLOW}\"$checkpoint\"${NC}"+ echo ""++ # Staleness indicator+ if [[ $hours_since -ge $STALENESS_THRESHOLD_HOURS ]]; then+ echo -e " ${RED}⚠ STALE: ${hours_since}h since last update${NC}"+ echo -e " ${YELLOW}→ This stage needs attention!${NC}"+ else+ echo -e " ${GREEN}✓ Active: Last updated ${hours_since}h ago${NC}"+ fi++ echo ""+ echo -e "${BOLD}═══════════════════════════════════════════════════════════════${NC}"++ # Log this status check+ log_activity "Status check: Stage $stage ($stage_name)"+}++cmd_stage() {+ local status_file+ if ! status_file=$(find_pipeline_status); then+ echo "0"+ return 1+ fi+ get_current_stage "$status_file"+}++cmd_staleness() {+ local status_file+ if ! status_file=$(find_pipeline_status); then+ echo "no_pipeline"+ return 1+ fi++ local last_activity=$(get_last_activity_time "$status_file")+ local hours_since=$(calculate_staleness_hours "$last_activity")++ if [[ $hours_since -ge $STALENESS_THRESHOLD_HOURS ]]; then+ echo "stale:${hours_since}h"+ return 0+ else+ echo "active:${hours_since}h"+ return 1+ fi+}++cmd_next_action() {+ local status_file+ if ! status_file=$(find_pipeline_status); then+ echo "Create PIPELINE_STATUS.md from template"+ return 1+ fi++ local stage=$(get_current_stage "$status_file")+ local stage_name=$(get_stage_name "$stage")+ local checkpoint=$(get_checkpoint_question "$stage")++ # Check staleness+ local last_activity=$(get_last_activity_time "$status_file")+ local hours_since=$(calculate_staleness_hours "$last_activity")++ if [[ $hours_since -ge $STALENESS_THRESHOLD_HOURS ]]; then+ echo -e "${RED}[STALE ${hours_since}h]${NC} Stage $stage: $stage_name"+ echo ""+ echo "Suggested actions:"+ echo " 1. Review current stage progress in PIPELINE_STATUS.md"+ echo " 2. Answer checkpoint: \"$checkpoint\""+ echo " 3. Update PIPELINE_STATUS.md with current status"+ else+ echo "Stage $stage: $stage_name"+ echo ""+ echo "Checkpoint to clear: \"$checkpoint\""+ fi+}++cmd_teach() {+ local status_file+ if ! status_file=$(find_pipeline_status); then+ echo "No pipeline found. Here's the overview:"+ echo ""+ echo "The ID8Pipeline has 10 stages:"+ echo " 1. Concept Lock - Define the problem"+ echo " 2. Scope Fence - Set boundaries"+ echo " 3. Architecture - Design the system"+ echo " 4. Foundation - Build scaffolding"+ echo " 5. Feature Blocks - Build features"+ echo " 6. Integration - Connect pieces"+ echo " 7. Polish - Handle edge cases"+ echo " 8. Launch Prep - Prepare for users"+ echo " 9. Ship - Go live"+ echo " 10. Iterate - Learn and improve"+ return 0+ fi++ local stage=$(get_current_stage "$status_file")+ get_stage_teaching "$stage"+}++cmd_log() {+ local message="$1"+ log_activity "$message"+ echo "Logged: $message"+}++cmd_briefing() {+ # Full session-start briefing+ echo ""+ echo -e "${BOLD}${CYAN}╔═══════════════════════════════════════════════════════════════╗${NC}"+ echo -e "${BOLD}${CYAN}║ ID8Pipeline Session Briefing ║${NC}"+ echo -e "${BOLD}${CYAN}╚═══════════════════════════════════════════════════════════════╝${NC}"+ echo ""++ local status_file+ if ! status_file=$(find_pipeline_status); then+ echo -e "${YELLOW}⚠ No active pipeline found in this project${NC}"+ echo ""+ echo "To start a new pipeline:"+ echo " cp ~/.claude/PIPELINE_STATUS_TEMPLATE.md ./PIPELINE_STATUS.md"+ echo ""+ return 0+ fi++ local project=$(get_project_name "$status_file")+ local stage=$(get_current_stage "$status_file")+ local stage_name=$(get_stage_name "$stage")+ local checkpoint=$(get_checkpoint_question "$stage")+ local last_activity=$(get_last_activity_time "$status_file")+ local hours_since=$(calculate_staleness_hours "$last_activity")++ echo -e " ${BOLD}Project:${NC} $project"+ echo -e " ${BOLD}Stage:${NC} $stage - $stage_name"++ if [[ $hours_since -ge $STALENESS_THRESHOLD_HOURS ]]; then+ echo -e " ${BOLD}Status:${NC} ${RED}Stale (${hours_since}h)${NC}"+ else+ echo -e " ${BOLD}Status:${NC} ${GREEN}Active${NC}"+ fi++ echo ""+ echo -e " ${BOLD}Your Focus:${NC}"+ echo -e " ${YELLOW}\"$checkpoint\"${NC}"+ echo ""++ # Show brief teaching+ echo -e "${BLUE}────────────────────────────────────────────────────────────────${NC}"+ get_stage_teaching "$stage" | head -15+ echo ""++ # Log briefing+ log_activity "Session started: Stage $stage"+}++# ─────────────────────────────────────────────────────────────────────────────+# Entry Point+# ─────────────────────────────────────────────────────────────────────────────++case "${1:-status}" in+ status) cmd_status ;;+ stage) cmd_stage ;;+ staleness) cmd_staleness ;;+ next-action) cmd_next_action ;;+ teach) cmd_teach ;;+ log) cmd_log "${2:-Activity logged}" ;;+ briefing) cmd_briefing ;;+ *)+ echo "Usage: pipeline-brain.sh {status|stage|staleness|next-action|teach|log|briefing}"+ exit 1+ ;;+esacdiff --git a/hooks/pipeline/pipeline-messenger.sh b/hooks/pipeline/pipeline-messenger.shnew file mode 100755index 0000000..868ba40--- /dev/null+++ b/hooks/pipeline/pipeline-messenger.sh@@ -0,0 +1,245 @@+#!/bin/bash+# ═══════════════════════════════════════════════════════════════════════════════+# ID8Pipeline Messenger - iMessage Integration+# ═══════════════════════════════════════════════════════════════════════════════+# Sends pipeline notifications via iMessage and can listen for replies.+#+# Usage:+# ./pipeline-messenger.sh notify "message" - Send a notification+# ./pipeline-messenger.sh alert "message" - Send urgent alert+# ./pipeline-messenger.sh ask "question" - Ask and wait for reply+# ./pipeline-messenger.sh setup - Configure phone number+# ═══════════════════════════════════════════════════════════════════════════════++set -euo pipefail++CONFIG_DIR="$HOME/.claude/pipeline-memory"+CONFIG_FILE="$CONFIG_DIR/messenger-config.txt"+REPLY_LOG="$CONFIG_DIR/imessage-replies.log"++mkdir -p "$CONFIG_DIR"++# Colors+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+RED='\033[0;31m'+NC='\033[0m'++# ─────────────────────────────────────────────────────────────────────────────+# Load configuration+# ─────────────────────────────────────────────────────────────────────────────+load_config() {+ if [[ -f "$CONFIG_FILE" ]]; then+ source "$CONFIG_FILE"+ else+ PHONE_NUMBER=""+ fi+}++save_config() {+ echo "PHONE_NUMBER=\"$PHONE_NUMBER\"" > "$CONFIG_FILE"+}++# ─────────────────────────────────────────────────────────────────────────────+# Setup - configure phone number+# ─────────────────────────────────────────────────────────────────────────────+cmd_setup() {+ echo ""+ echo -e "${GREEN}ID8Pipeline Messenger Setup${NC}"+ echo ""+ echo "Enter your phone number or iMessage email:"+ echo "(Format: +1234567890 or [email protected])"+ echo ""+ read -p "> " PHONE_NUMBER++ save_config++ echo ""+ echo -e "${GREEN}✓ Saved!${NC}"+ echo ""+ echo "Testing connection..."++ send_message "🔔 ID8Pipeline connected! You'll receive notifications here."++ echo ""+ echo -e "${GREEN}✓ Test message sent. Check your phone!${NC}"+}++# ─────────────────────────────────────────────────────────────────────────────+# Send iMessage+# ─────────────────────────────────────────────────────────────────────────────+send_message() {+ local message="$1"++ load_config++ if [[ -z "${PHONE_NUMBER:-}" ]]; then+ echo -e "${RED}Error: Phone number not configured. Run: pipeline-messenger.sh setup${NC}"+ return 1+ fi++ # Send via AppleScript+ osascript <<EOF+tell application "Messages"+ set targetService to 1st account whose service type = iMessage+ set targetBuddy to participant "$PHONE_NUMBER" of targetService+ send "$message" to targetBuddy+end tell+EOF++ # Log the send+ echo "[$(date '+%Y-%m-%d %H:%M:%S')] SENT: $message" >> "$REPLY_LOG"++ return 0+}++# ─────────────────────────────────────────────────────────────────────────────+# Send notification (non-urgent)+# ─────────────────────────────────────────────────────────────────────────────+cmd_notify() {+ local message="$1"+ send_message "📋 Pipeline: $message"+ echo "Notification sent"+}++# ─────────────────────────────────────────────────────────────────────────────+# Send alert (urgent)+# ─────────────────────────────────────────────────────────────────────────────+cmd_alert() {+ local message="$1"+ send_message "🔴 PIPELINE ALERT: $message"+ echo "Alert sent"+}++# ─────────────────────────────────────────────────────────────────────────────+# Send stale project alert+# ─────────────────────────────────────────────────────────────────────────────+cmd_stale_alert() {+ local project="$1"+ local stage="$2"+ local hours="$3"++ local message="⏰ $project is stale!++Stage $stage hasn't been updated in ${hours}h.++Reply:+• Y - Authorize autonomous work+• N - I'll handle it+• [task] - Work on specific task"++ send_message "$message"+ echo "Stale alert sent for $project"+}++# ─────────────────────────────────────────────────────────────────────────────+# Ask question and wait for reply+# ─────────────────────────────────────────────────────────────────────────────+cmd_ask() {+ local question="$1"+ local timeout="${2:-300}" # Default 5 minutes++ send_message "❓ $question++Reply within ${timeout}s or I'll wait."++ echo "Question sent, waiting for reply..."+ echo "(Note: Reply detection requires Messages.app automation permissions)"++ # For now, we can't easily detect replies without more complex setup+ # The user would need to:+ # 1. Grant automation permissions+ # 2. Set up a reply webhook or poll Messages database++ echo ""+ echo -e "${YELLOW}Tip: Full reply detection requires additional setup.${NC}"+ echo "For now, check manually or use a Telegram bot for two-way communication."+}++# ─────────────────────────────────────────────────────────────────────────────+# Send progress update+# ─────────────────────────────────────────────────────────────────────────────+cmd_progress() {+ local project="$1"+ local status="$2"+ local details="${3:-}"++ local message="📊 $project Progress++$status"++ if [[ -n "$details" ]]; then+ message="$message++$details"+ fi++ send_message "$message"+ echo "Progress update sent"+}++# ─────────────────────────────────────────────────────────────────────────────+# Send completion notification+# ─────────────────────────────────────────────────────────────────────────────+cmd_complete() {+ local project="$1"+ local summary="$2"++ send_message "✅ $project Task Complete!++$summary"++ echo "Completion notification sent"+}++# ─────────────────────────────────────────────────────────────────────────────+# Entry Point+# ─────────────────────────────────────────────────────────────────────────────+case "${1:-help}" in+ setup)+ cmd_setup+ ;;+ notify)+ cmd_notify "${2:-No message provided}"+ ;;+ alert)+ cmd_alert "${2:-Alert!}"+ ;;+ stale)+ cmd_stale_alert "${2:-Project}" "${3:-?}" "${4:-?}"+ ;;+ ask)+ cmd_ask "${2:-Question?}" "${3:-300}"+ ;;+ progress)+ cmd_progress "${2:-Project}" "${3:-In progress}" "${4:-}"+ ;;+ complete)+ cmd_complete "${2:-Project}" "${3:-Task completed}"+ ;;+ test)+ send_message "🧪 Test message from ID8Pipeline"+ echo "Test message sent"+ ;;+ help|--help|-h|"")+ echo "ID8Pipeline Messenger"+ echo ""+ echo "Usage: pipeline-messenger.sh [command] [args]"+ echo ""+ echo "Commands:"+ echo " setup Configure your phone number"+ echo " notify \"message\" Send a notification"+ echo " alert \"message\" Send urgent alert"+ echo " stale proj stage hours Send stale project alert"+ echo " ask \"question\" [timeout] Ask and await reply"+ echo " progress proj status Send progress update"+ echo " complete proj summary Send completion notice"+ echo " test Send test message"+ echo ""+ ;;+ *)+ echo "Unknown command: $1"+ echo "Run 'pipeline-messenger.sh help' for usage"+ exit 1+ ;;+esacdiff --git a/hooks/pipeline/pipeline-patterns.sh b/hooks/pipeline/pipeline-patterns.shnew file mode 100755index 0000000..4b8604b--- /dev/null+++ b/hooks/pipeline/pipeline-patterns.sh@@ -0,0 +1,227 @@+#!/bin/bash+# ═══════════════════════════════════════════════════════════════════════════════+# ID8Pipeline Pattern Tracker+# ═══════════════════════════════════════════════════════════════════════════════+# Tracks patterns across all projects to learn your development style:+# - Time spent at each stage+# - Common blockers+# - Stages frequently skipped+# - Velocity trends+#+# This data helps the pipeline give personalized guidance.+# ═══════════════════════════════════════════════════════════════════════════════++set -euo pipefail++PIPELINE_MEMORY_DIR="$HOME/.claude/pipeline-memory"+PATTERNS_FILE="$PIPELINE_MEMORY_DIR/patterns.json"+STAGE_TIMES_FILE="$PIPELINE_MEMORY_DIR/stage-times.csv"+INSIGHTS_FILE="$PIPELINE_MEMORY_DIR/insights.md"++mkdir -p "$PIPELINE_MEMORY_DIR"++# Initialize patterns file if it doesn't exist+init_patterns() {+ if [[ ! -f "$PATTERNS_FILE" ]]; then+ cat > "$PATTERNS_FILE" << 'EOF'+{+ "projects_completed": 0,+ "total_stages_cleared": 0,+ "stages_skipped": {},+ "average_time_per_stage": {+ "1": 0, "2": 0, "3": 0, "4": 0, "5": 0,+ "6": 0, "7": 0, "8": 0, "9": 0, "10": 0+ },+ "blockers": [],+ "last_updated": ""+}+EOF+ fi++ if [[ ! -f "$STAGE_TIMES_FILE" ]]; then+ echo "project,stage,started,completed,hours" > "$STAGE_TIMES_FILE"+ fi+}++# Record when a stage is started+record_stage_start() {+ local project="$1"+ local stage="$2"+ local timestamp=$(date "+%Y-%m-%d %H:%M:%S")++ echo "$project,$stage,$timestamp,," >> "$STAGE_TIMES_FILE"+}++# Record when a stage is completed+record_stage_complete() {+ local project="$1"+ local stage="$2"+ local timestamp=$(date "+%Y-%m-%d %H:%M:%S")++ # Find the last entry for this project/stage and update it+ # This is simplified - in production would be more robust+ local temp_file=$(mktemp)++ awk -F',' -v proj="$project" -v stg="$stage" -v ts="$timestamp" '+ BEGIN { OFS="," }+ NR == 1 { print; next }+ $1 == proj && $2 == stg && $4 == "" {+ # Calculate hours+ $4 = ts+ # Note: actual hour calculation would need date parsing+ $5 = "TBD"+ next+ }+ { print }+ ' "$STAGE_TIMES_FILE" > "$temp_file"++ mv "$temp_file" "$STAGE_TIMES_FILE"+}++# Analyze patterns and generate insights+generate_insights() {+ init_patterns++ local today=$(date "+%Y-%m-%d")++ cat > "$INSIGHTS_FILE" << HEADER+# ID8Pipeline Personal Insights++> Last analyzed: $today++These insights are based on your development patterns across all tracked projects.++---++HEADER++ # Count projects+ local project_count=$(ls -d "$HOME/Development"/*/PIPELINE_STATUS.md 2>/dev/null | wc -l || echo "0")++ echo "## Overview" >> "$INSIGHTS_FILE"+ echo "" >> "$INSIGHTS_FILE"+ echo "- **Projects Tracked:** $project_count" >> "$INSIGHTS_FILE"+ echo "" >> "$INSIGHTS_FILE"++ # Analyze stage times if we have data+ if [[ -f "$STAGE_TIMES_FILE" ]] && [[ $(wc -l < "$STAGE_TIMES_FILE") -gt 1 ]]; then+ echo "## Stage Duration Patterns" >> "$INSIGHTS_FILE"+ echo "" >> "$INSIGHTS_FILE"+ echo "| Stage | Avg Time | Your Pattern |" >> "$INSIGHTS_FILE"+ echo "|-------|----------|--------------|" >> "$INSIGHTS_FILE"++ # Simplified - would calculate actual averages in production+ for i in {1..10}; do+ local stage_name+ case $i in+ 1) stage_name="Concept Lock" ;;+ 2) stage_name="Scope Fence" ;;+ 3) stage_name="Architecture" ;;+ 4) stage_name="Foundation" ;;+ 5) stage_name="Features" ;;+ 6) stage_name="Integration" ;;+ 7) stage_name="Polish" ;;+ 8) stage_name="Launch Prep" ;;+ 9) stage_name="Ship" ;;+ 10) stage_name="Iterate" ;;+ esac+ echo "| $i. $stage_name | TBD | Analyzing... |" >> "$INSIGHTS_FILE"+ done++ echo "" >> "$INSIGHTS_FILE"+ fi++ # Add recommendations section+ cat >> "$INSIGHTS_FILE" << 'RECOMMENDATIONS'++## Recommendations++Based on your patterns (will populate as more data is collected):++1. **Watch for staleness** - Projects tend to stall after initial momentum+2. **Stage 5 is critical** - Feature Blocks often takes longest+3. **Don't skip Polish** - Stage 7 skips often lead to post-launch issues++---++## Raw Data++See `stage-times.csv` for detailed timing data.+RECOMMENDATIONS++ echo "Insights generated: $INSIGHTS_FILE"+}++# Get a personalized tip based on current stage and patterns+get_personalized_tip() {+ local stage="$1"++ # This would query the patterns file for personalized advice+ # For now, return stage-specific tips++ case $stage in+ 1)+ echo "Tip: You tend to spend time here. Focus on the one-liner before anything else."+ ;;+ 2)+ echo "Tip: Be ruthless with scope. Every feature you cut now saves days later."+ ;;+ 3)+ echo "Tip: Don't over-architect. A simple diagram beats a complex one."+ ;;+ 4)+ echo "Tip: Deploy early, deploy often. Get the pipeline working before features."+ ;;+ 5)+ echo "Tip: One feature at a time. Resist the urge to work on multiple features."+ ;;+ 6)+ echo "Tip: Test the seams. Bugs hide where features meet."+ ;;+ 7)+ echo "Tip: This stage is often rushed. Give it the time it deserves."+ ;;+ 8)+ echo "Tip: The stranger test is real. Watch someone use it without helping."+ ;;+ 9)+ echo "Tip: Ship it. Perfect is the enemy of done."+ ;;+ 10)+ echo "Tip: Listen more than you build. User feedback is gold."+ ;;+ esac+}++# ─────────────────────────────────────────────────────────────────────────────+# Entry Point+# ─────────────────────────────────────────────────────────────────────────────+case "${1:-help}" in+ init)+ init_patterns+ echo "Patterns tracking initialized"+ ;;+ start)+ record_stage_start "${2:-}" "${3:-}"+ ;;+ complete)+ record_stage_complete "${2:-}" "${3:-}"+ ;;+ insights)+ generate_insights+ ;;+ tip)+ get_personalized_tip "${2:-1}"+ ;;+ *)+ echo "Usage: pipeline-patterns.sh {init|start|complete|insights|tip}"+ echo ""+ echo "Commands:"+ echo " init - Initialize patterns tracking"+ echo " start proj stage - Record stage start time"+ echo " complete proj stg - Record stage completion"+ echo " insights - Generate insights report"+ echo " tip N - Get personalized tip for stage N"+ ;;+esacdiff --git a/hooks/pipeline/pipeline-progress-updater.sh b/hooks/pipeline/pipeline-progress-updater.shnew file mode 100755index 0000000..a4158df--- /dev/null+++ b/hooks/pipeline/pipeline-progress-updater.sh@@ -0,0 +1,295 @@+#!/bin/bash+# ═══════════════════════════════════════════════════════════════════════════════+# ID8Pipeline Progress Updater+# ═══════════════════════════════════════════════════════════════════════════════+# Handles automatic updates to PIPELINE_STATUS.md including:+# - Advancing to next stage+# - Marking checkpoints as cleared+# - Logging decisions and overrides+#+# Usage:+# ./pipeline-progress-updater.sh advance - Move to next stage+# ./pipeline-progress-updater.sh checkpoint - Mark current checkpoint cleared+# ./pipeline-progress-updater.sh decision "..." - Log a decision+# ./pipeline-progress-updater.sh override X "reason" - Log a stage skip+# ═══════════════════════════════════════════════════════════════════════════════++set -euo pipefail++PIPELINE_BRAIN="$HOME/.claude/hooks/pipeline/pipeline-brain.sh"+PIPELINE_MEMORY_DIR="$HOME/.claude/pipeline-memory"++# Colors+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+CYAN='\033[0;36m'+NC='\033[0m'++# Find PIPELINE_STATUS.md+find_pipeline_status() {+ local dir="${PWD}"+ while [[ "$dir" != "/" ]]; do+ if [[ -f "$dir/PIPELINE_STATUS.md" ]]; then+ echo "$dir/PIPELINE_STATUS.md"+ return 0+ fi+ dir=$(dirname "$dir")+ done+ return 1+}++get_current_stage() {+ local status_file="$1"+ grep -oE "Current Stage: ([0-9]+)" "$status_file" 2>/dev/null | grep -oE "[0-9]+" | head -1 || echo "0"+}++get_stage_name() {+ local stage_num="$1"+ case $stage_num in+ 1) echo "Concept Lock" ;;+ 2) echo "Scope Fence" ;;+ 3) echo "Architecture Sketch" ;;+ 4) echo "Foundation Pour" ;;+ 5) echo "Feature Blocks" ;;+ 6) echo "Integration Pass" ;;+ 7) echo "Polish & Harden" ;;+ 8) echo "Launch Prep" ;;+ 9) echo "Ship" ;;+ 10) echo "Listen & Iterate" ;;+ *) echo "Unknown" ;;+ esac+}++get_checkpoint_question() {+ local stage_num="$1"+ case $stage_num in+ 1) echo "What's the one-liner?" ;;+ 2) echo "What are we NOT building?" ;;+ 3) echo "Draw me the boxes and arrows." ;;+ 4) echo "Can we deploy an empty shell?" ;;+ 5) echo "Does this feature work completely, right now?" ;;+ 6) echo "Do all the pieces talk to each other?" ;;+ 7) echo "What breaks if I do something stupid?" ;;+ 8) echo "Could a stranger use this without asking me questions?" ;;+ 9) echo "Is it live and are people using it?" ;;+ 10) echo "What did we learn?" ;;+ *) echo "No checkpoint defined" ;;+ esac+}++# ─────────────────────────────────────────────────────────────────────────────+# Command: Advance to next stage+# ─────────────────────────────────────────────────────────────────────────────+cmd_advance() {+ local status_file+ if ! status_file=$(find_pipeline_status); then+ echo "No PIPELINE_STATUS.md found"+ return 1+ fi++ local current_stage=$(get_current_stage "$status_file")+ local next_stage=$((current_stage + 1))++ if [[ $next_stage -gt 10 ]]; then+ echo "Already at final stage (10)"+ return 0+ fi++ local current_name=$(get_stage_name "$current_stage")+ local next_name=$(get_stage_name "$next_stage")+ local next_checkpoint=$(get_checkpoint_question "$next_stage")+ local today=$(date "+%Y-%m-%d")++ echo ""+ echo -e "${CYAN}Advancing Pipeline${NC}"+ echo " From: Stage $current_stage - $current_name"+ echo " To: Stage $next_stage - $next_name"+ echo ""++ # Update current stage line+ sed -i.bak "s/Current Stage: $current_stage.*/Current Stage: $next_stage - $next_name/" "$status_file"++ # Update next checkpoint question+ sed -i.bak "s/\*\*Next Checkpoint Question:\*\* .*/\*\*Next Checkpoint Question:\*\* \"$next_checkpoint\"/" "$status_file"++ # Update progress tracker table - mark previous stage as cleared+ # Change: | X. Name | 🔄 In Progress | - | to | X. Name | ✅ Cleared | DATE |+ sed -i.bak "s/| $current_stage\. .* | 🔄 In Progress |/| $current_stage. $current_name | ✅ Cleared | $today |/" "$status_file"++ # Mark new stage as in progress+ sed -i.bak "s/| $next_stage\. .* | ⬜ Pending |/| $next_stage. $next_name | 🔄 In Progress | - |/" "$status_file"++ # Update Last Updated date+ sed -i.bak "s/^> Last Updated: .*/> Last Updated: $today/" "$status_file"++ # Clean up backup files+ rm -f "${status_file}.bak"++ # Log the advancement+ if [[ -x "$PIPELINE_BRAIN" ]]; then+ "$PIPELINE_BRAIN" log "Advanced from Stage $current_stage to Stage $next_stage" 2>/dev/null || true+ fi++ echo -e "${GREEN}✓ Pipeline advanced to Stage $next_stage${NC}"+ echo ""+ echo "New checkpoint: \"$next_checkpoint\""+}++# ─────────────────────────────────────────────────────────────────────────────+# Command: Mark checkpoint cleared (same as advance)+# ─────────────────────────────────────────────────────────────────────────────+cmd_checkpoint() {+ cmd_advance+}++# ─────────────────────────────────────────────────────────────────────────────+# Command: Log a decision+# ─────────────────────────────────────────────────────────────────────────────+cmd_decision() {+ local decision_text="$1"++ local status_file+ if ! status_file=$(find_pipeline_status); then+ echo "No PIPELINE_STATUS.md found"+ return 1+ fi++ local today=$(date "+%Y-%m-%d")+ local current_stage=$(get_current_stage "$status_file")++ # Find Decision Log table and add entry+ # The table format is: | Date | Decision | Reasoning | Stage |++ # Create a decision entry line+ local decision_line="| $today | $decision_text | | $current_stage |"++ # Use awk to insert after the Decision Log table header+ awk -v line="$decision_line" '+ /## Decision Log/ { found=1 }+ found && /^\|---/ { print; print line; found=0; next }+ { print }+ ' "$status_file" > "${status_file}.tmp" && mv "${status_file}.tmp" "$status_file"++ echo -e "${GREEN}✓ Decision logged${NC}"++ # Log to pipeline brain+ if [[ -x "$PIPELINE_BRAIN" ]]; then+ "$PIPELINE_BRAIN" log "Decision: $decision_text" 2>/dev/null || true+ fi+}++# ─────────────────────────────────────────────────────────────────────────────+# Command: Log an override (stage skip)+# ─────────────────────────────────────────────────────────────────────────────+cmd_override() {+ local skipped_stage="$1"+ local reason="${2:-No reason provided}"++ local status_file+ if ! status_file=$(find_pipeline_status); then+ echo "No PIPELINE_STATUS.md found"+ return 1+ fi++ local today=$(date "+%Y-%m-%d")++ # Create an override entry line+ local override_line="| $today | Stage $skipped_stage | $reason | Yes |"++ # Use awk to insert after the Override Log table header+ awk -v line="$override_line" '+ /## Override Log/ { found=1 }+ found && /^\|---/ { print; print line; found=0; next }+ { print }+ ' "$status_file" > "${status_file}.tmp" && mv "${status_file}.tmp" "$status_file"++ # Also mark the stage as skipped in progress tracker+ local stage_name=$(get_stage_name "$skipped_stage")+ sed -i.bak "s/| $skipped_stage\. .* | ⬜ Pending |/| $skipped_stage. $stage_name | ⏭️ Skipped | $today |/" "$status_file"+ rm -f "${status_file}.bak"++ echo -e "${YELLOW}⏭️ Override logged: Stage $skipped_stage skipped${NC}"+ echo "Reason: $reason"++ # Log to pipeline brain+ if [[ -x "$PIPELINE_BRAIN" ]]; then+ "$PIPELINE_BRAIN" log "Override: Skipped stage $skipped_stage - $reason" 2>/dev/null || true+ fi+}++# ─────────────────────────────────────────────────────────────────────────────+# Command: Initialize a new pipeline status file+# ─────────────────────────────────────────────────────────────────────────────+cmd_init() {+ local project_name="${1:-$(basename "$PWD")}"+ local status_file="./PIPELINE_STATUS.md"+ local template="$HOME/.claude/PIPELINE_STATUS_TEMPLATE.md"++ if [[ -f "$status_file" ]]; then+ echo "PIPELINE_STATUS.md already exists"+ return 1+ fi++ if [[ ! -f "$template" ]]; then+ echo "Template not found at $template"+ return 1+ fi++ # Copy template+ cp "$template" "$status_file"++ # Fill in project name and dates+ local today=$(date "+%Y-%m-%d")+ sed -i.bak "s/\[PROJECT NAME\]/$project_name/" "$status_file"+ sed -i.bak "s/\[DATE\]/$today/g" "$status_file"+ sed -i.bak "s/\[STAGE NUMBER\]/1/" "$status_file"+ sed -i.bak "s/\[STAGE NAME\]/Concept Lock/" "$status_file"+ sed -i.bak "s/\[QUESTION\]/What's the one-liner?/" "$status_file"++ # Mark stage 1 as in progress+ sed -i.bak "s/| 1\. Concept Lock | ⬜ Pending |/| 1. Concept Lock | 🔄 In Progress |/" "$status_file"++ rm -f "${status_file}.bak"++ echo -e "${GREEN}✓ Pipeline initialized for: $project_name${NC}"+ echo "Starting at Stage 1: Concept Lock"+ echo ""+ echo "First checkpoint: \"What's the one-liner?\""++ # Log to pipeline brain+ if [[ -x "$PIPELINE_BRAIN" ]]; then+ "$PIPELINE_BRAIN" log "Pipeline initialized for $project_name" 2>/dev/null || true+ fi+}++# ─────────────────────────────────────────────────────────────────────────────+# Entry Point+# ─────────────────────────────────────────────────────────────────────────────+case "${1:-help}" in+ advance)+ cmd_advance+ ;;+ checkpoint)+ cmd_checkpoint+ ;;+ decision)+ cmd_decision "${2:-}"+ ;;+ override)+ cmd_override "${2:-0}" "${3:-}"+ ;;+ init)+ cmd_init "${2:-}"+ ;;+ *)+ echo "Usage: pipeline-progress-updater.sh {advance|checkpoint|decision|override|init}"+ echo ""+ echo "Commands:"+ echo " advance - Move to the next pipeline stage"+ echo " checkpoint - Mark current checkpoint as cleared"+ echo " decision \"text\" - Log a decision to the Decision Log"+ echo " override N \"why\" - Log skipping stage N with reason"+ echo " init [name] - Initialize new PIPELINE_STATUS.md"+ exit 1+ ;;+esacdiff --git a/hooks/pipeline/session-start-briefing.sh b/hooks/pipeline/session-start-briefing.shnew file mode 100755index 0000000..2001576--- /dev/null+++ b/hooks/pipeline/session-start-briefing.sh@@ -0,0 +1,161 @@+#!/bin/bash+# ═══════════════════════════════════════════════════════════════════════════════+# ID8Pipeline Session Start Briefing+# ═══════════════════════════════════════════════════════════════════════════════+# Runs at the start of each Claude Code session to:+# - Show current pipeline status+# - Alert if work is stale+# - Provide contextual teaching for current stage+# - Suggest next actions+#+# Hook type: user-prompt-submit (runs on session start)+# ═══════════════════════════════════════════════════════════════════════════════++set -euo pipefail++PIPELINE_BRAIN="$HOME/.claude/hooks/pipeline/pipeline-brain.sh"+PIPELINE_PATTERNS="$HOME/.claude/hooks/pipeline/pipeline-patterns.sh"+STALENESS_THRESHOLD_HOURS=24++# Colors+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+BLUE='\033[0;34m'+CYAN='\033[0;36m'+MAGENTA='\033[0;35m'+BOLD='\033[1m'+DIM='\033[2m'+NC='\033[0m'++# Find PIPELINE_STATUS.md+find_pipeline_status() {+ local dir="${PWD}"+ while [[ "$dir" != "/" ]]; do+ if [[ -f "$dir/PIPELINE_STATUS.md" ]]; then+ echo "$dir/PIPELINE_STATUS.md"+ return 0+ fi+ dir=$(dirname "$dir")+ done+ return 1+}++get_current_stage() {+ local status_file="$1"+ grep -oE "Current Stage: ([0-9]+)" "$status_file" 2>/dev/null | grep -oE "[0-9]+" | head -1 || echo "0"+}++get_stage_name() {+ local stage_num="$1"+ case $stage_num in+ 1) echo "Concept Lock" ;;+ 2) echo "Scope Fence" ;;+ 3) echo "Architecture Sketch" ;;+ 4) echo "Foundation Pour" ;;+ 5) echo "Feature Blocks" ;;+ 6) echo "Integration Pass" ;;+ 7) echo "Polish & Harden" ;;+ 8) echo "Launch Prep" ;;+ 9) echo "Ship" ;;+ 10) echo "Listen & Iterate" ;;+ *) echo "Unknown" ;;+ esac+}++get_checkpoint_question() {+ local stage_num="$1"+ case $stage_num in+ 1) echo "What's the one-liner?" ;;+ 2) echo "What are we NOT building?" ;;+ 3) echo "Draw me the boxes and arrows." ;;+ 4) echo "Can we deploy an empty shell?" ;;+ 5) echo "Does this feature work completely, right now?" ;;+ 6) echo "Do all the pieces talk to each other?" ;;+ 7) echo "What breaks if I do something stupid?" ;;+ 8) echo "Could a stranger use this without asking me questions?" ;;+ 9) echo "Is it live and are people using it?" ;;+ 10) echo "What did we learn?" ;;+ *) echo "N/A" ;;+ esac+}++get_stage_emoji() {+ local stage_num="$1"+ case $stage_num in+ 1) echo "🎯" ;;+ 2) echo "🚧" ;;+ 3) echo "📐" ;;+ 4) echo "🏗️" ;;+ 5) echo "🧱" ;;+ 6) echo "🔗" ;;+ 7) echo "✨" ;;+ 8) echo "🚀" ;;+ 9) echo "🎉" ;;+ 10) echo "👂" ;;+ *) echo "📋" ;;+ esac+}++calculate_staleness_hours() {+ local status_file="$1"+ local last_modified=$(stat -f "%m" "$status_file" 2>/dev/null || stat -c "%Y" "$status_file" 2>/dev/null)+ local current_time=$(date +%s)+ echo $(( (current_time - last_modified) / 3600 ))+}++# Main briefing+main() {+ local status_file+ if ! status_file=$(find_pipeline_status); then+ # No pipeline - give a subtle hint+ echo -e "${DIM}💡 No pipeline found. Use: pipeline-progress-updater.sh init${NC}"+ exit 0+ fi++ local project=$(basename "$(dirname "$status_file")")+ local stage=$(get_current_stage "$status_file")+ local stage_name=$(get_stage_name "$stage")+ local checkpoint=$(get_checkpoint_question "$stage")+ local emoji=$(get_stage_emoji "$stage")+ local hours_since=$(calculate_staleness_hours "$status_file")++ # Compact but informative briefing+ echo ""+ echo -e "${BOLD}${CYAN}┌─────────────────────────────────────────────────────────────┐${NC}"+ echo -e "${BOLD}${CYAN}│${NC} ${BOLD}ID8Pipeline: ${project}${NC}"+ echo -e "${BOLD}${CYAN}├─────────────────────────────────────────────────────────────┤${NC}"++ # Status line+ if [[ $hours_since -ge $STALENESS_THRESHOLD_HOURS ]]; then+ echo -e "${BOLD}${CYAN}│${NC} ${RED}⚠ STALE (${hours_since}h)${NC} │ Stage $stage: $stage_name $emoji"+ else+ echo -e "${BOLD}${CYAN}│${NC} ${GREEN}✓ Active${NC} │ Stage $stage: $stage_name $emoji"+ fi++ echo -e "${BOLD}${CYAN}├─────────────────────────────────────────────────────────────┤${NC}"+ echo -e "${BOLD}${CYAN}│${NC} ${YELLOW}Checkpoint: \"$checkpoint\"${NC}"+ echo -e "${BOLD}${CYAN}└─────────────────────────────────────────────────────────────┘${NC}"++ # If stale, add urgency message+ if [[ $hours_since -ge $STALENESS_THRESHOLD_HOURS ]]; then+ echo ""+ echo -e "${RED}This stage hasn't been updated in ${hours_since} hours.${NC}"+ echo -e "${YELLOW}Suggested: Review PIPELINE_STATUS.md and update progress.${NC}"+ fi++ # Get personalized tip+ if [[ -x "$PIPELINE_PATTERNS" ]]; then+ echo ""+ echo -e "${DIM}$($PIPELINE_PATTERNS tip "$stage")${NC}"+ fi++ echo ""++ # Log session start+ if [[ -x "$PIPELINE_BRAIN" ]]; then+ "$PIPELINE_BRAIN" log "Session started at Stage $stage" 2>/dev/null || true+ fi+}++main "$@"diff --git a/hooks/pipeline/staleness-monitor.sh b/hooks/pipeline/staleness-monitor.shnew file mode 100755index 0000000..1a950b1--- /dev/null+++ b/hooks/pipeline/staleness-monitor.sh@@ -0,0 +1,260 @@+#!/bin/bash+# ═══════════════════════════════════════════════════════════════════════════════+# ID8Pipeline Staleness Monitor+# ═══════════════════════════════════════════════════════════════════════════════+# Runs periodically to check all tracked projects for staleness.+# Creates notifications and logs when projects need attention.+#+# Designed to run via launchd (Mac) or cron (Linux)+# ═══════════════════════════════════════════════════════════════════════════════++set -euo pipefail++PIPELINE_MEMORY_DIR="$HOME/.claude/pipeline-memory"+PROJECTS_FILE="$PIPELINE_MEMORY_DIR/tracked-projects.txt"+STALENESS_LOG="$PIPELINE_MEMORY_DIR/staleness.log"+STALENESS_REPORT="$PIPELINE_MEMORY_DIR/staleness-report.md"+STALENESS_THRESHOLD_HOURS=24++# Ensure directories exist+mkdir -p "$PIPELINE_MEMORY_DIR"++# Colors (for terminal output)+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+NC='\033[0m'++timestamp() {+ date "+%Y-%m-%d %H:%M:%S"+}++log() {+ echo "[$(timestamp)] $1" >> "$STALENESS_LOG"+}++# ─────────────────────────────────────────────────────────────────────────────+# Discover all projects with PIPELINE_STATUS.md+# ─────────────────────────────────────────────────────────────────────────────+discover_projects() {+ # Search common development directories+ local search_dirs=(+ "$HOME/Development"+ "$HOME/Projects"+ "$HOME/Code"+ "$HOME/repos"+ )++ local found_projects=()++ for dir in "${search_dirs[@]}"; do+ if [[ -d "$dir" ]]; then+ while IFS= read -r -d '' file; do+ found_projects+=("$(dirname "$file")")+ done < <(find "$dir" -maxdepth 3 -name "PIPELINE_STATUS.md" -type f -print0 2>/dev/null)+ fi+ done++ # Update tracked projects file+ printf '%s\n' "${found_projects[@]}" | sort -u > "$PROJECTS_FILE"++ echo "${#found_projects[@]}"+}++# ─────────────────────────────────────────────────────────────────────────────+# Check staleness for a single project+# ─────────────────────────────────────────────────────────────────────────────+check_project_staleness() {+ local project_dir="$1"+ local status_file="$project_dir/PIPELINE_STATUS.md"++ if [[ ! -f "$status_file" ]]; then+ echo "missing"+ return+ fi++ # Get last modified time+ local last_modified=$(stat -f "%m" "$status_file" 2>/dev/null || stat -c "%Y" "$status_file" 2>/dev/null)+ local current_time=$(date +%s)+ local hours_since=$(( (current_time - last_modified) / 3600 ))++ # Get current stage+ local stage=$(grep -oE "Current Stage: ([0-9]+)" "$status_file" 2>/dev/null | grep -oE "[0-9]+" | head -1 || echo "0")++ if [[ $hours_since -ge $STALENESS_THRESHOLD_HOURS ]]; then+ echo "stale:$hours_since:$stage"+ else+ echo "active:$hours_since:$stage"+ fi+}++# ─────────────────────────────────────────────────────────────────────────────+# Generate staleness report+# ─────────────────────────────────────────────────────────────────────────────+generate_report() {+ log "Generating staleness report"++ cat > "$STALENESS_REPORT" << 'HEADER'+# ID8Pipeline Staleness Report++> Generated: DATE_PLACEHOLDER+> Threshold: 24 hours++---++HEADER++ # Replace date placeholder+ sed -i.bak "s/DATE_PLACEHOLDER/$(date '+%Y-%m-%d %H:%M')/" "$STALENESS_REPORT"+ rm -f "${STALENESS_REPORT}.bak"++ local stale_count=0+ local active_count=0+ local total_count=0++ # Check if we have tracked projects+ if [[ ! -f "$PROJECTS_FILE" ]] || [[ ! -s "$PROJECTS_FILE" ]]; then+ discover_projects+ fi++ # Process each project+ echo "## Projects Needing Attention" >> "$STALENESS_REPORT"+ echo "" >> "$STALENESS_REPORT"++ local has_stale=false++ while IFS= read -r project_dir; do+ [[ -z "$project_dir" ]] && continue++ local result=$(check_project_staleness "$project_dir")+ local project_name=$(basename "$project_dir")++ ((total_count++))++ case $result in+ stale:*)+ local hours=$(echo "$result" | cut -d: -f2)+ local stage=$(echo "$result" | cut -d: -f3)+ ((stale_count++))+ has_stale=true++ echo "### $project_name" >> "$STALENESS_REPORT"+ echo "- **Status:** STALE ($hours hours)" >> "$STALENESS_REPORT"+ echo "- **Stage:** $stage" >> "$STALENESS_REPORT"+ echo "- **Path:** \`$project_dir\`" >> "$STALENESS_REPORT"+ echo "- **Action:** Review and update PIPELINE_STATUS.md" >> "$STALENESS_REPORT"+ echo "" >> "$STALENESS_REPORT"+ ;;+ active:*)+ ((active_count++))+ ;;+ esac+ done < "$PROJECTS_FILE"++ if [[ "$has_stale" == "false" ]]; then+ echo "None! All projects are active." >> "$STALENESS_REPORT"+ echo "" >> "$STALENESS_REPORT"+ fi++ # Summary section+ cat >> "$STALENESS_REPORT" << SUMMARY++---++## Summary++| Metric | Count |+|--------|-------|+| Total Projects | $total_count |+| Active | $active_count |+| Stale | $stale_count |++SUMMARY++ log "Report complete: $stale_count stale, $active_count active"++ echo "$stale_count"+}++# ─────────────────────────────────────────────────────────────────────────────+# Send notification (Mac notification + iMessage)+# ─────────────────────────────────────────────────────────────────────────────+send_notification() {+ local stale_count="$1"++ if [[ "$stale_count" -gt 0 ]]; then+ # Mac notification center+ if command -v osascript &> /dev/null; then+ osascript -e "display notification \"$stale_count project(s) need attention\" with title \"ID8Pipeline\" subtitle \"Staleness Alert\""+ fi++ # iMessage notification+ local messenger="$HOME/.claude/hooks/pipeline/pipeline-messenger.sh"+ if [[ -x "$messenger" ]] && [[ -f "$PIPELINE_MEMORY_DIR/messenger-config.txt" ]]; then+ # Get list of stale projects for the message+ local stale_list=""+ while IFS= read -r project_dir; do+ [[ -z "$project_dir" ]] && continue+ local result=$(check_project_staleness "$project_dir")+ case $result in+ stale:*)+ local hours=$(echo "$result" | cut -d: -f2)+ local stage=$(echo "$result" | cut -d: -f3)+ local name=$(basename "$project_dir")+ stale_list="${stale_list}• $name (Stage $stage, ${hours}h)\n"+ ;;+ esac+ done < "$PROJECTS_FILE"++ "$messenger" alert "🔴 $stale_count project(s) stale!++$stale_list+Reply Y to authorize autonomous work on the most stale project."+ fi++ log "Notification sent: $stale_count stale projects (desktop + iMessage)"+ fi+}++# ─────────────────────────────────────────────────────────────────────────────+# Main execution+# ─────────────────────────────────────────────────────────────────────────────+main() {+ log "Staleness monitor started"++ # Discover projects+ local discovered=$(discover_projects)+ log "Discovered $discovered projects"++ # Generate report+ local stale_count=$(generate_report)++ # Send notification if needed+ send_notification "$stale_count"++ # Output for terminal+ if [[ -t 1 ]]; then+ # Running in terminal, show summary+ echo ""+ echo -e "${YELLOW}═══════════════════════════════════════════════════${NC}"+ echo -e "${YELLOW} ID8Pipeline Staleness Check${NC}"+ echo -e "${YELLOW}═══════════════════════════════════════════════════${NC}"+ echo ""++ if [[ "$stale_count" -gt 0 ]]; then+ echo -e " ${RED}⚠ $stale_count project(s) are stale${NC}"+ echo ""+ echo " Review the full report:"+ echo " $STALENESS_REPORT"+ else+ echo -e " ${GREEN}✓ All projects are active${NC}"+ fi++ echo ""+ fi++ log "Staleness monitor completed"+}++# Run+main "$@"diff --git a/hooks/protect-main-branch.sh b/hooks/protect-main-branch.shnew file mode 100755index 0000000..72a7c99--- /dev/null+++ b/hooks/protect-main-branch.sh@@ -0,0 +1,31 @@+#!/bin/bash+# Protect Main Branch Hook+# Blocks file edits when on main/master branch+# Exit code 2 = block the tool call++# Get project directory from environment or use PWD+PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$PWD}"++# Check if we're in a git repo+if ! git -C "$PROJECT_DIR" rev-parse --git-dir > /dev/null 2>&1; then+ # Not a git repo, allow the edit+ exit 0+fi++# Get current branch+branch=$(git -C "$PROJECT_DIR" branch --show-current 2>/dev/null)++# Block edits on main or master+if [[ "$branch" == "main" ]] || [[ "$branch" == "master" ]]; then+ echo "BLOCKED: Cannot edit files on '$branch' branch." >&2+ echo "" >&2+ echo "Please create a feature branch first:" >&2+ echo " git checkout -b feature/your-feature-name" >&2+ echo "" >&2+ echo "Or use the git-workflow plugin:" >&2+ echo " /git-workflow:feature your-feature-name" >&2+ exit 2+fi++# Allow the edit+exit 0diff --git a/hooks/track-tool-usage.sh b/hooks/track-tool-usage.shnew file mode 100755index 0000000..94bf039--- /dev/null+++ b/hooks/track-tool-usage.sh@@ -0,0 +1,56 @@+#!/bin/bash+# Track Claude Code tool usage to id8labs API+# This hook fires after tool calls and increments the usage counter++# Configuration+API_URL="https://id8labs.app/api/claude-stats"+API_KEY_FILE="$HOME/.claude/.id8labs-api-key"++# Get tool name from hook context+# Claude hooks pass tool info via environment or stdin+TOOL_INPUT=$(cat)+TOOL_NAME="${CLAUDE_TOOL_NAME:-}"++# If tool name not in env, try to extract from input+if [ -z "$TOOL_NAME" ]; then+ # Try to get from hook arguments+ TOOL_NAME="$1"+fi++# Map tool names to our tracked categories+case "$TOOL_NAME" in+ Bash|bash)+ TOOL="bash"+ ;;+ Read|read)+ TOOL="read"+ ;;+ Edit|edit)+ TOOL="edit"+ ;;+ Write|write)+ TOOL="write"+ ;;+ *)+ # Unknown tool, skip tracking+ exit 0+ ;;+esac++# Check if API key exists+if [ ! -f "$API_KEY_FILE" ]; then+ # Silently skip if no API key configured+ exit 0+fi++API_KEY=$(cat "$API_KEY_FILE")++# Send increment request to API (background, non-blocking)+curl -s -X POST "$API_URL" \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $API_KEY" \+ -d "{\"tool\": \"$TOOL\", \"increment\": 1}" \+ > /dev/null 2>&1 &++# Always exit success to not block Claude+exit 0