import subprocess, time, os, sys
TRACE = r'C:\Users\decid\AppData\Local\spt-core\adapters\_github\SaberMage-claude-spt\hook-trace.log'
SID = '19d48c98-d787-4436-90c2-da3f52339ae1'

def tail_size():
    try: return os.path.getsize(TRACE)
    except OSError: return 0

def read_from(off):
    try:
        with open(TRACE, 'rb') as f:
            f.seek(off)
            return f.read().decode('utf-8', 'replace')
    except OSError:
        return ''

base = tail_size()
t0 = time.time()
print('PROBE START epoch_ms=%d trace_off=%d' % (int(t0*1000), base))

# 1. tell core this endpoint is IDLE even though this turn is mid-flight
r = subprocess.run(['spt','api','--adapter','claude-spt','state','idle','perri','--session-id',SID],
                   capture_output=True, text=True)
print('state idle rc=%d out=%r err=%r' % (r.returncode, r.stdout.strip()[:200], r.stderr.strip()[:200]))

# 2. self-send -> core should take the IDLE route: PTY-type a stub + Enter into the input box
r = subprocess.run(['spt','send','--from','perri','perri'], input='ENQUEUE-PROBE-PAYLOAD',
                   capture_output=True, text=True)
print('send rc=%d out=%r err=%r' % (r.returncode, r.stdout.strip()[:200], r.stderr.strip()[:200]))
sent_ms = int(time.time()*1000)
print('SENT epoch_ms=%d (+%.1fs)' % (sent_ms, time.time()-t0))

# 3. watch for a UserPromptSubmit BEGIN while THIS turn is still executing
deadline = t0 + 30
seen = []
while time.time() < deadline:
    chunk = read_from(base)
    for line in chunk.split('\n'):
        if 'BEGIN UserPromptSubmit' in line and line not in seen:
            seen.append(line)
            print('  *** UPS BEGIN WHILE BUSY (+%.1fs): %s' % (time.time()-t0, line.strip()))
    time.sleep(0.4)

print('PROBE END epoch_ms=%d elapsed=%.1fs ups_begin_during_turn=%d' % (int(time.time()*1000), time.time()-t0, len(seen)))
print('VERDICT: %s' % ('ENQUEUE (hook fired while turn still running)' if seen else 'no UPS during the turn -> consistent with DEQUEUE, pending next-turn check'))
tailtxt = read_from(base)
print('--- all new trace bytes (%d) ---' % len(tailtxt))
sys.stdout.write(tailtxt[-3000:])
