#!/bin/bash
# Nightly Self-Audit — Wakes each agent with the self-audit prompt
#
# Schedule: cron at 2:00 AM AEDT daily (before 4 AM session reset)
# Install:  crontab -e → 0 2 * * * /home/ccuser/rateright-growth/rivet/scripts/nightly-self-audit.sh >> /home/ccuser/logs/self-audit.log 2>&1
#
# Uses agent-bridge.js to wake each agent sequentially (not parallel —
# avoids VPS CPU spike from 7 agents thinking simultaneously on 4 vCPU)

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BRIDGE="$SCRIPT_DIR/agent-bridge.js"
LOG_DATE=$(date +%Y-%m-%d)

echo "[$LOG_DATE $(date +%H:%M:%S)] === Nightly Self-Audit Starting ==="

# The audit prompt — same for all agents, they each interpret it through their own SOUL.md
AUDIT_PROMPT='NIGHTLY SELF-AUDIT — Follow the "Nightly Self-Audit" protocol in AGENTS.md exactly.

Part 1: Housekeeping — consolidate daily notes, trim MEMORY.md, check alignment with CURRENT.md.
Part 2: Self-Assessment — what did you produce today? What was your biggest miss? Is your documentation accurate?
Part 3: Think Beyond Your Instructions — what is Michael NOT asking for that he should be? What could you do that nobody asked? What do you know that another agent needs?

Write results to memory/'"$LOG_DATE"'.md under ## Self-Audit. Keep it under 30 lines. If you have a real insight, ACT on it — do not just log it.'

# Agents to audit (all except Builder — Builder's workspace is separate and code-focused)
# Rivet audits last so it can read other agents' audit outputs
AGENTS=(susan harper sentinel radar herald cog rivet)

SUCCEEDED=0
FAILED=0

for agent in "${AGENTS[@]}"; do
  echo "[$LOG_DATE $(date +%H:%M:%S)] Waking $agent for self-audit..."

  if node "$BRIDGE" "$agent" wake "$AUDIT_PROMPT" 2>/dev/null; then
    echo "[$LOG_DATE $(date +%H:%M:%S)]   $agent: OK"
    SUCCEEDED=$((SUCCEEDED + 1))
  else
    echo "[$LOG_DATE $(date +%H:%M:%S)]   $agent: FAILED (may be offline)"
    FAILED=$((FAILED + 1))
  fi

  # 30-second gap between agents to avoid CPU spike
  if [ "$agent" != "rivet" ]; then
    sleep 30
  fi
done

echo "[$LOG_DATE $(date +%H:%M:%S)] === Self-Audit Complete: $SUCCEEDED succeeded, $FAILED failed ==="
