"""Use the CLI's real MCP authentication and transport to capture both read views.
Temporarily adds an environment-controlled read-only CLI branch, restores it afterwards.
Usage: python3 capture-mcp.py CHECKOUT THREAD_ID OUTPUT_DIRECTORY
"""
import sys,pathlib,subprocess,json
root,thread,out=sys.argv[1:];root=pathlib.Path(root);out=pathlib.Path(out);out.mkdir(parents=True,exist_ok=True)
source=root/'apps/server/src/cli/thread.ts';original=source.read_text()
needle='const { thread, messages: latest } = yield* readLatestMessages('
patch='''if (process.env.T3_EVIDENCE_VIEW) {
            const result = yield* tools.call("t3_thread_read", {threadId, view: process.env.T3_EVIDENCE_VIEW, limit: 100}, OrchestratorMcpThreadReadResult);
            return yield* printJson(result);
          }
          '''
try:
 source.write_text(original.replace(needle,patch+needle,1))
 import os,time
 time.sleep(6)
 for view in ['activity','messages']:
  result=subprocess.check_output(['node','apps/server/src/bin.ts','thread','show',thread,'--base-dir','.t3','--json'],cwd=root,env={**os.environ,'T3_EVIDENCE_VIEW':view},text=True)
  json.loads(result)
  (out/(view+'.json')).write_text(result)
finally:
 source.write_text(original)
