#!/bin/bash
# Auto-archive old sessions for all agents
# Keeps the 3 newest .jsonl files, archives the rest
# Run daily via cron

AGENTS="rivet:clawdbot builder:clawdbot-builder susan:clawdbot-susan harper:clawdbot-harper sentinel:clawdbot-sentinel radar:clawdbot-radar herald:clawdbot-herald cog:clawdbot-cog"

for entry in $AGENTS; do
  agent=${entry%%:*}
  case $agent in
    rivet) dir="/root/.clawdbot/agents/main/sessions" ;;
    *) dir="/root/.clawdbot-$agent/agents/main/sessions" ;;
  esac
  
  [ -d "$dir" ] || continue
  
  count=$(ls "$dir"/*.jsonl 2>/dev/null | wc -l)
  if [ "$count" -gt 5 ]; then
    mkdir -p "$dir/archive"
    cd "$dir"
    to_archive=$(ls -t *.jsonl 2>/dev/null | tail -n +4)
    archived=0
    for f in $to_archive; do
      mv "$f" archive/ 2>/dev/null && ((archived++))
    done
    if [ "$archived" -gt 0 ]; then
      cd archive
      tar czf "sessions-$(date +%Y%m%d).tar.gz" *.jsonl 2>/dev/null && rm -f *.jsonl 2>/dev/null
      echo "$(date -Iseconds) $agent: archived $archived sessions"
    fi
  fi
done
