import { spawn, execFileSync } from "node:child_process";
import * as fs from "node:fs";
import * as path from "node:path";
import * as net from "node:net";
const APP_DIR=process.cwd();
let T3_HOME;

const scratch = process.env.PROOF_ARTIFACT_DIR;
const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
async function until<T>(label: string, read: () => Promise<T>, yes: (v:T)=>boolean, timeout=120000) {
  const end=Date.now()+timeout;
  while(Date.now()<end) { const v=await read(); if(yes(v)) return v; await pause(200); }
  throw new Error(`STEP_TIMEOUT: ${label}`);
}
function cli(home:string, args:string[]) {
  return execFileSync(process.execPath,["apps/server/src/bin.ts",...args,"--base-dir",home],{cwd:APP_DIR,encoding:"utf8",env:{...process.env,T3CODE_DEV_SEED:"0"}}).trim();
}
async function rpc(home:string) {
  const {origin}=JSON.parse(fs.readFileSync(path.join(home,"userdata/server-runtime.json"),"utf8"));
  const token=cli(home,["auth","session","issue","--token-only"]);
  const response=await fetch(origin+"/api/auth/websocket-ticket",{method:"POST",headers:{authorization:`Bearer ${token}`}});
  const {ticket}=await response.json() as any;
  if(!ticket) throw new Error(`No websocket ticket: ${response.status}`);
  const ws=new WebSocket(origin.replace(/^http/,"ws")+`/ws?orchestrationProtocol=2&wsTicket=${encodeURIComponent(ticket)}`);
  await new Promise<void>((resolve,reject)=>{ws.onopen=()=>resolve(); ws.onerror=reject;});
  let id=0; const pending=new Map<string,{resolve:(v:any)=>void,reject:(e:any)=>void}>();
  ws.onmessage=e=>{ for(const m of [JSON.parse(String(e.data))].flat()) {
    if(m._tag==="Ping") ws.send(JSON.stringify({_tag:"Pong"}));
    if(m._tag!=="Exit") continue;
    const p=pending.get(String(m.requestId)); if(!p) continue; pending.delete(String(m.requestId));
    if(m.exit._tag==="Success") p.resolve(m.exit.value); else p.reject(new Error(JSON.stringify(m.exit)));
  }};
  return {origin,close:()=>ws.close(),call:(tag:string,payload:any)=>new Promise<any>((resolve,reject)=>{
    const key=String(++id); pending.set(key,{resolve,reject});
    ws.send(JSON.stringify({_tag:"Request",id:key,tag,payload,headers:[],traceId:"01234567890123456789012345678901",spanId:"0123456789012345",sampled:false}));
  })};
}
async function mcp(endpoint:string,authorization:string) {
  let session="",id=0;
  async function request(method:string,params:any) {
    const response=await fetch(endpoint,{method:"POST",headers:{authorization,"content-type":"application/json",accept:"application/json, text/event-stream",...(session?{"mcp-session-id":session,"mcp-protocol-version":"2025-06-18"}:{})},body:JSON.stringify({jsonrpc:"2.0",id:++id,method,params})});
    session=response.headers.get("mcp-session-id")??session;
    const text=await response.text();
    if(!response.ok) throw new Error(`MCP HTTP ${response.status}: ${text}`);
    const messages=text.startsWith("{")?[JSON.parse(text)]:text.split("\n").filter(x=>x.startsWith("data: ")).map(x=>JSON.parse(x.slice(6)));
    const result=messages.find(x=>x.id===id); if(result?.error) throw new Error(JSON.stringify(result.error));
    return result?.result;
  }
  await request("initialize",{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"proof-replay-driver",version:"1"}});
  return async(name:string,args:any)=>{const r=await request("tools/call",{name,arguments:args}); if(r?.isError) throw new Error(JSON.stringify(r)); return r.structuredContent;};
}
// A transparent wrapper around the shipped replay agent. Only explicitly marked long turns
// are gated; every other turn is the repository's recorded multi-turn model.
const wrapper=String.raw`
import {spawn} from 'node:child_process';
import * as fs from 'node:fs';
import * as readline from 'node:readline';
import * as path from 'node:path';
const child=spawn(process.execPath,[process.argv[2]],{stdio:['pipe','pipe','inherit']});
child.stdout.pipe(process.stdout);
let cwd='',sessionId='',held;
const send=x=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...x})+'\n');
const update=text=>send({method:'session/update',params:{sessionId,update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text}}}});
readline.createInterface({input:process.stdin}).on('line',line=>{
 const m=JSON.parse(line),p=m.params??{};
 if(m.method==='session/new'||m.method==='session/load'){
  cwd=p.cwd; fs.writeFileSync(path.join(cwd,'.proof-mcp.json'),JSON.stringify(p.mcpServers),{mode:0o600});
 }
 if(m.method==='session/prompt'){
  sessionId=p.sessionId;
  const text=JSON.stringify(p.prompt);
  if(text.includes('PROOF_PARENT_HOLD')||text.includes('UNRELATED_ACTIVE_WORK')){
   update(text.includes('PROOF_PARENT_HOLD')?'Originating agent is coordinating the remote task.\n':'Unrelated active work is running; waiting for its explicit release.\n');
   held={id:m.id,parent:text.includes('PROOF_PARENT_HOLD')};
   const timer=setInterval(()=>{if(!held){clearInterval(timer);return;} if(fs.existsSync(path.join(cwd,'.proof-release'))){clearInterval(timer); update('Unrelated active work completed normally.\n'); send({id:held.id,result:{stopReason:'end_turn'}});held=undefined;}},100);
   return;
  }
  if(text.includes('CANCEL_ONLY_THIS_QUEUED_FOLLOWUP')){update('CANCELLED FOLLOW-UP EXECUTED: this should never run.\n');send({id:m.id,result:{stopReason:'end_turn'}});return;}
  if(text.includes('PRESERVE_OTHER_QUEUED_WORK')){update('Other queued work completed normally.\n');send({id:m.id,result:{stopReason:'end_turn'}});return;}
 }
 if(m.method==='session/cancel'&&held){send({id:held.id,result:{stopReason:'cancelled'}});held=undefined;return;}
 child.stdin.write(line+'\n');
});
process.on('SIGTERM',()=>{child.kill('SIGTERM');process.exit();});
`;

async function main(){
 const runDir=fs.mkdtempSync(path.join(scratch,"manual-"));
const castFile=path.join(runDir,"session.cast");
fs.writeFileSync(castFile,JSON.stringify({version:2,width:110,height:38,title:"Real T3 server: queued remote follow-up cancellation"})+"\n");
const start=Date.now(),write=process.stdout.write.bind(process.stdout);
process.stdout.write=(chunk,...args)=>{fs.appendFileSync(castFile,JSON.stringify([(Date.now()-start)/1000,"o",String(chunk).replaceAll("\n","\r\n")])+"\n");return write(chunk,...args);};
console.log("Reproduction: queued remote follow-up cancellation");
console.log("Commit:",execFileSync("git",["rev-parse","HEAD"],{encoding:"utf8"}).trim());
console.log("Surface: real T3 servers, MCP over HTTP, authenticated linked peer, fresh synthetic data.");
 T3_HOME=path.join(runDir,"origin");
 const localPort=await new Promise(resolve=>{const s=net.createServer();s.listen(0,"127.0.0.1",()=>{const p=s.address().port;s.close(()=>resolve(p));});});
 const localLog=fs.openSync(path.join(runDir,"origin.log"),"w");
 const local=spawn(process.execPath,[path.join(APP_DIR,"scripts/scenarios/start-app.ts"),"web",T3_HOME,"127.0.0.1",String(localPort)],{cwd:APP_DIR,env:{...process.env,T3CODE_DEV_SEED:"0"},stdio:["ignore",localLog,localLog]});
 const remoteHome=path.join(runDir,"peer");
 const wrapperPath=path.join(runDir,"replay-wrapper.mjs");fs.writeFileSync(wrapperPath,wrapper);
 const port=await new Promise<number>(resolve=>{const s=net.createServer();s.listen(0,"127.0.0.1",()=>{const p=(s.address() as net.AddressInfo).port;s.close(()=>resolve(p));});});
 const remoteUrl=`http://127.0.0.1:${port}`;
 const log=fs.openSync(path.join(runDir,"peer.log"),"w");
 const remote=spawn(process.execPath,[path.join(APP_DIR,"scripts/scenarios/start-app.ts"),"web",remoteHome,"127.0.0.1",String(port)],{cwd:APP_DIR,env:{...process.env,T3CODE_DEV_SEED:"0"},stdio:["ignore",log,log]});
 let localRpc:any,remoteRpc:any;
 try {
  await until("remote app startup",async()=>{try{return (await fetch(remoteUrl+"/.well-known/t3/environment")).ok;}catch{return false;}},Boolean);
  await until("origin startup",async()=>{try{return (await fetch(`http://127.0.0.1:${localPort}/.well-known/t3/environment`)).ok;}catch{return false;}},Boolean);
  localRpc=await rpc(T3_HOME);remoteRpc=await rpc(remoteHome);
  const config={driver:"acpRegistry",displayName:"Replay (proof)",enabled:true,config:{source:"local",commandPath:process.execPath,commandArgs:[wrapperPath,path.join(APP_DIR,"apps/server/scripts/dev-replay-agent.ts")]}};
  for(const r of [localRpc,remoteRpc]) await r.call("server.updateSettings",{patch:{linkedEnvironmentsEnabled:true},providerInstanceMutation:{operation:"upsert",instanceId:"devReplay",instance:config}});
  const state=(home)=>({
project:async(title)=>{const root=path.join(home,"workspaces",title);fs.mkdirSync(root,{recursive:true});fs.writeFileSync(path.join(root,".gitignore"),".proof-*\n");execFileSync("git",["init","-q","--initial-branch=main",root]);execFileSync("git",["-C",root,"add","."]);execFileSync("git",["-C",root,"-c","user.name=Proof","-c","user.email=proof@example.invalid","commit","-qm","Initial commit"]);cli(home,["project","add",root,"--title",title]);return root;},
thread:async({project,title,messages})=>JSON.parse(cli(home,["thread","start",project,messages[0],"--title",title,"--provider","devReplay","--model","multi-turn","--wait","--json"]))
});
const t3=state(T3_HOME);const peerState=state(remoteHome);
  const project=await t3.project("Origin project");
  const peerProject=await peerState.project("Remote project");
  const origin=await t3.thread({project,title:"Remote task coordinator",messages:["first"]});
  cli(T3_HOME,["thread","send",origin.threadId,"PROOF_PARENT_HOLD","--json"]);
  await until("origin provider credential",async()=>fs.existsSync(path.join(project,".proof-mcp.json")),Boolean);
  const servers=JSON.parse(fs.readFileSync(path.join(project,".proof-mcp.json"),"utf8"));
  const server=servers.find((x:any)=>x.name==="t3")??servers[0];
  const env=Object.fromEntries((server.env??[]).map((x:any)=>[x.name,x.value]));
  const auth=server.headers?.find((x:any)=>x.name.toLowerCase()==="authorization")?.value??env.T3_ACP_MCP_AUTHORIZATION;
  const endpoint=server.url??env.T3_ACP_MCP_ENDPOINT;
  const call=await mcp(endpoint,auth);
  const pair=JSON.parse(cli(remoteHome,["auth","pairing","create","--json"]));
  const link=await localRpc.call("peerLinks.link",{url:remoteRpc.origin,pairingCode:pair.credential,access:"full-access",expectedLabel:"Remote proof environment"});
  const environmentId=link.environmentId;
  const projects=await call("t3_project_list",{environmentId,limit:100});
  const peerProjectId=projects.projects.find((x:any)=>x.workspaceRoot===peerProject).id;
  await call("orchestrator_capabilities",{environmentId});
  const delegated=await call("delegate_task",{task:"first",title:"Remote follow-up cancellation",target:{environmentId,projectId:peerProjectId,providerInstanceId:"devReplay",model:"multi-turn"},mode:"async"});
  const threadId=delegated.remoteChild.threadId;
  const read=()=>call("t3_thread_read",{environmentId,threadId,runLimit:20,limit:20});
  await until("initial delegation finishes",()=>call("task_status",{taskId:delegated.taskId}),(r:any)=>r.status==="completed");
  const active=await call("t3_thread_send",{environmentId,threadId,message:"UNRELATED_ACTIVE_WORK",mode:"queue"});
  await until("unrelated run is running",read,(r:any)=>r.recentRuns.some((x:any)=>x.runId===active.runId&&x.status==="running"));
  const target=await call("t3_thread_send",{environmentId,threadId,message:"CANCEL_ONLY_THIS_QUEUED_FOLLOWUP",mode:"queue"});
  const other=await call("t3_thread_send",{environmentId,threadId,message:"PRESERVE_OTHER_QUEUED_WORK",mode:"queue"});
  const print=(label,r)=>{
fs.appendFileSync(path.join(runDir,"responses.ndjson"),JSON.stringify({step:label,response:r})+"\n");
console.log("\n"+label);
if(r.runs){console.table(r.runs.map(x=>({work:x.label,status:x.status})));for(const m of r.messages??[]) if(m.text?.includes("completed normally")||m.text?.includes("CANCELLED FOLLOW-UP EXECUTED"))console.log(m.text.trim());}
else if(label.includes("cancel only")) console.log("Retained taskId and exact queued runId (see responses.ndjson).");
else console.log(JSON.stringify(r));
};
  const compact=r=>({threadStatus:r.thread.status,runs:r.recentRuns.map(x=>({label:x.runId===active.runId?"unrelated active work":x.runId===target.runId?"cancel target":x.runId===other.runId?"other queued work":"initial delegation",runId:x.runId,status:x.status,startedAt:x.startedAt,prompt:x.userMessage?.text??null})),messages:r.items.filter(x=>x.type==="assistant_message"||x.type==="user_message").map(x=>({type:x.type,runId:x.runId,text:x.text}))});
  print("STEP 1: delegation finished; unrelated work is active; two follow-ups queued",compact(await read()));
  const gate=async(stage)=>{if(!process.env.PROOF_PAUSE_UI)return;fs.writeFileSync(path.join(runDir,"observer.json"),JSON.stringify({stage,remoteUrl,environmentId,threadId,remoteHome}));await until("observer "+stage,async()=>fs.existsSync(path.join(runDir,stage+".continue")),Boolean,900000);};
  await gate("before-cancel");
  print("STEP 2: cancel only this task and run",{taskId:target.taskId,runId:target.runId});
  const cancelled=await call("task_cancel",{taskId:target.taskId});
  const afterCancel=await read();
  print("STEP 3: task_cancel response",cancelled);print("STEP 4: remote state immediately after cancellation",compact(afterCancel));
  await gate("after-cancel");
  console.log("\nSTEP 5: resume the remote queue and release unrelated active work");
  await remoteRpc.call("orchestration.dispatchCommand",{type:"queue.resume",commandId:crypto.randomUUID(),threadId});
  fs.writeFileSync(path.join(peerProject,".proof-release"),"release");
  const final=await until("other queued work finishes",read,(r:any)=>r.recentRuns.some((x:any)=>x.runId===other.runId&&x.status==="completed"));
  print("STEP 6: remote state after queue.resume and releasing unrelated active work",compact(final));
  const status=(r:any,id:string)=>r.recentRuns.find((x:any)=>x.runId===id)?.status;
  const localFinal=await until("local cancellation settles",()=>call("task_status",{taskId:target.taskId}),r=>r.status==="cancelled");
  const evidence={activeAfterCancel:status(afterCancel,active.runId),targetAfterCancel:status(afterCancel,target.runId),otherAfterCancel:status(afterCancel,other.runId),activeAfterResume:status(final,active.runId),targetAfterResume:status(final,target.runId),otherAfterResume:status(final,other.runId),localTaskStatus:localFinal.status,cancelResponse:cancelled.status,taskId:target.taskId,runId:target.runId};
  fs.writeFileSync(path.join(runDir,"observations.json"),JSON.stringify(evidence,null,2));

  await gate("after-resume");
  console.log("\nObserved outcome (real server responses):");const {taskId,runId,...outcome}=evidence;console.table(outcome);
 } finally {
  localRpc?.close();remoteRpc?.close();remote.kill("SIGTERM");
  await new Promise<void>(resolve=>{if(remote.exitCode!==null)resolve();else remote.once("exit",()=>resolve());});
  local.kill("SIGTERM");await new Promise(resolve=>{if(local.exitCode!==null)resolve();else local.once("exit",()=>resolve());});fs.closeSync(localLog);
  fs.closeSync(log);
 }
}
await main();
