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, assert } from '@effect/vitest';
import { ThreadId } from '@t3tools/contracts';
import * as Effect from 'effect/Effect';
import * as Layer from 'effect/Layer';
import * as Stream from 'effect/Stream';
import * as SqlClient from 'effect/sql/SqlClient';
import * as Store from './persistence/OrchestrationEventStore.ts';
import * as Sqlite from './persistence/Sqlite.ts';
import * as Management from './orchestration-v2/ThreadManagementService.ts';
import { projectDomainEventForWire } from './orchestration-v2/WireProjection.ts';
import { subscribeOrchestrationV2Thread } from './ws.ts';
import { v2Projection } from '../../../packages/client-runtime/src/state/orchestrationV2TestFixtures.ts';
import { applyOrchestrationV2ProjectionEvent } from '../../../packages/client-runtime/src/state/orchestrationV2Projection.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 now = '2026-10-27T00:00:00.000Z';
const threadId = ThreadId.make('thread-v2');
const message = (text: string, extra = {}) => ({ type:'message.updated', payload:{ id:'message', threadId, runId:null,nodeId:null,role:'assistant',text,attachments:[],streaming:true,createdBy:'agent',creationSource:'web',createdAt:now,updatedAt:now,...extra } });
const item = (type: string, text: string, extra = {}) => ({type:'turn-item.updated',payload:{id:'item',type,threadId,runId:null,nodeId:null,providerThreadId:null,providerTurnId:null,nativeItemRef:null,parentItemId:null,ordinal:0,status:'running',title:'Synthetic',startedAt:now,completedAt:null,updatedAt:now,...(type==='assistant_message'||type==='reasoning'?{messageId:'message',text,streaming:true}:type==='file_change'?{fileName:'synthetic.ts',newStr:text}:type==='dynamic_tool'?{toolName:'synthetic',input:text,output:text}:type==='file_search'?{pattern:text}:type==='web_search'?{patterns:[text]}:{input:text,output:text}),...extra}});
const boundary = {type:'provider-session.detached', payload:{providerSessionId:'synthetic',detachedAt:now}};
const growing = Array.from({length:64},(_,i)=>message('x'.repeat(256*(i+1))));
const cases = [
 {name:'64-streaming',rows:growing},
 {name:'64-streaming-completed',rows:[...growing,message('x'.repeat(16384)+'!',{streaming:false})]},
 {name:'paired-message-item',rows:Array.from({length:12},(_,i)=>[message('x'.repeat(64*(i+1))),item('assistant_message','x'.repeat(64*(i+1)))]).flat()},
 ...['assistant_message','reasoning','command_execution','file_change','file_search','web_search','dynamic_tool'].map(type=>({name:`item-${type}`,rows:[item(type,'first'),item(type,'latest')]})),
 {name:'completed-nonassistant-boundaries',rows:[message('a'),message('b'),message('complete',{streaming:false}),message('user',{role:'user'}),message('user2',{role:'user'}),boundary,message('next')]},
 {name:'identity-run-interleave',rows:[message('a'),item('reasoning','a'),message('b'),item('reasoning','b'),message('c',{id:'different'}),message('d'),{...message('run'),runId:'another-run'},message('end')]},
 {name:'item-status-boundary',rows:[item('reasoning','a'),item('reasoning','b',{streaming:false}),item('reasoning','c',{status:'completed',streaming:false,completedAt:now}),item('reasoning','d')]},
 {name:'unknown-highwater',rows:[message('a'),{type:'future.event',payload:{}},message('b'),{type:'future.event',payload:{}}]},
 {name:'128-raw',rows:Array.from({length:128},()=>message('small'))},
 {name:'129-raw',rows:Array.from({length:129},()=>message('small'))},
 {name:'raw-over-1MiB',rows:[message('x'.repeat(1048576))]},
 {name:'cursor-absent',rows:[message('a')],cursor:'absent'},
 {name:'cursor-equal',rows:[message('a')],cursor:'equal'},
 {name:'cursor-ahead',rows:[message('a')],cursor:'ahead'},
 ...[1048575,1048576,1048577].map(bytes=>{const row=message('');row.payload.text='x'.repeat(bytes-Buffer.byteLength(JSON.stringify(row.payload)));return {name:`raw-exact-${bytes}`,rows:[row]};}),
 {name:'created-shell-exists',rows:[{type:'thread.created',payload:v2Projection.thread},message('a')],shell:true},
 {name:'created-shell-missing',rows:[{type:'thread.created',payload:v2Projection.thread},message('a')],shell:false},
 {name:'bounded-fallback',rows:Array.from({length:129},()=>message('small')),flags:{acceptBoundedSnapshot:true}},
 {name:'full-dedupe-fallback',rows:Array.from({length:129},()=>message('small')),flags:{acceptDedupedBodies:true}},
 {name:'bounded-compact-dedupe-fallback',rows:Array.from({length:129},()=>message('small')),flags:{acceptBoundedSnapshot:true,acceptCompactTurnItems:true,acceptDedupedBodies:true,acceptCompactIds:true}},
 {name:'other-item-type-boundary',rows:[message('a'),item('proposed_plan','plan',{planId:'plan',markdown:'synthetic plan',streaming:true}),message('b')]},
 {name:'item-identity-run-boundaries',rows:[item('command_execution','a',{id:'item-a'}),item('command_execution','b',{id:'item-b'}),item('command_execution','a2',{id:'item-a'}),{...item('command_execution','run'),runId:'different-run'},item('command_execution','original-run')]},
 {name:'marker-off',rows:[message('a'),message('b')],marker:false},
];
for (const fixture of cases) for (const sample of [1,2,3]) it.live(`${fixture.name} sample ${sample}`,()=>Effect.gen(function*(){
 const sql=yield* SqlClient.SqlClient; const store=yield* Store.OrchestrationEventStore;
 const insert=(row: any, version: number)=>sql<{sequence:number}>`INSERT INTO orchestration_events (event_id,aggregate_kind,stream_id,stream_version,event_type,occurred_at,actor_kind,payload_json,metadata_json,application_event_version) VALUES (${`event-${version}`},'thread',${threadId},${version},${row.type},${now},'server',${JSON.stringify(row.payload)},${JSON.stringify(row.runId?{runId:row.runId}:{})},2) RETURNING sequence`;
 for(const [i,row] of fixture.rows.entries()) yield* insert(row,i);
 const highWater=yield* store.latestAgentSequence(threadId);
 const candidateStored=yield* store.readAgentEvents({threadId,afterSequence:0,throughSequence:highWater,skipUnknownEventTypes:true}).pipe(Stream.runCollect);
 const uncoalescedProjectedItemJsonBytes=candidateStored.reduce((sum,stored)=>sum+Buffer.byteLength(JSON.stringify({kind:'event',sequence:stored.sequence,event:projectDomainEventForWire(stored.event)})),0);
 let liveCursor=-1; let snapshotMode:string|null=null;
 const afterSequence=fixture.cursor==='absent'?undefined:fixture.cursor==='equal'?highWater:fixture.cursor==='ahead'?highWater+5:0;
 const input={threadId,...(afterSequence===undefined?{}:{afterSequence}),requestCompletionMarker:fixture.marker!==false,...fixture.flags};
 const timeline=Array.from({length:100},(_,i)=>({...item('assistant_message',`synthetic-history-${i}`).payload,id:`history-item-${i}`,messageId:`history-message-${i}`,ordinal:i,streaming:false,status:'completed',completedAt:now}));
 const snapshotProjection={...v2Projection,turnItems:timeline,visibleTurnItems:timeline.map((item,i)=>({position:i,visibility:'local',sourceThreadId:threadId,sourceItemId:item.id,item}))};
 const snapshot=()=>{snapshotMode='full';return Effect.succeed({snapshotSequence:highWater,projection:snapshotProjection})};
 const boundedSnapshot=()=>{snapshotMode='bounded';return Effect.succeed({snapshotSequence:highWater,projection:snapshotProjection})};
 const started=performance.now();
 const items=yield* subscribeOrchestrationV2Thread(input).pipe(Effect.flatMap(Stream.runCollect),Effect.provideService(Management.ThreadManagementService,{
 ensureLegacyTranscript:()=>Effect.void,getThreadShell:()=>Effect.succeed(fixture.shell?{}:null),getThreadSnapshot:snapshot,getThreadSnapshotWindow:boundedSnapshot,
 streamStoredEventsFrom:({afterSequence}: {afterSequence:number})=>{liveCursor=afterSequence;return Stream.unwrap(insert(message('LIVE',{streaming:false,id:'live'}),fixture.rows.length).pipe(Effect.map(()=>store.readAgentEvents({threadId,afterSequence}))));}
 } as any));
 const events=items.filter((v:any)=>v.kind==='event');
 const replay=events.filter((v:any)=>v.sequence<=highWater);
 const raw=fixture.rows.reduce((sum,row)=>sum+Buffer.byteLength(JSON.stringify(row.payload)),0);
 const summary=(v:any)=>v.kind==='event'?{kind:v.kind,sequence:v.sequence,type:v.event.type,id:v.event.payload.id,runId:v.event.runId??null,textLength:(v.event.payload.text??v.event.payload.output??'').length,textPreview:(v.event.payload.text??v.event.payload.output??'').slice(0,24),streaming:v.event.payload.streaming,status:v.event.payload.status}:v.kind==='snapshot'?{kind:v.kind,snapshotSequence:v.snapshotSequence,historyCursor:v.historyCursor??null,hasMoreHistory:v.hasMoreHistory??null,latestLocalTurnOrdinal:v.latestLocalTurnOrdinal??null,turnItemsOmitLocalVisible:v.turnItemsOmitLocalVisible??null,idTable:v.idTable??null,turnItemCount:v.projection.turnItems.length,visibleCount:v.projection.visibleTurnItems.length}:v;
 const survivorCursors:any[]=[];
 let equivalence:any='not applicable (snapshot or no replay)';
 if(afterSequence===0&&snapshotMode===null){
 const rawEvents=yield* store.readAgentEvents({threadId,afterSequence:0,throughSequence:highWater,skipUnknownEventTypes:true}).pipe(Stream.runCollect);
 const apply=(es:any[])=>es.reduce((p,e)=>applyOrchestrationV2ProjectionEvent(p,e.event)??p,v2Projection);
 // Body text, item order/status and all projection fields must agree.
 const projected=rawEvents.map((stored:any)=>({...stored,event:projectDomainEventForWire(stored.event)}));
 assert.deepEqual(apply(replay),apply(projected));
 if(sample===1){
 const allStored=yield* store.readAgentEvents({threadId,afterSequence:0,skipUnknownEventTypes:true}).pipe(Stream.runCollect);
 const expected=apply(allStored.map((stored:any)=>({...stored,event:projectDomainEventForWire(stored.event)})));
 for(const [index,survivor] of replay.entries()){
  const resumed=yield* subscribeOrchestrationV2Thread({threadId,afterSequence:survivor.sequence,requestCompletionMarker:true}).pipe(Effect.flatMap(Stream.runCollect),Effect.provideService(Management.ThreadManagementService,{ensureLegacyTranscript:()=>Effect.void,streamStoredEventsFrom:()=>Stream.empty} as any));
  const received=[...replay.slice(0,index+1),...resumed.filter((v:any)=>v.kind==='event')];assert.deepEqual(apply(received),expected);
  survivorCursors.push({cursor:survivor.sequence,resumedSequences:resumed.filter((v:any)=>v.kind==='event').map((v:any)=>v.sequence),finalProjectionEqual:true});
 }
 }
 equivalence={finalProjection:true,latestMessages:apply(replay).messages.map((m:any)=>({id:m.id,textLength:m.text.length,streaming:m.streaming}))};
 }
 console.log(JSON.stringify({row:'R1',sha,fixture:fixture.name,sample,inputs:input,rawCount:fixture.rows.length,rawPayloadBytes:raw,uncoalescedProjectedItemJsonBytes,elapsedMs:performance.now()-started,emittedItems:items.map(summary),replayEventCount:replay.length,replayItemJsonBytes:replay.reduce((s:number,e:any)=>s+Buffer.byteLength(JSON.stringify(e)),0),totalItemJsonBytes:items.reduce((s:number,e:any)=>s+Buffer.byteLength(JSON.stringify(e)),0),bytesDefinition:'sum UTF-8 JSON.stringify stream items; excludes RPC envelopes/chunks',snapshotMode,liveSourceCursor:liveCursor,highWater,equivalence,survivorCursors}));
}).pipe(Effect.scoped,Effect.provide(Store.layer.pipe(Layer.provideMerge(Sqlite.layerMemory)))));
