import { readFileSync } from 'node:fs';
import { platform, release, arch } from 'node:os';
console.log(JSON.stringify({environment:{node:process.version,runner:'global vp v1.3.0 / local vite-plus v1.4.0 / Vitest v5.0.5',os:`${platform()} ${release()} ${arch()}`,vm:readFileSync('/home/ubuntu/.agents/MACHINE','utf8').trim()}}));
import { execFileSync } from 'node:child_process';
import { it, expect } from '@effect/vitest';
import { EnvironmentId,ThreadId,MessageId,RunId,ORCHESTRATION_V2_WS_METHODS } from '@t3tools/contracts';
import * as Effect from 'effect/Effect';
import * as Crypto from 'effect/Crypto';
import * as Deferred from 'effect/Deferred';
import * as Layer from 'effect/Layer';
import * as Option from 'effect/Option';
import * as SubscriptionRef from 'effect/SubscriptionRef';
import { Atom,AtomRegistry } from 'effect/reactivity';
import * as Registry from '../connection/registry.ts';
import * as Supervisor from '../connection/supervisor.ts';
import { createThreadEnvironmentAtoms } from './threadCommands.ts';
import { ThreadHistoryController } from './threadHistoryController.ts';
const sha=execFileSync('git',['rev-parse','HEAD'],{encoding:'utf8'}).trim();
if(!['5808469018fb95676af148e7a7662c23665c67a3','db41c18dc69938e7196e221cc7e79982d82e5815'].includes(sha)) throw new Error('Evidence requires the pinned base or head revision');
const env=EnvironmentId.make('synthetic-environment');const thread=ThreadId.make('synthetic-thread');
const configs=[
 ...(['startTurn','interruptTurn'] as const).flatMap(action=>[false,true].map(pending=>({name:`${action}-${pending?'pending-history':'idle'}`,action,pending}))),
 {name:'reverse-command-before-history',action:'startTurn',reverse:true},
 {name:'same-thread-command-serialization',action:'startTurn',serial:'command'},
 {name:'same-thread-history-serialization',action:'startTurn',serial:'history'},
 {name:'other-thread-independent',action:'startTurn',pending:true,otherThread:true},
 {name:'other-environment-independent',action:'startTurn',pending:true,otherEnvironment:true},
 ...(['noop','busy','error'] as const).map(outcome=>({name:`history-${outcome}-releases-queue`,action:'startTurn',serial:'history',outcome})),
 {name:'stop-rpc-error-reconciles',action:'interruptTurn',pending:true,reject:true},
];
for(const config of configs) for(const sample of [1,2,3]) it.live(`${config.name} sample ${sample}`,()=>Effect.gen(function*(){
 const events:any[]=[];const started=performance.now();
 const log=(phase:string,extra={})=>events.push({phase,ms:performance.now()-started,...extra});
 const historyStarted=yield* Deferred.make<void>();const rpcStarted=yield* Deferred.make<void>();const reconciled=yield* Deferred.make<void>();
 let historyCount=0,dispatchCount=0;const dispatchTimes:number[]=[];const invokedTimes:number[]=[];
 const supervisor={target:{environmentId:env},session:yield* SubscriptionRef.make(Option.some({client:{[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]:(command:any)=>Effect.gen(function*(){
   dispatchCount++;dispatchTimes.push(performance.now());log('rpc-dispatch',{type:command.type,threadId:command.threadId,dispatchCount});yield* Deferred.succeed(rpcStarted,undefined);
   yield* Effect.sleep(50);log('rpc-receipt',{dispatchCount});
   if(config.reject) return yield* Effect.fail(new Error('synthetic rejected Stop'));
   return {sequence:dispatchCount};
 })}}))};
 const runtime=Atom.runtime(Layer.mergeAll(
 Layer.succeed(Registry.EnvironmentRegistry,{run:(environmentId:any,effect:any)=>effect.pipe(Effect.provideService(Supervisor.EnvironmentSupervisor,{...supervisor,target:{environmentId}} as any))} as any),
 Layer.succeed(Crypto.Crypto,Crypto.make({randomBytes:size=>new Uint8Array(size),digest:(_algorithm,data)=>Effect.succeed(data)})),
 Layer.succeed(ThreadHistoryController,{
 register:()=>Effect.die('unused'),unregister:()=>Effect.void,
 reconcilePendingWork:(_env:any,id:any)=>Effect.gen(function*(){log('pending-work-reconciled',{threadId:id});yield* Deferred.succeed(reconciled,undefined);}),
 loadEarlier:(_env:any,historyThreadId:any,throughEntryId:any)=>Effect.gen(function*(){
   const call=++historyCount;log('history-start',{call,environmentId:_env,threadId:historyThreadId,throughEntryId:throughEntryId??null});yield* Deferred.succeed(historyStarted,undefined);
   yield* Effect.sleep(250);log('history-release',{call});
   if(config.outcome==='error'&&call===1) return yield* Effect.fail(new Error('synthetic history failure'));
   return {_tag:call===1?(config.outcome??'loaded'):'loaded'} as any;
 })
 } as any)));
 const registry=AtomRegistry.make();yield* Effect.addFinalizer(()=>Effect.sync(()=>registry.dispose()));
 const commands=createThreadEnvironmentAtoms(runtime,()=>Atom.make(null));
 const history=(throughEntryId?:string)=>{log('history-invocation');return commands.loadEarlierHistory.run(registry,{environmentId:env,input:{threadId:thread,...(throughEntryId?{throughEntryId}: {})}});};
 const command=()=>{
  invokedTimes.push(performance.now());log('command-invocation',{action:config.action,environmentId:config.otherEnvironment?'independent-environment':env,threadId:config.otherThread?'independent-thread':thread});
  return commands[config.action as 'startTurn'].run(registry,{environmentId:config.otherEnvironment?EnvironmentId.make('independent-environment'):env,input:{threadId:config.otherThread?ThreadId.make('independent-thread'):thread,runId:RunId.make('synthetic-active-run'),message:{messageId:MessageId.make(`send-${invokedTimes.length}`),role:'user',text:'Synthetic Send',attachments:[]},runtimeMode:'full-access',interactionMode:'default',dispatchMode:'start'} as any});
 };
 const promises:Promise<any>[]=[];
 if(config.reverse){promises.push(command());yield* Deferred.await(rpcStarted);promises.push(history());}
 else if(config.serial==='command'){promises.push(command());yield* Deferred.await(rpcStarted);promises.push(command());}
 else if(config.serial==='history'){promises.push(history());yield* Deferred.await(historyStarted);promises.push(history('entry-old'));promises.push(command());}
 else {if(config.pending){promises.push(history());yield* Deferred.await(historyStarted);}promises.push(command());}
 const results=yield* Effect.promise(()=>Promise.all(promises));
 if(config.action==='interruptTurn') yield* Deferred.await(reconciled);
 log('all-complete',{results:results.map(r=>r._tag)});
 console.log(JSON.stringify({row:'R4',sha,fixture:config.name,sample,inputs:{environmentId:env,threadId:thread,historyDelayMs:250,rpcReplyDelayMs:50,action:config.action,historyState:config.pending?'pending':config.reverse?'reverse':config.serial??'idle',historyOutcome:config.outcome??'loaded',throughEntryId:config.serial==='history'?'entry-old':null},events,dispatchLatencyMs:dispatchTimes.map((v,i)=>v-invokedTimes[i]!),measurement:'command invocation to RPC dispatch; receipt is separate; provider termination not measured',results:results.map(r=>r._tag),historyCalls:historyCount,rpcCalls:dispatchCount,projectionCoverage:'scheduler-only controller stub; real history merge captured separately or listed unverified'}));
}).pipe(Effect.scoped));
