#!/bin/bash
# session-cleanup.sh — remove stale cron:run and openai subagent sessions
# Run at the start of each cron job to prevent accumulation

SESSIONS_DIR="$HOME/.openclaw/agents/main/sessions"
SESSIONS_JSON="$SESSIONS_DIR/sessions.json"

python3 - << 'EOF'
import json, os, sys

sessions_dir = os.path.expanduser("~/.openclaw/agents/main/sessions")
sessions_path = os.path.join(sessions_dir, "sessions.json")

with open(sessions_path) as f:
    data = json.load(f)

keep = {}
removed = 0

for key, val in data.items():
    sid = val.get("sessionId", "")
    if ":run:" in key or key.startswith("agent:main:openai:"):
        removed += 1
        jsonl = os.path.join(sessions_dir, sid + ".jsonl")
        if os.path.exists(jsonl):
            os.remove(jsonl)
    else:
        keep[key] = val

with open(sessions_path, "w") as f:
    json.dump(keep, f, indent=2)

if removed > 0:
    print(f"[session-cleanup] removed {removed} stale sessions", flush=True)
EOF
