Skip to content
Shell
10.1 KB
Raw Blame
#!/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 "$@"