import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import * as net from 'node:net';
import * as crypto from 'node:crypto';
import {execFileSync} from 'node:child_process';
import {it} from 'vitest';
import * as NodeServices from '@effect/platform-node/NodeServices';
import * as Effect from 'effect/Effect';
import * as Layer from 'effect/Layer';
import * as Fiber from 'effect/Fiber';
import * as Exit from 'effect/Exit';
import * as Scope from 'effect/Scope';
import * as Context from 'effect/Context';
import {ChildProcessSpawner, ChildProcess} from 'effect/process';
import * as ServerConfig from '../config.ts';
import * as GitVcsDriver from './GitVcsDriver.ts';

const scratch='/tmp/lead-26601-r1/capture';
const helper=path.join(scratch,'fixture26601.py');
const sha=execFileSync('git',['rev-parse','HEAD'],{encoding:'utf8'}).trim();
const group=process.env.CAPTURE_GROUP??'core';
const root=path.join(scratch,`${new Date().toISOString().replaceAll(':','-')}-${sha.slice(0,10)}-${group}`);
fs.mkdirSync(root,{recursive:true});
const mono=process.hrtime.bigint();
const events:any[]=[];
const waiters=new Set<{predicate:(e:any)=>boolean,resolve:(e:any)=>void}>();
const summaries:any[]=[];
const now=()=>Number(process.hrtime.bigint()-mono)/1e6;
function log(kind:string,data:any={}) {const e={...data,ms:+now().toFixed(3),kind};events.push(e);fs.appendFileSync(path.join(root,'events.jsonl'),JSON.stringify(e)+'\n');console.log(JSON.stringify(e));for(const w of waiters)if(w.predicate(e)){waiters.delete(w);w.resolve(e);}return e;}
function wait(predicate:(e:any)=>boolean){const e=events.find(predicate);if(e)return Promise.resolve(e);return new Promise<any>(resolve=>waiters.add({predicate,resolve}));}
const ready=(label:string)=>Effect.promise(()=>wait(e=>e.kind==='READY'&&e.label===label));
const qu=(s:string)=>"'"+s.replaceAll("'","'\\''")+"'";
const socketPath=path.join(root,'ipc.sock');
const server=net.createServer();
function git(cwd:string,args:string[]){return execFileSync('git',args,{cwd,env:{...process.env,GIT_CONFIG_GLOBAL:'/dev/null',GIT_AUTHOR_DATE:'2026-01-01T00:00:00Z',GIT_COMMITTER_DATE:'2026-01-01T00:00:00Z'},encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim();}
function repo(label:string){const cwd=path.join(root,label);fs.mkdirSync(cwd,{recursive:true});git(cwd,['init','-b','main']);git(cwd,['config','user.name','Capture']);git(cwd,['config','user.email','capture@example.invalid']);fs.writeFileSync(path.join(cwd,'tracked'),'seed\n');git(cwd,['add','.']);git(cwd,['commit','-m','synthetic seed']);return cwd;}
function alive(pid:number){try{const raw=fs.readFileSync(`/proc/${pid}/stat`,'utf8');return raw.slice(raw.lastIndexOf(')')+2).split(' ')[0]!=='Z';}catch{return false;}}
function snapshot(label:string,prefix=label){const pids=[...new Set(events.filter(e=>e.source==='fixture'&&(e.label===prefix||e.label?.startsWith(prefix+'.'))).map(e=>e.pid))];const live=pids.filter(alive);const markers=fs.readdirSync(root).filter(x=>x.endsWith('.marker')&&(x===prefix+'.marker'||x.startsWith(prefix+'.')));return log('SNAPSHOT',{label,pids,live,liveCount:live.length,markers,markerCount:markers.length});}
function summary(row:string,variant:string,data:any){const e={row,variant,...data};summaries.push(e);log('RESULT',e);fs.writeFileSync(path.join(root,'results.json'),JSON.stringify(summaries,null,2));}
const safe=(e:any)=>e&&({_tag:e._tag,operation:e.operation,detail:e.detail,reason:e.reason,exitCode:e.exitCode,stdoutLength:e.stdoutLength,stderrLength:e.stderrLength});
function measure(label:string,effect:any){return Effect.gen(function*(){const start=now();log('REQUEST',{label});const result=yield* Effect.result(effect);const elapsed=now()-start;log('RETURN',{label,elapsedMs:+elapsed.toFixed(3),result:result._tag==='Success'?result.success:safe(result.failure)});return {elapsedMs:+elapsed.toFixed(3),ok:result._tag==='Success',result:result._tag==='Success'?result.success:safe(result.failure)};});}
const rawKill=process.kill.bind(process);
const signals:any[]=[];
function instrumentKill(){process.kill=((pid:number,signal:any)=>{if(signal!==0){const e=log('SIGNAL',{pid,signal});signals.push(e);}return rawKill(pid,signal);}) as typeof process.kill;}
function layer(label:string){const observe=Layer.effect(ChildProcessSpawner.ChildProcessSpawner,Effect.gen(function*(){const native=yield* ChildProcessSpawner.ChildProcessSpawner;return ChildProcessSpawner.make(command=>Effect.gen(function*(){if(!ChildProcess.isStandardCommand(command))return yield* native.spawn(command);const id=events.length;const cwd=command.options.cwd;const args=command.args;const start=now();log('SPAWN_REQUEST',{service:label,id,cwd,args,options:{forceKillAfter:command.options.forceKillAfter,detached:command.options.detached},nativeDelegation:true});yield* Effect.addFinalizer(()=>Effect.sync(()=>log('FINALIZED',{service:label,id,cwd,args,elapsedMs:+(now()-start).toFixed(3)})));const handle=yield* native.spawn(command);log('SPAWNED',{service:label,id,pid:handle.pid,cwd,args});return handle;}));})).pipe(Layer.provide(NodeServices.layer));return GitVcsDriver.layer.pipe(Layer.provide(ServerConfig.layerTest(root,path.join(root,'config-'+label))),Layer.provide(observe),Layer.provideMerge(NodeServices.layer));}
function withDriver(label:string,run:(d:any)=>any){return Effect.scoped(Effect.gen(function*(){const d=yield* GitVcsDriver.GitVcsDriver;return yield* run(d);}).pipe(Effect.provide(layer(label))));}
function command(d:any,cwd:string,label:string,options:any={}){const {mode='hostile',duration=8000,code=0,...input}=options;return d.execute({operation:'capture.'+label,cwd,args:['-c',`alias.capture=!exec python3 ${qu(helper)} ${qu(mode)} ${duration} ${code} ${qu(label)} ${qu(root)} ${qu(socketPath)}`,'capture'],...input});}
function probes(d:any,cwd:string,label:string,count=8){return measure(label,Effect.all(Array.from({length:count},()=>d.execute({operation:'capture.probe',cwd,args:['rev-parse','HEAD']})),{concurrency:'unbounded'})).pipe(Effect.tap((r:any)=>Effect.sync(()=>log('PROBES',{label,count:r.ok?r.result.length:0}))));}
function holders(d:any,cwd:string,label:string,options:any={}){return Effect.gen(function*(){const fibers=[];for(let i=0;i<8;i++)fibers.push(yield* measure(label+'.h'+i,command(d,cwd,label+'.h'+i,options)).pipe(Effect.forkChild));const readies=yield* Effect.all(Array.from({length:8},(_,i)=>ready(label+'.h'+i)),{concurrency:'unbounded'});log('EIGHT_READY',{label,readyCount:readies.length,liveCount:readies.filter(e=>alive(e.pid)).length});return fibers;});}
const joins=(fibers:any[])=>Effect.all(fibers.map(f=>Fiber.join(f)),{concurrency:'unbounded'});
const interrupts=(fibers:any[])=>Effect.all(fibers.map(f=>Fiber.interrupt(f)),{concurrency:'unbounded'});
function core(){return Effect.gen(function*(){
for(const variant of ['A','B'])yield* withDriver('R02'+variant,d=>Effect.gen(function*(){const label='R02'+variant,cwd=repo(label);git(cwd,['branch','feature-x']);const input=(suffix:string)=>({cwd,refName:'main',newRefName:variant==='A'?'feature-x':'feature-y'+suffix,path:path.join(root,label+'-wt'+suffix)});const solo=yield* measure(label+'.solo',d.createWorktree(input('-solo'),{submodules:'none'}));const hs=yield* holders(d,cwd,label,{timeoutMs:1000});const queued=yield* measure(label+'.queued',d.createWorktree(input('-queued'),{submodules:'none'}));const hr=yield* joins(hs);const recovered=yield* probes(d,cwd,label+'.recovered');const snap=snapshot(label);summary('R02',variant,{solo,queued,holders:hr,recovered:recovered.ok,...snap,worktreeExists:fs.existsSync(input('-queued').path),registration:git(cwd,['worktree','list','--porcelain'])});}));
for(const timeout of [undefined,30000,31000,null])yield* withDriver('R03-'+String(timeout),d=>Effect.gen(function*(){const label='R03-'+String(timeout),cwd=repo(label);const hs=yield* holders(d,cwd,label,{...(timeout===undefined?{}:{timeoutMs:timeout})});const start=now();const ninth=yield* measure(label+'.ninth',command(d,cwd,label+'.ninth',{mode:'leaf',duration:0})).pipe(Effect.forkChild);yield* Effect.promise(()=>wait(e=>e.kind==='REQUEST'&&e.label===label+'.ninth'));log('NINTH_REGISTERED',{label});let preInterruptStart=false;if(timeout===31000||timeout===null){yield* ready(label+'.ninth');preInterruptStart=true;log('NINE_ACTIVE',{label,holderLive:snapshot(label,label).liveCount});}else{log('BLOCKED_WAITER',{label,spawnCount:events.filter(e=>e.kind==='SPAWNED'&&e.args?.some((x:string)=>x.includes(label+'.ninth'))).length});}log('INTERRUPT_REQUEST',{label});yield* interrupts(hs);const nr=yield* Fiber.join(ninth);const recovered=yield* probes(d,cwd,label+'.recovered',1);summary('R03',String(timeout),{preInterruptStart,ninth:nr,cleanupMs:+(now()-start).toFixed(3),recovered:recovered.ok,...snapshot(label)});}));
yield* withDriver('R04',d=>Effect.gen(function*(){const label='R04',cwd=repo(label);const holder=yield* measure(label,command(d,cwd,label,{timeoutMs:31000,duration:40000})).pipe(Effect.forkChild);yield* ready(label);const probe=yield* probes(d,cwd,label+'.probe',1);const result=yield* Fiber.join(holder);summary('R04','31000',{result,probe,...snapshot(label)});}));
for(const timeout of [undefined,null])yield* withDriver('R05-'+String(timeout),d=>Effect.gen(function*(){const label='R05-'+String(timeout),cwd=repo(label);const h=yield* command(d,cwd,label,timeout===undefined?{}:{timeoutMs:timeout}).pipe(Effect.forkChild);yield* ready(label);log('INTERRUPT_REQUEST',{label});const start=now();yield* Fiber.interrupt(h);const exit=yield* Fiber.await(h);const elapsedMs=now()-start;const recovered=yield* probes(d,cwd,label+'.recovered');summary('R05',String(timeout),{interruptMs:+elapsedMs.toFixed(3),exitTag:exit._tag,exit:String(exit),recovered:recovered.ok,...snapshot(label)});}));
for(const variant of ['timeout','interrupt'])yield* withDriver('R06-'+variant,d=>Effect.gen(function*(){const label='R06-'+variant,cwd=repo(label);fs.appendFileSync(path.join(cwd,'tracked'),'edited\n');const hook=path.join(cwd,'.git','hooks','pre-commit');fs.writeFileSync(hook,`#!/bin/sh\nexec python3 ${qu(helper)} cooperative 8000 0 ${qu(label)} ${qu(root)} ${qu(socketPath)}\n`,{mode:0o755});const h=yield* measure(label,d.execute({operation:'capture.'+label,cwd,args:['commit','-a','-m','controlled hook'],timeoutMs:variant==='timeout'?1000:null})).pipe(Effect.forkChild);yield* ready(label);const lockPath=path.join(cwd,'.git','index.lock');const lockBefore=fs.existsSync(lockPath);log('LOCK_BEFORE',{label,lockPath,exists:lockBefore});const begin=now();let result;if(variant==='interrupt'){log('INTERRUPT_REQUEST',{label});yield* Fiber.interrupt(h);result=String(yield* Fiber.await(h));}else result=yield* Fiber.join(h);const lockAfter=fs.existsSync(lockPath);log('LOCK_AFTER',{label,lockPath,exists:lockAfter});fs.renameSync(hook,hook+'.disabled');const commit=yield* measure(label+'.subsequent',d.execute({operation:'capture.commit',cwd,args:['commit','-a','-m','after cancellation']}));const locks=fs.readdirSync(path.join(cwd,'.git')).filter(x=>x.endsWith('.lock'));summary('R06',variant,{lockPath,lockBefore,lockAfter,result,cleanupFromReadyMs:+(now()-begin).toFixed(3),subsequentCommit:commit,locks,...snapshot(label)});}));
for(const timeout of [10000,31000,null])for(const variant of ['zero','allowed17','error17'])yield* withDriver('R07-'+timeout+'-'+variant,d=>Effect.gen(function*(){const label='R07-'+timeout+'-'+variant,cwd=repo(label);const result=yield* measure(label,command(d,cwd,label,{mode:'leaf',duration:3000,code:variant==='zero'?0:17,allowNonZeroExit:variant==='allowed17',timeoutMs:timeout}));const fast=yield* measure(label+'.fast',d.execute({operation:'capture.status',cwd,args:['status','--porcelain']}));const recovered=yield* probes(d,cwd,label+'.recovered');summary('R07',timeout+'-'+variant,{result,fast,recovered:recovered.ok,...snapshot(label)});}));
for(const variant of ['zero','allowed17','error17'])yield* withDriver('R08-'+variant,d=>Effect.gen(function*(){const label='R08-'+variant,cwd=repo(label);const result=yield* measure(label,command(d,cwd,label,{mode:'leader',code:variant==='zero'?0:17,allowNonZeroExit:variant==='allowed17',timeoutMs:null}));const immediate=snapshot(label);const r=events.find(e=>e.kind==='READY'&&e.label===label+'.child');yield* Effect.promise(()=>new Promise<void>(resolve=>setTimeout(resolve,Math.max(0,r.ms+8250-now()))));const checkpoint=snapshot(label);summary('R08',variant,{result,immediate,checkpoint});}));
for(const trunc of [false,true])yield* withDriver('R09-'+trunc,d=>Effect.gen(function*(){const label='R09-'+trunc,cwd=repo(label);const result=yield* measure(label,command(d,cwd,label,{mode:'overflow',duration:trunc?3000:8000,maxOutputBytes:128,appendTruncationMarker:trunc,timeoutMs:null}));summary('R09',String(trunc),{result,...snapshot(label)});}));
yield* withDriver('R13',d=>Effect.gen(function*(){const label='R13',cwd=repo(label);const hs=yield* holders(d,cwd,label);const ninth=yield* measure(label+'.cancelled',command(d,cwd,label+'.cancelled',{mode:'leaf',duration:0})).pipe(Effect.forkChild);yield* Effect.promise(()=>wait(e=>e.kind==='REQUEST'&&e.label===label+'.cancelled'));log('NINTH_REGISTERED',{label});const t=now();yield* Fiber.interrupt(ninth);const interrupted=yield* Fiber.await(ninth);log('QUEUED_INTERRUPT_COMPLETE',{label,elapsedMs:now()-t,exit:String(interrupted)});const before=snapshot(label);yield* interrupts(hs);const recovered=yield* probes(d,cwd,label+'.recovered');summary('R13','queued',{interruptMs:+(before.ms-t).toFixed(3),ninthStarts:events.filter(e=>e.kind==='SPAWNED'&&e.args?.some((x:string)=>x.includes(label+'.cancelled'))).length,ninthReady:events.filter(e=>e.kind==='READY'&&e.label===label+'.cancelled').length,ninthMarker:fs.existsSync(path.join(root,label+'.cancelled.marker')),recovered:recovered.ok,...snapshot(label)});}));
for(const variant of ['timeout','interrupt'])yield* withDriver('R14-'+variant,d=>Effect.gen(function*(){const label='R14-'+variant,cwd=repo(label);const wt=path.join(root,label+'-linked');git(cwd,['worktree','add','-b','linked',wt]);yield* d.writeConfigValue({cwd,key:'capture.primed',value:'yes'});yield* d.writeConfigValue({cwd:wt,key:'capture.primed',value:'yes'});const hs=yield* measure(label+'.owner',command(d,cwd,label,{timeoutMs:variant==='timeout'?1000:null,writesSharedConfig:true})).pipe(Effect.forkChild);yield* ready(label);const lockBefore=fs.existsSync(path.join(cwd,'.git','config.lock'));const writer=yield* measure(label+'.writer',d.writeConfigValue({cwd:wt,key:'capture.written',value:'yes'})).pipe(Effect.forkChild);log('SECOND_WRITER_REQUESTED',{label,lockBefore});if(variant==='interrupt'){log('INTERRUPT_REQUEST',{label});yield* Fiber.interrupt(hs);}else yield* Fiber.join(hs);const result=yield* Fiber.join(writer);summary('R14',variant,{writer:result,value:git(cwd,['config','--get','capture.written']),lockBefore,lockAfter:fs.existsSync(path.join(cwd,'.git','config.lock')),...snapshot(label)});}));
});}
function supplement(){return Effect.gen(function*(){
for(const timeout of [undefined,30000,31000,null])yield* withDriver('R03-'+String(timeout),d=>Effect.gen(function*(){const label='R03-'+String(timeout),cwd=repo(label);const hs=yield* holders(d,cwd,label,{...(timeout===undefined?{}:{timeoutMs:timeout})});const start=now();const ninth=yield* measure(label+'.ninth',command(d,cwd,label+'.ninth',{mode:'leaf',duration:0})).pipe(Effect.forkChild);yield* Effect.promise(()=>wait(e=>e.kind==='REQUEST'&&e.label===label+'.ninth'));log('NINTH_REGISTERED',{label});let preInterruptStart=false;if(timeout===31000||timeout===null){yield* ready(label+'.ninth');preInterruptStart=true;log('NINE_ACTIVE',{label,holderLive:snapshot(label,label).liveCount});}else{log('BLOCKED_WAITER',{label,spawnCount:events.filter(e=>e.kind==='SPAWNED'&&e.args?.some((x:string)=>x.includes(label+'.ninth'))).length});}log('INTERRUPT_REQUEST',{label});yield* interrupts(hs);const nr=yield* Fiber.join(ninth);const recovered=yield* probes(d,cwd,label+'.recovered',1);summary('R03',String(timeout),{preInterruptStart,ninth:nr,cleanupMs:+(now()-start).toFixed(3),recovered:recovered.ok,...snapshot(label)});}));
yield* withDriver('R13',d=>Effect.gen(function*(){const label='R13',cwd=repo(label);const hs=yield* holders(d,cwd,label);const ninth=yield* measure(label+'.cancelled',command(d,cwd,label+'.cancelled',{mode:'leaf',duration:0})).pipe(Effect.forkChild);yield* Effect.promise(()=>wait(e=>e.kind==='REQUEST'&&e.label===label+'.cancelled'));log('NINTH_REGISTERED',{label});const t=now();yield* Fiber.interrupt(ninth);const interrupted=yield* Fiber.await(ninth);log('QUEUED_INTERRUPT_COMPLETE',{label,elapsedMs:now()-t,exit:String(interrupted)});const before=snapshot(label);yield* interrupts(hs);const recovered=yield* probes(d,cwd,label+'.recovered');summary('R13','queued',{interruptMs:+(before.ms-t).toFixed(3),ninthStarts:events.filter(e=>e.kind==='SPAWNED'&&e.args?.some((x:string)=>x.includes(label+'.cancelled'))).length,ninthReady:events.filter(e=>e.kind==='READY'&&e.label===label+'.cancelled').length,ninthMarker:fs.existsSync(path.join(root,label+'.cancelled.marker')),recovered:recovered.ok,...snapshot(label)});}));
for(const variant of ['timeout','interrupt'])yield* withDriver('R14-'+variant,d=>Effect.gen(function*(){const label='R14-'+variant,cwd=repo(label);const wt=path.join(root,label+'-linked');git(cwd,['worktree','add','-b','linked',wt]);yield* d.writeConfigValue({cwd,key:'capture.primed',value:'yes'});yield* d.writeConfigValue({cwd:wt,key:'capture.primed',value:'yes'});const hs=yield* measure(label+'.owner',command(d,cwd,label,{timeoutMs:variant==='timeout'?1000:null,writesSharedConfig:true})).pipe(Effect.forkChild);yield* ready(label);const lockBefore=fs.existsSync(path.join(cwd,'.git','config.lock'));const writer=yield* measure(label+'.writer',d.writeConfigValue({cwd:wt,key:'capture.written',value:'yes'})).pipe(Effect.forkChild);log('SECOND_WRITER_REQUESTED',{label,lockBefore});if(variant==='interrupt'){log('INTERRUPT_REQUEST',{label});yield* Fiber.interrupt(hs);}else yield* Fiber.join(hs);const result=yield* Fiber.join(writer);summary('R14',variant,{writer:result,value:git(cwd,['config','--get','capture.written']),lockBefore,lockAfter:fs.existsSync(path.join(cwd,'.git','config.lock')),...snapshot(label)});}));
});}
function transportRepo(label:string,duration:number){const cwd=repo(label),origin=path.join(root,label+'-origin.git');git(cwd,['clone','--bare',cwd,origin]);git(cwd,['remote','add','origin',origin]);git(cwd,['fetch','origin']);git(cwd,['branch','--set-upstream-to=origin/main','main']);const upload=`python3 ${qu(helper)} transport ${duration} 0 ${qu(label)} ${qu(root)} ${qu(socketPath)}`;git(cwd,['config','remote.origin.uploadpack',upload]);git(cwd,['config','capture.origin',origin]);return {cwd,origin};}
function background11(){return withDriver('R11',d=>Effect.gen(function*(){const label='R11',t=transportRepo(label,310000);process.env.FIXTURE_ORIGIN=t.origin;const call=yield* measure(label+'.caller',d.statusDetailsRemote(t.cwd,{refreshUpstream:true})).pipe(Effect.forkChild);yield* ready(label);const caller=yield* Fiber.join(call);const callerSnapshot=snapshot(label);log('WAIT_BACKGROUND_SAFETY',{label,caller});yield* Effect.promise(()=>wait(e=>e.kind==='FINALIZED'&&e.cwd===t.cwd&&e.args?.includes('fetch')));const final=snapshot(label);const cooldownStart=events.filter(e=>e.kind==='SPAWNED'&&e.cwd===t.cwd&&e.args?.includes('fetch')).length;const cooldown=yield* measure(label+'.cooldown',d.statusDetailsRemote(t.cwd,{refreshUpstream:true}));const cooldownEnd=events.filter(e=>e.kind==='SPAWNED'&&e.cwd===t.cwd&&e.args?.includes('fetch')).length;const next=transportRepo('R11-next',0);process.env.FIXTURE_ORIGIN=next.origin;const probe=yield* measure(label+'.next',d.statusDetailsRemote(next.cwd,{refreshUpstream:true}));summary('R11','safety',{caller,callerSnapshot,final,cooldown,cooldownFetchSpawns:cooldownEnd-cooldownStart,next:probe});}));}
function backgroundOther(){return Effect.gen(function*(){yield* withDriver('R10',d=>Effect.gen(function*(){const label='R10',t=transportRepo(label,8000);process.env.FIXTURE_ORIGIN=t.origin;const a=yield* measure(label+'.caller1',d.statusDetailsRemote(t.cwd,{refreshUpstream:true})).pipe(Effect.forkChild);yield* ready(label);const b=yield* measure(label+'.caller2',d.statusDetailsRemote(t.cwd,{refreshUpstream:true})).pipe(Effect.forkChild);const callers=yield* joins([a,b]);const callerSnapshot=snapshot(label);yield* Effect.promise(()=>wait(e=>e.kind==='FINALIZED'&&e.cwd===t.cwd&&e.args?.includes('fetch')));summary('R10','joined',{callers,callerSnapshot,fetchSpawns:events.filter(e=>e.kind==='SPAWNED'&&e.cwd===t.cwd&&e.args?.includes('fetch')).length,...snapshot(label)});}));
const scope=yield* Scope.make();const context=yield* Layer.buildWithScope(layer('R12'),scope);const d=Context.get(context,GitVcsDriver.GitVcsDriver);const tuples=Array.from({length:5},(_,i)=>transportRepo('R12.'+i,8000));const calls=[];for(let i=0;i<5;i++){process.env.FIXTURE_ORIGIN=tuples[i].origin;calls.push(yield* measure('R12.caller'+i,d.statusDetailsRemote(tuples[i].cwd,{refreshUpstream:true})).pipe(Effect.forkChild));if(i<4)yield* ready('R12.'+i);}log('FOUR_FETCHES_READY',{label:'R12',count:4,fifthReady:events.filter(e=>e.kind==='READY'&&e.label==='R12.4').length});yield* probes(d,tuples[0].cwd,'R12.independent',1);log('CALLER_INTERRUPT_REQUEST',{label:'R12.caller0'});yield* Fiber.interrupt(calls[0]);const afterCaller=snapshot('R12');const t=now();log('SERVICE_CLOSE_REQUEST',{label:'R12'});yield* Scope.close(scope,Exit.void);const closeMs=now()-t;yield* interrupts(calls.slice(1));summary('R12','scope',{closeMs:+closeMs.toFixed(3),afterCaller,fifthReady:events.filter(e=>e.kind==='READY'&&e.label==='R12.4').length,...snapshot('R12')});});}

it('captures real GitVcsDriver runtime',async()=>{
await new Promise<void>(resolve=>server.listen(socketPath,resolve));
server.on('connection',sock=>{let buf='';sock.on('data',data=>{buf+=data.toString();let ix;while((ix=buf.indexOf('\n'))>=0){const e=JSON.parse(buf.slice(0,ix));buf=buf.slice(ix+1);const {kind,...rest}=e;log(kind,{...rest,source:'fixture'});}});});
const driverHash=crypto.createHash('sha256').update(fs.readFileSync(import.meta.filename)).digest('hex');
const helperHash=crypto.createHash('sha256').update(fs.readFileSync(helper)).digest('hex');
const env={sha,wallOrigin:new Date().toISOString(),os:os.type(),kernel:os.release(),node:process.version,git:git(process.cwd(),['--version']),cpus:os.availableParallelism(),platformNodeShared:JSON.parse(fs.readFileSync(path.join(fs.realpathSync('node_modules/@effect/platform-node'),'..','platform-node-shared','package.json'),'utf8')).version,driverHash,helperHash,group,root,inputProtocol:'native GitVcsDriver.layer + NodeServices.layer + ServerConfig.layerTest; passive native spawn/signal observer; real git aliases/hooks/local upload-pack; READY IPC; no fake spawner/clock/platform'};
log('ENVIRONMENT',env);fs.writeFileSync(path.join(root,'environment.json'),JSON.stringify(env,null,2));instrumentKill();
try{await Effect.runPromise(Effect.scoped(group==='R11'?background11():group==='background'?backgroundOther():group==='supplement'?supplement():core()));}finally{process.kill=rawKill as typeof process.kill;server.close();log('RUN_COMPLETE',{rows:summaries.length});}
});
