#!/bin/bash
# K2.5 Watchdog - Kill runaway agents
# Run via cron every 5 minutes

LOG_FILE="/home/johan/clawd/memory/k2-watchdog.log"
THRESHOLD_TOKENS=100000  # Alert if >100K tokens in session
KILL_THRESHOLD=500000    # Kill if >500K tokens

log() {
    echo "$(date -Iseconds) $1" >> "$LOG_FILE"
}

# Check k2-browser session size
SESSION_DIR="/home/johan/.clawdbot/agents/k2-browser/sessions"
if [ -d "$SESSION_DIR" ]; then
    for session in "$SESSION_DIR"/*.jsonl; do
        [ -f "$session" ] || continue
        
        # Count lines (roughly = API calls)
        LINES=$(wc -l < "$session" 2>/dev/null || echo 0)
        
        # Estimate tokens (rough: ~25K tokens per call with context)
        EST_TOKENS=$((LINES * 25000))
        
        if [ "$EST_TOKENS" -gt "$KILL_THRESHOLD" ]; then
            log "KILL: Session $session has $LINES calls (~${EST_TOKENS} tokens). Clearing sessions."
            rm -f "$SESSION_DIR"/*.jsonl
            systemctl --user restart clawdbot-gateway
            
            # Alert via Signal (if configured)
            # curl -X POST http://localhost:8080/v1/send -d '{"number":"+31...", "message":"K2 KILLED: runaway loop detected"}'
            
            log "Gateway restarted, sessions cleared"
            exit 1
        elif [ "$EST_TOKENS" -gt "$THRESHOLD_TOKENS" ]; then
            log "WARN: Session $session has $LINES calls (~${EST_TOKENS} tokens). Monitoring."
        fi
    done
fi

# Check if any session file is growing rapidly (modified in last 2 min with high line count)
RECENT=$(find "$SESSION_DIR" -name "*.jsonl" -mmin -2 -exec wc -l {} \; 2>/dev/null | awk '$1 > 50 {print}')
if [ -n "$RECENT" ]; then
    log "ACTIVE: Recent activity detected: $RECENT"
fi
