#!/bin/sh
set -u

home="${HOME:-}"
now="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"

section() {
  printf '\n## %s\n' "$1"
}

count_files() {
  find "$1" "$2" -type f 2>/dev/null | wc -l | tr -d ' '
}

printf '# Mac Local-Agent Risk Scan\n'
printf '\nGenerated: %s\n' "$now"
printf 'Mode: read-only\n'

section "Top Memory Processes"
ps -axo pid,rss,comm 2>/dev/null | sort -nrk2 | head -12 | awk '
  NR == 1 { next }
  { printf "- pid=%s rss_mb=%.1f command=%s\n", $1, $2 / 1024, $3 }
'

section "Agent And Terminal Processes"
ps -axo pid,rss,command 2>/dev/null | awk '
  BEGIN { IGNORECASE = 1 }
  /codex|openclaw|claude|tmux|wezterm|node|computeruse|mcp/ && !/awk/ {
    printf "- pid=%s rss_mb=%.1f command=%s\n", $1, $2 / 1024, substr($0, index($0,$3), 180)
  }
' | head -40

section "tmux Sessions"
if command -v tmux >/dev/null 2>&1; then
  tmux ls 2>/dev/null | sed 's/^/- /' || printf '- none or tmux server not running\n'
else
  printf '- tmux not installed or not on PATH\n'
fi

section "Custom Launch Agents"
if [ -d "$home/Library/LaunchAgents" ]; then
  find "$home/Library/LaunchAgents" -maxdepth 1 -type f \( \
    -name 'com.igor.*.plist' -o \
    -name 'com.igorganapolsky.*.plist' -o \
    -name 'com.thumbgate.*.plist' -o \
    -name '*openclaw*.plist' -o \
    -name '*codex*.plist' -o \
    -name '*agent*.plist' \
  \) 2>/dev/null | sort | sed "s#^$home#~#" | sed 's/^/- /'
else
  printf '- LaunchAgents directory missing\n'
fi

section "Loaded Agent-Like launchd Jobs"
launchctl list 2>/dev/null | awk '
  BEGIN { IGNORECASE = 1 }
  /igor|thumbgate|openclaw|codex|agent|tmux/ { print "- " $0 }
' | head -80

section "Mail Outbox Queue"
if [ -d "$home/Library/Mail" ]; then
  outbox_count="$(find "$home/Library/Mail" -path '*Outbox.mbox*Messages*.emlx' -type f 2>/dev/null | wc -l | tr -d ' ')"
  printf '%s\n' "- outbox_emlx_count=$outbox_count"
else
  printf '%s\n' "- Mail directory missing"
fi

section "OpenClaw And Codex State Size"
for dir in "$home/.openclaw" "$home/.codex" "$home/.config/codex"; do
  if [ -d "$dir" ]; then
    size="$(du -sh "$dir" 2>/dev/null | awk '{print $1}')"
    printf -- '- %s size=%s\n' "$(printf '%s' "$dir" | sed "s#^$home#~#")" "${size:-unknown}"
  fi
done

section "Risk Flags"
risk=0

mail_count=0
if [ -d "$home/Library/Mail" ]; then
  mail_count="$(find "$home/Library/Mail" -path '*Outbox.mbox*Messages*.emlx' -type f 2>/dev/null | wc -l | tr -d ' ')"
fi
if [ "${mail_count:-0}" -gt 0 ] 2>/dev/null; then
  printf '%s\n' "- HIGH: Mail Outbox has queued messages. Disable outbound automation before retrying sends."
  risk=$((risk + 3))
fi

tmux_count=0
if command -v tmux >/dev/null 2>&1; then
  tmux_count="$(tmux ls 2>/dev/null | wc -l | tr -d ' ')"
fi
if [ "${tmux_count:-0}" -gt 5 ] 2>/dev/null; then
  printf '%s\n' "- MEDIUM: More than five tmux sessions are active. Check whether auto-restore is amplifying agent memory."
  risk=$((risk + 2))
fi

launch_count=0
if [ -d "$home/Library/LaunchAgents" ]; then
  launch_count="$(find "$home/Library/LaunchAgents" -maxdepth 1 -type f \( -name 'com.igor.*.plist' -o -name 'com.thumbgate.*.plist' -o -name '*agent*.plist' \) 2>/dev/null | wc -l | tr -d ' ')"
fi
if [ "${launch_count:-0}" -gt 8 ] 2>/dev/null; then
  printf '%s\n' "- MEDIUM: Many custom launch agents exist. Review persistence and duplicate revenue/automation jobs."
  risk=$((risk + 2))
fi

big_agent="$(ps -axo rss,comm 2>/dev/null | awk 'BEGIN { max=0; name="" } /Codex|codex|openclaw|node|WezTerm|tmux/ { if ($1 > max) { max=$1; name=$2 } } END { if (max > 4194304) printf "%s %.1f", name, max / 1024 }')"
if [ -n "$big_agent" ]; then
  printf '%s\n' "- HIGH: Agent-like process over 4GB RSS detected: $big_agent MB."
  risk=$((risk + 3))
fi

if [ "$risk" -eq 0 ]; then
  printf '%s\n' "- No high-confidence risk flags found from this read-only scan."
fi

section "Recommended Next Step"
if [ "$risk" -ge 5 ]; then
  printf '%s\n' "- Risk score: $risk/high"
  printf '%s\n' '- Buy the $99 diagnostic: https://buy.stripe.com/9B6fZhduQ4r42dz7mb3sI1h'
elif [ "$risk" -ge 2 ]; then
  printf '%s\n' "- Risk score: $risk/medium"
  printf '%s\n' '- Buy the $49 Safe Agent Ops Kit: https://buy.stripe.com/4gMcN59eAbTw7xTfSH3sI1q'
else
  printf '%s\n' "- Risk score: $risk/low"
  printf '%s\n' '- Keep the $49 kit bookmarked before adding more background agents: https://buy.stripe.com/4gMcN59eAbTw7xTfSH3sI1q'
fi

printf '\nGuide: https://igorganapolsky.github.io/AI_OpenClaw_Setup_Kits/guides/codex-openclaw-runaway-agent-safety.md\n'
