#!/usr/bin/env python3 """Why does context grow? Classify the last N days of messages per profile from state.db (read-only). Weighted cost = message size x number of model calls (assistant messages) after it in the same session, because a message stays in context and is resent on every later call until compression drops it. Run only with the user's permission, on their own profiles. Writes sizes/categories only, no message text. Usage: python3 context_growth_from_statedb.py [profile ...] -> ~/.hermes/cache/scratch/ajan-analiz/baglam.json""" import sqlite3, json, sys, time, re from pathlib import Path from collections import defaultdict H = Path.home() / '.hermes' PROF = sys.argv[1:] or ['default'] DAYS = 7 since = time.time() - DAYS * 86400 out = {} L = lambda x: len(x) if x else 0 for p in PROF: db = (H if p == 'default' else H / 'profiles' / p) / 'state.db' con = sqlite3.connect(f'file:{db}?mode=ro', uri=True) rows = con.execute("""select id, session_id, role, content, tool_calls, tool_name, reasoning, reasoning_content, reasoning_details, api_content from messages where timestamp > ? order by session_id, id""", (since,)).fetchall() by_sess = defaultdict(list) for r in rows: by_sess[r[1]].append(r) cat = defaultdict(lambda: [0, 0, 0]) # count, raw chars, weighted chars skills = defaultdict(lambda: [0, 0]); big = [] for s, ms in by_sess.items(): after = [0] * len(ms); c = 0 for i in range(len(ms) - 1, -1, -1): after[i] = c if ms[i][2] == 'assistant': c += 1 for i, (mid, sid, role, content, tcalls, tname, rsn, rsnc, rsnd, api) in enumerate(ms): w = after[i] if role == 'assistant': # reasoning, reasoning_content and reasoning_details hold the SAME thinking: take max, never sum for k, v in (('assistant text', L(content)), ('assistant tool args (written files, patches, scripts)', L(tcalls)), ('reasoning blocks', max(L(rsn), L(rsnc), L(rsnd)))): if v: cat[k][0] += 1; cat[k][1] += v; cat[k][2] += v * w continue size = max(L(content), L(api)) if role == 'tool': key = 'tool output: ' + (tname or '?') if tname == 'skill_view': m = re.search(r'"name":\s*"([^"]+)"', (content or '')[:500]) nm = m.group(1) if m else '?'; skills[nm][0] += 1; skills[nm][1] += size elif role == 'user': key = 'user / handoff message' else: key = 'other: ' + role cat[key][0] += 1; cat[key][1] += size; cat[key][2] += size * w if size > 30000: big.append((size, s[-12:], key)) # sizes only, never message text tw = sum(v[2] for v in cat.values()) or 1; tr = sum(v[1] for v in cat.values()) or 1 out[p] = {'sessions': len(by_sess), 'messages': len(rows), 'categories': sorted([[k, v[0], v[1], round(100 * v[1] / tr, 1), round(100 * v[2] / tw, 1)] for k, v in cat.items()], key=lambda x: -x[4])[:14], 'skill_view': sorted([[k, v[0], v[1]] for k, v in skills.items()], key=lambda x: -x[2])[:10], 'largest_messages': sorted(big, reverse=True)[:12]} print(p, 'ok', file=sys.stderr) dst = H / 'cache/scratch/ajan-analiz'; dst.mkdir(parents=True, exist_ok=True) json.dump(out, open(dst / 'baglam.json', 'w'), ensure_ascii=False, indent=1) print('done', dst / 'baglam.json')