import json,pathlib,subprocess,os,re
root=pathlib.Path(__file__).parent
for side in ['before','after']:
 log=(root/(side+'-settled-driver.log')).read_text()
 result=pathlib.Path(log.split('RESULTS ')[-1].strip()); run=result.parent; data=json.loads(result.read_text()); repo=run/'workspace'
 env={**os.environ,'GIT_INDEX_FILE':str(run/'control.index')}
 def git(*args): return subprocess.check_output(['git',*args],cwd=repo,env=env,text=True).strip()
 git('read-tree','HEAD'); git('add','-A'); control=git('ls-files','--stage')
 text=['Real T3 Code server checkpoint capture','Side: '+side,'Commit: '+data['sha'],'Environment: '+data['environment'],'Surface: source server, driven by the real t3 CLI; free devReplay multi-turn ACP provider.','Fresh database and fresh synthetic repository per side. No test service or checkpoint implementation called directly.','64 MiB deterministic random files; file content identical across both runs.','Waited >3 seconds after creating files; waited for each checkpoint ordinal before the next step.','Git commands below are selected from the server process Git Trace2 stream; exit statuses are Git process exit statuses.','Checkpoint trees below are actual git ls-tree -rl outputs.\n']
 for r in data['results']:
  n=r['turn']; text += ['TURN '+str(n), 'Mutation: '+({4:'write :ignored to .gitignore',5:'also ignore plain.bin and create 64 MiB :(magic)'}.get(n,'none')),'Git status --short --ignored:',r['statusIgnored'],'Server Git commands:']
  for c in r['reuseCommands']:
   argv=[str(x).replace(str(repo),'<workspace>') for x in c['argv']]
   text.append('  '+' '.join(argv)+' => exit '+str(c['exit']))
  for e in r['gitErrors']:
   if 'Invalid pathspec magic' in e: text.append('  Git error: '+e)
  text += ['Checkpoint ordinal '+str(n)+':',r['checkpoints'][str(n)],'']
 text += ['CONTROL after turn 9: fresh scratch index, git read-tree HEAD; git add -A; git ls-files --stage',control,'', 'Driver intentionally leaves the working index untouched. No timing claim is inferred; reuse is established by core.ignorestat=true update-index.']
 transcript='\n'.join(text)+'\n'; (root/(side+'-transcript.txt')).write_text(transcript)
 # Published structured capture retains all collected data, with synthetic workspace paths normalized.
 public=json.dumps(data,indent=2).replace(str(repo),'<workspace>')
 (root/(side+'-results.json')).write_text(public)
 print(side, data['sha'],data['environment'])
 print('control:',control)
