sudo /usr/bin/bash -c "
grep -RIn --exclude-dir='__pycache__' --exclude='*.pyc' \
  -E \"INSERT INTO outreach_queue|UPDATE outreach_queue|sent_at|status='sent'|status = 'sent'\" \
  /Eden/CORE | head -n 120
"
echo
echo "== 2) Find who marks sent_at specifically =="
sudo /usr/bin/bash -c "
grep -RIn --exclude-dir='__pycache__' --exclude='*.pyc' \
  -E \"sent_at\" \
  /Eden/CORE | head -n 120
"
echo
echo "== 3) Show systemd ExecStart for the master service (to see what module actually runs) =="
sudo /usr/bin/systemctl show eden-master-consciousness.service -p ExecStart --no-pager
set -euo pipefail
FILE="/Eden/CORE/eden_github_sender.py"
BACKUP="${FILE}.bak.$(date +%s)"
echo "== 0) Backup =="
sudo cp "$FILE" "$BACKUP"
echo "Backup saved to: $BACKUP"
echo
echo "== 1) Patch file (idempotent) =="
sudo /usr/bin/python3 - <<'PY'
from pathlib import Path
import re

p = Path("/Eden/CORE/eden_github_sender.py")
src = p.read_text()

helper = '''
def bump_daily_limits(conn):
    cur = conn.cursor()
    cur.execute("""
        INSERT OR IGNORE INTO daily_limits(date, outreach_count, last_outreach_at)
        VALUES (date('now','localtime'), 0, NULL)
    """)
    cur.execute("""
        UPDATE daily_limits
        SET outreach_count = outreach_count + 1,
            last_outreach_at = datetime('now','localtime'),
            updated_at = datetime('now')
        WHERE date = date('now','localtime')
    """)
'''.strip()

# 1) Inject helper if missing
if "def bump_daily_limits(conn):" not in src:
    # place after imports
    m = re.search(r"(import .+\n)+", src)
    if not m:
        raise SystemExit("Could not find import block")
    insert_at = m.end()
    src = src[:insert_at] + "\n\n" + helper + "\n\n" + src[insert_at:]

# 2) Hook after outreach_queue sent update
pattern = re.compile(
    r"(UPDATE outreach_queue SET status\s*=\s*'sent'.+?\)\s*)",
    re.DOTALL
)

def repl(m):
    block = m.group(1)
    if "bump_daily_limits" in block:
        return block
    return block + "\n    bump_daily_limits(conn)\n    conn.commit()\n"

src_new, n = pattern.subn(repl, src, count=1)
if n == 0:
    raise SystemExit("❌ Could not find sent update block to hook")

p.write_text(src_new)
print("✅ Patch applied successfully")
PY

echo
echo "== 2) Syntax check =="
sudo /usr/bin/python3 -m py_compile "$FILE" && echo "✅ syntax ok"
echo
echo "== 3) Restart service =="
sudo /usr/bin/systemctl restart eden-master-consciousness.service
sleep 1
sudo /usr/bin/systemctl is-active eden-master-consciousness.service && echo "✅ active"
echo
echo "== 4) Verify daily_limits =="
sudo /usr/bin/sqlite3 /Eden/DATA/sales.db "
SELECT date, outreach_count, last_outreach_at
FROM daily_limits
ORDER BY date DESC
LIMIT 3;
"
set -euo pipefail
FILE="/Eden/CORE/eden_github_sender.py"
BACKUP="/Eden/CORE/eden_github_sender.py.bak.1765859884"
echo "== 0) Restore backup (undo bad patch) =="
sudo /usr/bin/cp "$BACKUP" "$FILE"
echo
echo "== 1) Apply safe line-based patch (no multiline regex) =="
sudo /usr/bin/python3 - <<'PY'
from pathlib import Path

p = Path("/Eden/CORE/eden_github_sender.py")
lines = p.read_text().splitlines()

# Insert helper once, right after the last import line.
helper = [
"def bump_daily_limits(conn):",
"    cur = conn.cursor()",
"    cur.execute(\"\"\"",
"        INSERT OR IGNORE INTO daily_limits(date, outreach_count, last_outreach_at)",
"        VALUES (date('now','localtime'), 0, NULL)",
"    \"\"\")",
"    cur.execute(\"\"\"",
"        UPDATE daily_limits",
"        SET outreach_count = outreach_count + 1,",
"            last_outreach_at = datetime('now','localtime'),",
"            updated_at = datetime('now')",
"        WHERE date = date('now','localtime')",
"    \"\"\")",
"",
]

if not any("def bump_daily_limits(conn)" in l for l in lines):
    last_import = -1
    for i,l in enumerate(lines):
        if l.startswith("import ") or l.startswith("from "):
            last_import = i
    if last_import == -1:
        raise SystemExit("❌ Could not find import block to insert helper after.")
    lines = lines[:last_import+1] + [""] + helper + lines[last_import+1:]

# Find the UPDATE outreach_queue ... status='sent' line, then insert bump/commit AFTER the execute call finishes.
# We'll insert after the first line that contains the UPDATE string AND after we see the closing ")" of that execute() call.
update_idx = None
for i,l in enumerate(lines):
    if "UPDATE outreach_queue" in l and "status" in l and "sent" in l:
        update_idx = i
        break
if update_idx is None:
    raise SystemExit("❌ Could not find the UPDATE outreach_queue ... sent statement in this file.")

# Walk forward to find the end of the conn.execute(...) block for that update.
end_idx = None
depth = 0
started = False
for j in range(update_idx, min(update_idx+60, len(lines))):
    lj = lines[j]
    # Count parentheses to detect end of execute call safely
    for ch in lj:
        if ch == "(":
            depth += 1
            started = True
        elif ch == ")":
            depth -= 1
    if started and depth <= 0:
        end_idx = j
        break
if end_idx is None:
    raise SystemExit("❌ Could not locate end of the conn.execute(...) block for the sent update.")

# Determine indentation based on the UPDATE line
indent = lines[update_idx][:len(lines[update_idx]) - len(lines[update_idx].lstrip())]
insertion = [
indent + "bump_daily_limits(conn)",
indent + "conn.commit()",
]

# Avoid double-inserting
window = "\n".join(lines[end_idx+1:end_idx+6])
if "bump_daily_limits(conn)" not in window:
    lines = lines[:end_idx+1] + insertion + lines[end_idx+1:]

p.write_text("\n".join(lines) + "\n")
print("✅ Safe patch applied")
PY

echo
echo "== 2) Syntax check =="
sudo /usr/bin/python3 -m py_compile "$FILE" && echo "✅ syntax ok"
echo
echo "== 3) Restart master service =="
sudo /usr/bin/systemctl restart eden-master-consciousness.service
sleep 1
sudo /usr/bin/systemctl is-active eden-master-consciousness.service && echo "✅ active"
echo
echo "== 4) Prove the hook exists (show the 40 lines around it) =="
sudo /usr/bin/python3 - <<'PY'
p="/Eden/CORE/eden_github_sender.py"
lines=open(p,"r",encoding="utf-8",errors="ignore").read().splitlines()
for i,l in enumerate(lines,1):
    if "UPDATE outreach_queue" in l and "sent" in l:
        start=max(1,i-15); end=min(len(lines), i+25)
        print("\n".join(f"{k:4d}: {lines[k-1]}" for k in range(start,end+1)))
        break
PY

set -euo pipefail
echo "== 1) Sent vs queued status counts =="
sudo /usr/bin/sqlite3 /Eden/DATA/sales.db "
SELECT status, COUNT(*) 
FROM outreach_queue
GROUP BY status
ORDER BY COUNT(*) DESC;
"
echo
echo "== 2) Any sent_at timestamps at all? =="
sudo /usr/bin/sqlite3 /Eden/DATA/sales.db "
SELECT COUNT(*) AS sent_with_timestamp
FROM outreach_queue
WHERE sent_at IS NOT NULL AND trim(sent_at) <> '';
"
echo
echo "== 3) Show the newest 10 by sent_at (if any exist) =="
sudo /usr/bin/sqlite3 /Eden/DATA/sales.db "
SELECT id, user, substr(issue_url,1,60), status, sent_at
FROM outreach_queue
WHERE sent_at IS NOT NULL AND trim(sent_at) <> ''
ORDER BY sent_at DESC
LIMIT 10;
"
set -euo pipefail
FILE="/Eden/CORE/eden_github_sender.py"
BACKUP="${FILE}.bak.utcfix.$(date +%s)"
echo "== 0) Backup =="
sudo /usr/bin/cp "$FILE" "$BACKUP"
echo "Backup: $BACKUP"
echo
echo "== 1) Replace localtime daily_limits with UTC daily_limits =="
sudo /usr/bin/python3 - <<'PY'
from pathlib import Path
p=Path("/Eden/CORE/eden_github_sender.py")
s=p.read_text()

s=s.replace("date('now','localtime')","date('now')")
s=s.replace("datetime('now','localtime')","datetime('now')")

p.write_text(s)
print("✅ Rewrote daily_limits to UTC in eden_github_sender.py")
PY

echo
echo "== 2) Syntax check =="
sudo /usr/bin/python3 -m py_compile "$FILE" && echo "✅ syntax ok"
echo
echo "== 3) Restart master =="
sudo /usr/bin/systemctl restart eden-master-consciousness.service
sleep 1
sudo /usr/bin/systemctl is-active eden-master-consciousness.service && echo "✅ active"
set -euo pipefail
DB="/Eden/DATA/sales.db"
echo "== 1) Ensure UTC 'today' row exists in daily_limits =="
sudo /usr/bin/sqlite3 "$DB" "
INSERT OR IGNORE INTO daily_limits(date, outreach_count)
VALUES (date('now'), 0);
SELECT date, outreach_count, last_outreach_at
FROM daily_limits
ORDER BY date DESC
LIMIT 6;
"
echo
echo "== 2) Compare: sent rows today (UTC) vs daily_limits today (UTC) =="
sudo /usr/bin/sqlite3 "$DB" "
WITH d AS (SELECT date('now') AS utc_today),
sent AS (
  SELECT COUNT(*) AS sent_today
  FROM outreach_queue, d
  WHERE sent_at IS NOT NULL
    AND trim(sent_at) <> ''
    AND substr(sent_at,1,10) = d.utc_today
)
SELECT
  (SELECT utc_today FROM d) AS utc_day,
  (SELECT sent_today FROM sent) AS sent_rows_today,
  COALESCE((SELECT outreach_count FROM daily_limits WHERE date=(SELECT utc_today FROM d)), -1) AS daily_limits_count;
"
set -euo pipefail
DB="/Eden/DATA/sales.db"
echo "== 1) Pick one failed row to retry =="
ROW="$(sudo /usr/bin/sqlite3 "$DB" "
SELECT id || '|' || issue_url || '|' || message
FROM outreach_queue
WHERE status='failed'
ORDER BY created_at DESC
LIMIT 1;
")"
if [ -z "$ROW" ]; then   echo "No failed rows to retry. We'll retry the newest sent row instead (won't bump unless re-sent).";   exit 0; fi
ID="$(echo "$ROW" | cut -d'|' -f1)"
URL="$(echo "$ROW" | cut -d'|' -f2)"
MSG="$(echo "$ROW" | cut -d'|' -f3-)"
echo "Retrying ID: $ID"
echo "URL: $URL"
echo
echo "== 2) Run sender directly (ensures our patched code path runs) =="
sudo /usr/bin/bash -c "cd /Eden/CORE && PYTHONPATH=/Eden/CORE /usr/bin/python3 - <<PY
from eden_github_sender import SENDER
res = SENDER.send_comment(\"$URL\", \"\"\"$MSG\"\"\", \"$ID\", None)
print(res)
PY"
set -euo pipefail
cat >/tmp/eden_retry_failed_outreach.py <<'PY'
import sqlite3
import sys
import os

DB="/Eden/DATA/sales.db"

def main():
    conn = sqlite3.connect(DB)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()

    row = c.execute("""
        SELECT id, issue_url, message
        FROM outreach_queue
        WHERE status='failed'
        ORDER BY created_at DESC
        LIMIT 1
    """).fetchone()

    if not row:
        print("No failed rows to retry.")
        return 0

    queue_id = row["id"]
    url = row["issue_url"]
    msg = row["message"] or ""

    print(f"Retrying ID: {queue_id}")
    print(f"URL: {url}")

    # Import sender from Eden codebase
    sys.path.insert(0, "/Eden/CORE")
    from eden_github_sender import SENDER

    res = SENDER.send_comment(url, msg, queue_id, None)
    print("Result:", res)

    # Show DB state + UTC daily_limits after attempt
    c2 = conn.cursor()
    st = c2.execute("SELECT id, status, sent_at FROM outreach_queue WHERE id=?", (queue_id,)).fetchone()
    dl = c2.execute("SELECT date, outreach_count, last_outreach_at FROM daily_limits WHERE date=date('now')").fetchone()

    print("Row now:", tuple(st) if st else None)
    print("UTC daily_limits:", tuple(dl) if dl else None)

    conn.close()
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
PY

# Run it from the correct working directory so imports behave
sudo /usr/bin/bash -c "cd /Eden/CORE && /usr/bin/python3 /tmp/eden_retry_failed_outreach.py"
set -u
TS="$(date +%s)"
LOG="/tmp/eden_retry_debug.${TS}.log"
DMESG="/tmp/eden_retry_debug.${TS}.dmesg.log"
JOUR="/tmp/eden_retry_debug.${TS}.journal.log"
echo "Logging to: $LOG"
echo "dmesg to:   $DMESG"
echo "journal to: $JOUR"
echo
# 1) Snapshot kernel + service logs BEFORE
sudo /usr/bin/dmesg -T | tail -n 200 >"$DMESG" 2>/dev/null || true
sudo /usr/bin/journalctl -u eden-master-consciousness.service -b --no-pager -n 200 >"$JOUR" 2>/dev/null || true
# 2) Write the retry script (again) but run it ultra-safely and capture everything
cat >/tmp/eden_retry_failed_outreach.py <<'PY'
import sqlite3, sys, traceback

DB="/Eden/DATA/sales.db"

def main():
    conn = sqlite3.connect(DB)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()

    row = c.execute("""
        SELECT id, issue_url, message
        FROM outreach_queue
        WHERE status='failed'
        ORDER BY created_at DESC
        LIMIT 1
    """).fetchone()

    if not row:
        print("No failed rows to retry.")
        return 0

    queue_id = row["id"]
    url = row["issue_url"]
    msg = row["message"] or ""

    print(f"Retrying ID: {queue_id}")
    print(f"URL: {url}")
    print(f"Message length: {len(msg)}")

    sys.path.insert(0, "/Eden/CORE")
    from eden_github_sender import SENDER

    res = SENDER.send_comment(url, msg, queue_id, None)
    print("Result:", res)

    st = conn.execute("SELECT id, status, sent_at FROM outreach_queue WHERE id=?", (queue_id,)).fetchone()
    dl = conn.execute("SELECT date, outreach_count, last_outreach_at FROM daily_limits WHERE date=date('now')").fetchone()

    print("Row now:", tuple(st) if st else None)
    print("UTC daily_limits:", tuple(dl) if dl else None)

    conn.close()
    return 0

if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception:
        traceback.print_exc()
        raise
PY

echo "== RUN START $(date) ==" | tee "$LOG"
# Run without `set -e` behavior killing the shell; we capture the exit code ourselves.
sudo /usr/bin/bash -c "cd /Eden/CORE && /usr/bin/python3 /tmp/eden_retry_failed_outreach.py" >>"$LOG" 2>&1
EC=$?
echo "== RUN END $(date) exit_code=$EC ==" | tee -a "$LOG"
# 3) Snapshot kernel + logs AFTER (look for OOM/kill/segfault)
echo >>"$DMESG"
echo "==== AFTER ====" >>"$DMESG"
sudo /usr/bin/dmesg -T | tail -n 200 >>"$DMESG" 2>/dev/null || true
echo >>"$JOUR"
echo "==== AFTER ====" >>"$JOUR"
sudo /usr/bin/journalctl -u eden-master-consciousness.service -b --no-pager -n 250 >>"$JOUR" 2>/dev/null || true
echo
echo "Done."
echo "Exit code: $EC"
echo "Open logs:"
echo "  $LOG"
echo "  $DMESG"
echo "  $JOUR"
set -euo pipefail
TS="$(date +%s)"
LOG="/tmp/eden_retry_debug.${TS}.log"
echo "Logging to: $LOG"
sudo /usr/bin/python3 - <<'PY'
from pathlib import Path
code = r'''import sqlite3, sys, traceback

DB="/Eden/DATA/sales.db"

def main():
    conn = sqlite3.connect(DB)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()

    row = c.execute("""
        SELECT id, issue_url, message
        FROM outreach_queue
        WHERE status='failed'
        ORDER BY created_at DESC
        LIMIT 1
    """).fetchone()

    if not row:
        print("No failed rows to retry.")
        return 0

    queue_id = row["id"]
    url = row["issue_url"]
    msg = row["message"] or ""

    print(f"Retrying ID: {queue_id}")
    print(f"URL: {url}")
    print(f"Message length: {len(msg)}")

    sys.path.insert(0, "/Eden/CORE")
    from eden_github_sender import SENDER

    res = SENDER.send_comment(url, msg, queue_id, None)
    print("Result:", res)

    st = conn.execute("SELECT id, status, sent_at FROM outreach_queue WHERE id=?", (queue_id,)).fetchone()
    dl = conn.execute("SELECT date, outreach_count, last_outreach_at FROM daily_limits WHERE date=date('now')").fetchone()

    print("Row now:", tuple(st) if st else None)
    print("UTC daily_limits:", tuple(dl) if dl else None)

    conn.close()
    return 0

if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception:
        traceback.print_exc()
        raise
'''
Path("/tmp/eden_retry_failed_outreach.py").write_text(code, encoding="utf-8")
print("Wrote /tmp/eden_retry_failed_outreach.py")
PY

