#!/usr/bin/env python3
"""Transparent Claude wrapper; public records contain only whitelisted evidence."""
import json, os, pathlib, signal, subprocess, sys, threading, time
home=pathlib.Path(os.environ['CLAUDE_CONFIG_DIR'])
c=json.loads((home.parent/'capture-context.json').read_text())
pid=os.getpid(); log=pathlib.Path(c['runDir'])/f'spawn-{pid}.jsonl'
def record(x):
 with log.open('a') as f: f.write(json.dumps(x,sort_keys=True)+'\n')
a=sys.argv[1:]
fmt=a[a.index('--output-format')+1] if '--output-format' in a else None
route='version' if '--version' in a else ('C3 text generation' if fmt=='json' else 'C1 session or C2 capability probe')
if c.get('cliControl'):route='CLI control (not T3 caller)'
record({'event':'spawn','commit':c['commit'],'claudeVersion':c['claudeVersion'],'fixture':c['fixture'],'pid':pid,'ppid':os.getppid(),'route':route,'argvSummary':{'outputFormat':fmt,'print':'-p' in a or '--print' in a,'toolsArgumentPresent':'--tools' in a,'hasSessionId':'--session-id' in a,'hasJsonSchema':'--json-schema' in a},'env':{k:os.environ.get(k) for k in ['CLAUDE_CODE_ENTRYPOINT','CLAUDE_CODE_ARTIFACT','claude_code_artifact']},'settings':json.loads((home/'settings.json').read_text()) if (home/'settings.json').exists() else {}})
p=subprocess.Popen([c['realClaude'],*a],stdout=subprocess.PIPE)
record({'event':'exec-child','pid':p.pid})
if fmt=='json':
 timer=threading.Timer(5,lambda: p.terminate() if p.poll() is None else None);timer.daemon=True;timer.start()
raw=pathlib.Path(c['runDir'])/f'private-stdout-{pid}.jsonl'
buf=b''; init=False
with raw.open('wb') as f:
 while True:
  chunk=os.read(p.stdout.fileno(),65536)
  if not chunk:break
  f.write(chunk);f.flush();os.write(1,chunk);buf+=chunk
  while b'\n' in buf:
   line,buf=buf.split(b'\n',1)
   try:e=json.loads(line)
   except (ValueError,UnicodeDecodeError):continue
   if e.get('type')=='system' and e.get('subtype')=='init':
    tools=[t for t in e.get('tools',[]) if t in ['Artifact','ArtifactComments','ArtifactData']]
    record({'event':'system/init','artifactTools':tools,'artifactToolCount':len(tools),'modelField':'removed','sessionId':'removed','unrelatedTools':'removed'});init=True
    if c.get('stopAfterInit',True):p.terminate()
rc=p.wait();record({'event':'exit','code':rc,'initObserved':init});sys.exit(rc if rc>=0 else 128-rc)
