import json, time, sys
from pathlib import Path

# Read only the native Claude session's naming records; never modify it.
session_id = Path('session-id').read_text().strip()
files = list((Path.home() / '.claude' / 'projects').glob('*/' + session_id + '.jsonl'))
if len(files) != 1:
    raise RuntimeError('Expected one native Claude session')
start = time.monotonic()
previous = None
print('\033[?25l', end='', flush=True)
print('READ-ONLY native Claude session observer', flush=True)
print('Source: session JSONL custom-title / agent-name records', flush=True)
while True:
    rows = []
    for line in files[0].read_text().splitlines():
        try:
            row = json.loads(line)
        except ValueError:
            continue
        if row.get('type') in ('custom-title', 'agent-name'):
            rows.append({k: row[k] for k in ('type', 'customTitle', 'agentName') if k in row})
    elapsed = round(time.monotonic() - start, 1)
    if rows != previous:
        print('\nNative naming records (%d):' % len(rows), flush=True)
        for kind in ('custom-title', 'agent-name'):
            entries = [r for r in rows if r['type'] == kind]
            print('  %s = %s' % (kind, json.dumps(entries[-1] if entries else None)), flush=True)
        with open('observer.jsonl', 'a') as log:
            log.write(json.dumps({'elapsedSeconds': elapsed, 'namingRecords': rows}) + '\n')
        previous = rows
    if '--once' in sys.argv:
        break
    if Path('freeze').exists():
        time.sleep(0.5)
        continue
    print('\rObserved for %5.1fs | latest native name: %s    ' % (elapsed, (rows[-1].get('customTitle') or rows[-1].get('agentName')) if rows else '(none)'), end='', flush=True)
    time.sleep(0.5)
