// Evidence-only runtime driver. Copied temporarily to apps/server, then removed.
import * as NodeServices from '@effect/platform-node/NodeServices';
import * as HostProcess from '@t3tools/shared/HostProcess';
import * as Effect from 'effect/Effect';
import * as Deferred from 'effect/Deferred';
import * as Fiber from 'effect/Fiber';
import * as Exit from 'effect/Exit';
import * as Cause from 'effect/Cause';
import * as Duration from 'effect/Duration';
import * as FileSystem from 'effect/FileSystem';
import * as ConfigProvider from 'effect/ConfigProvider';
import * as Layer from 'effect/Layer';
import * as Terminal from 'effect/Terminal';
import * as Queue from 'effect/Queue';
import * as Option from 'effect/Option';
import { HttpClient } from 'effect/http';
import * as PR from './src/processRunner.ts';
import * as BS from './src/cloud/bootService.ts';
import { SERVICE_RESTART_PENDING_FILE, SERVICE_ENV_FILE, SERVICE_LAUNCHER_PROTOCOL } from './src/cloud/serviceProtocol.ts';
import { offerServiceDuringOnboarding } from './src/cli/service.ts';
import * as nfs from 'node:fs';
import * as np from 'node:path';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';

const [bundle, side, runRoot, legacyRoot] = process.argv.slice(2);
const revision = process.env.CAPTURE_REVISION!;
const release = bundle !== 'O3';
const fixtureRoot='/tmp/lead-25999-r1/evidence-capture-2/fixtures';
const isHead = revision === '7a90b56c54a924d63d91c40e3eecd96d048c1da4';
const A=release?'0.1.1-preview.20261018.3327':'0.1.3', B=release?'0.1.3-preview.20261026.3702':'0.1.4', C=release?A:'0.1.5';
nfs.mkdirSync(runRoot,{recursive:true});
function emit(kind:string, data:unknown) { console.log(JSON.stringify({kind, data}, null, 2)); }
function hash(bytes:Buffer|string) { return createHash('sha256').update(bytes).digest('hex'); }
function file(p:string) { try {return nfs.readFileSync(p,'utf8')} catch(e) {return {absentOrError:(e as NodeJS.ErrnoException).code}} }
function fileHash(p:string|number) {
 const fd=typeof p==='number'?p:nfs.openSync(p,'r');const digest=createHash('sha256');const bytes=Buffer.alloc(1024*1024);let pos=0,n;
 try {while((n=nfs.readSync(fd,bytes,0,bytes.length,pos))>0){digest.update(bytes.subarray(0,n));pos+=n;}return digest.digest('hex');}finally{if(typeof p!=='number')nfs.closeSync(fd);}
}
let manifestNumber=0;
function fullTree(root:string) {
 const result:any[]=[];
 function walk(p:string,relative:string) {
  let st;try{st=nfs.lstatSync(p)}catch{return;}
  const type=st.isDirectory()?'directory':st.isSymbolicLink()?'symlink':'file';
  result.push({path:relative,type,mode:(st.mode&0o7777).toString(8),...(type==='file'?{bytes:st.size,sha256:fileHash(p),...(relative.endsWith('.install-complete')||relative.endsWith('.install-complete.saved')?{sentinel:file(p)}:{})}:{}),...(type==='symlink'?{target:nfs.readlinkSync(p)}:{})});
  if(type==='directory')for(const name of nfs.readdirSync(p).sort())walk(np.join(p,name),np.join(relative,name));
 }
 walk(root,'.');return result;
}
function tree(root:string) {
 const entries=fullTree(root);
 if(!release)return entries;
 const normalized=JSON.stringify(entries).replaceAll(legacyRoot,'<LEGACY_ROOT>').replaceAll(runRoot,'<RUN_ROOT>');
 const name=`manifest-${String(++manifestNumber).padStart(3,'0')}.json`;
 nfs.writeFileSync(np.join(runRoot,'..',bundle+'-'+side+'-'+name),normalized+'\n');
 return {manifest:bundle+'-'+side+'-'+name,manifestSHA256:hash(normalized),entryCount:entries.length,fileCount:entries.filter(e=>e.type==='file').length,totalFileBytes:entries.reduce((n,e)=>n+(e.bytes??0),0),symlinks:entries.filter(e=>e.type==='symlink'),entries:entries.filter(e=>e.path.split(np.sep).length<=2||['t3','.install-complete','.install-complete.saved','service-state.json','service-restart-pending'].includes(np.basename(e.path)))};
}

function assert(ok:unknown, message:string) {emit('assert',{message,pass:!!ok});if(!ok) throw new Error(message);}
function xmlDecode(s:string) {return s.replaceAll('&quot;','"').replaceAll('&apos;',"'").replaceAll('&lt;','<').replaceAll('&gt;','>').replaceAll('&amp;','&');}
function programArgs(unit:string) {const a=/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(unit);return a?[...a[1].matchAll(/<string>(.*?)<\/string>/g)].map(x=>xmlDecode(x[1])):unit.split('\n').filter(x=>x.startsWith('ExecStart='));}
function serialExit(ex:any) {return Exit.isSuccess(ex)?{exit:'Success',value:ex.value}:{exit:'Failure',cause:Cause.pretty(ex.cause)};}
function seed(base:string, version:string) {
 const dir=np.join(base,'runtime','versions',version);
 if(release){nfs.mkdirSync(np.dirname(dir),{recursive:true});execFileSync('cp',['-a','--reflink=auto',np.join(fixtureRoot,version),dir]);emit('fixture.seed',{version,provenance:'native Linux release; all assets; scratch copy',source:np.join(fixtureRoot,version),destination:dir,command:['cp','-a','--reflink=auto'],sourceSentinel:version===A?'absent in live source; scratch sentinel reconstructed from real version':'copied unchanged',sha256:fileHash(np.join(dir,'t3'))});return;}
 nfs.mkdirSync(np.join(dir,'assets','nested'),{recursive:true,mode:0o755});
 nfs.writeFileSync(np.join(dir,'t3'),`#!/bin/sh\n# Synthetic evidence runtime ${version}; not a release or Mach-O.\nif [ "$1" = "--version" ]; then printf 't3 v${version}\\n'; exit 0; fi\nprintf 'unsupported synthetic invocation\\n' >&2\nexit 64\n`,{mode:0o755});
 nfs.chmodSync(np.join(dir,'t3'),0o755);
 nfs.writeFileSync(np.join(dir,'.install-complete'),version+'\n',{mode:0o644});
 nfs.writeFileSync(np.join(dir,'assets','manifest.json'),JSON.stringify({version,synthetic:true})+'\n',{mode:0o644});
 nfs.writeFileSync(np.join(dir,'assets','nested','data.bin'),Buffer.from(`asset-${version}\0synthetic\n`),{mode:0o640});
 nfs.writeFileSync(np.join(dir,'helper'),'#!/bin/sh\nexit 0\n',{mode:0o750});
 nfs.symlinkSync('assets/manifest.json',np.join(dir,'manifest-link'));
}
const main = Effect.gen(function*(){
 const realFs=yield* FileSystem.FileSystem;
 const realRunner=yield* PR.make();
 function context(row:string, platform:'darwin'|'linux'='darwin', existingRoot?:string) {
  return Effect.gen(function*(){
   const root=existingRoot??np.join(runRoot,row);
   const home=np.join(root,'user home');
   const base=np.join(root,'T3 Data & <capture>');
   nfs.mkdirSync(home,{recursive:true});
   if(!existingRoot || !nfs.existsSync(np.join(base,'runtime','versions',A,'t3'))) for(const v of new Set([A,B,C])) seed(base,v);
   const launcher=np.join(base,'runtime','launcher');
   const state=np.join(base,'runtime','service-state.json');
   const marker=np.join(base,'runtime',SERVICE_RESTART_PENDING_FILE);
   const env=np.join(base,SERVICE_ENV_FILE);
   const control:any={cp:'real',fault:undefined,bootstrapFail:false,readFault:false,copyBarrier:undefined,renameBarrier:undefined,allowLoginctl:process.env.CAPTURE_ALLOW_LOGINCTL==='1'};
   const commands:any[]=[]; const operations:any[]=[];
   const record=(op:string,detail:any)=>{const event={row,op,...detail}; operations.push(event);emit('filesystem',event);};
   const fs={...realFs,
    copy:(from:string,to:string,opts?:any)=>Effect.gen(function*(){
     record('copy.start',{from,to,destinationExists:nfs.existsSync(to),fault:control.fault??null});
     if(control.fault==='copy-fail') {
      yield* realFs.makeDirectory(to,{recursive:true});yield* realFs.writeFileString(np.join(to,'partial'),'incomplete fallback');
      record('injected.copy-failure',{from,to});return yield* realFs.copy(np.join(from,'missing-fixture-asset'),np.join(to,'missing'));
     }
     if(control.copyBarrier) return yield* control.copyBarrier(from,to);
     yield* realFs.copy(from,to,opts);record('copy.complete',{from,to});
    }),
    rename:(from:string,to:string)=>Effect.gen(function*(){
     const old=from===launcher;
     const promotion=to===launcher&&np.basename(from)==='launcher'&&from!==launcher;
     const rollback=to===launcher&&np.basename(from)==='previous';
     record('rename.start',{from,to});
     if((control.fault==='old-rename'&&old)||(control.fault==='promotion'&&promotion)||(control.fault==='double-rename'&&(promotion||rollback))) {
      record('injected.rename-failure',{from,to});const ex=yield* Effect.exit(realFs.rename(from,np.join(to,'missing-parent','failure')));record('rename.error',{from,to,...serialExit(ex)});if(Exit.isFailure(ex))return yield* Effect.failCause(ex.cause);return ex.value;
     }
     yield* realFs.rename(from,to);record('rename.complete',{from,to});if(to===state&&control.overwriteState){yield* realFs.writeFileString(state,control.overwriteState);record('injected.concurrent-state-overwrite',{path:state,contents:control.overwriteState});}
     if(old&&control.renameBarrier) yield* control.renameBarrier(from,to);
    }),
    remove:(p:string,opts?:any)=>Effect.gen(function*(){record('remove',{path:p,options:opts??null});if((control.fault==='staging-remove'&&np.basename(p).startsWith('launcher.next-'))||(control.fault==='entry-remove'&&p===launcher)){record('injected.remove-failure',{path:p});const ex=yield* Effect.exit(realFs.remove(p+'.injected-missing'));record('remove.error',{path:p,...serialExit(ex)});if(Exit.isFailure(ex))return yield* Effect.failCause(ex.cause);return ex.value;}yield* realFs.remove(p,opts);}),
    readDirectory:(p:string)=>Effect.gen(function*(){if(control.fault==='readdir'&&p===np.dirname(launcher)){const ex=yield* Effect.exit(realFs.readDirectory(p+'.injected-missing'));record('readDirectory.error',{path:p,...serialExit(ex)});if(Exit.isFailure(ex))return yield* Effect.failCause(ex.cause);return ex.value;}return yield* realFs.readDirectory(p);}),
    readFileString:(p:string,opts?:any)=>control.readFault&&p===np.join(launcher,'.install-complete')?Effect.gen(function*(){record('injected.sentinel-read-error',{path:p,method:'readFileString redirected to nonexistent literal sibling'});return yield* realFs.readFileString(p+'.unreadable-fault');}):realFs.readFileString(p,opts),
   };
   const runner=PR.ProcessRunner.of({run:(input:any)=>Effect.gen(function*(){
    const intercepted=['launchctl','systemctl','systemd-run'].includes(input.command)||(input.command==='loginctl'&&control.allowLoginctl);
    const mode=input.command==='cp'&&control.cp!=='real'?'harness':intercepted?'intercepted':'real';
    const invocation:any={row,mode,command:input.command,args:input.args,timeoutMs:input.timeout===undefined?null:Duration.toMillis(Duration.fromInputUnsafe(input.timeout))};
    commands.push(invocation);emit('command.start',invocation);
    let output:any;
    if(input.command==='cp'&&control.cp!=='real') {
     const [source,dest]=input.args.slice(-2);
     if(control.cp==='success') {yield* realFs.copy(source,dest);emit('harness.clone-success',{source,dest,completeCopy:true,notAPFS:true});output={code:0,stdout:'',stderr:''};}
     else {
      yield* realFs.makeDirectory(dest,{recursive:true});yield* realFs.writeFileString(np.join(dest,'partial'),'partial clone artifact');yield* realFs.writeFileString(np.join(dest,'t3'),'partial executable');
      emit('harness.partial-clone',{source,dest,fault:control.cp});
      if(control.cp==='runner-error') {const error=new PR.ProcessSpawnError({command:input.command,argumentCount:input.args.length,cause:new Error('injected runner-level cp failure')});emit('command.error',{...invocation,error:String(error)});return yield* Effect.fail(error);}
      output={code:1,stdout:'',stderr:'injected nonzero cp after partial copy'};
     }
    } else if(intercepted) {
     const fail=input.command==='launchctl'&&input.args[0]==='bootstrap'&&control.bootstrapFail;
     output={code:fail?1:0,stdout:input.command==='loginctl'?'yes\n':input.args.includes('is-enabled')?'enabled\n':'',stderr:fail?'injected launchctl bootstrap failure':''};
    } else {
     const ex=yield* Effect.exit(realRunner.run(input));
     if(Exit.isFailure(ex)){emit('command.error',{...invocation,...serialExit(ex)});return yield* Effect.failCause(ex.cause);}
     output=ex.value;
    }
    output={timedOut:false,stdoutTruncated:false,stderrTruncated:false,stdoutInvalidUtf8:false,stderrInvalidUtf8:false,...output};
    invocation.result=output;emit('command.result',{...invocation});return output;
   })});
   function service(version=A,inside=false) {return BS.make({baseDir:base,logsDir:np.join(base,'userdata','logs'),cliVersion:version,host:{execPath:'/usr/bin/t3'}}).pipe(
    Effect.provideService(FileSystem.FileSystem,fs),Effect.provideService(PR.ProcessRunner,runner),
    Effect.provide(Layer.mergeAll(Layer.succeed(HostProcess.Platform,control.platform??platform),Layer.succeed(HostProcess.Architecture,'x64'),Layer.succeed(HostProcess.UserId,control.missingUID?undefined:platform==='linux'?1000:501),Layer.succeed(HostProcess.ExecutablePath,'/usr/bin/t3'),Layer.succeed(HttpClient.HttpClient,HttpClient.make(()=>Effect.die('unexpected network access forbidden'))),ConfigProvider.layer(ConfigProvider.fromEnv({env:{HOME:control.emptyHome?'':home,PATH:control.path??'/usr/bin:/bin',...(inside?{T3_BOOT_SERVICE_UNIT:'t3code.service'}:{})}})))));}
   function checkpoint(label:string,s:any, extra:any={}) {return Effect.gen(function*(){
    const statusExit=yield* Effect.exit(s.status);
    const status:any=Exit.isSuccess(statusExit)?statusExit.value:serialExit(statusExit);
    const unit=typeof status.unitPath==='string'&&nfs.existsSync(status.unitPath)?nfs.readFileSync(status.unitPath,'utf8'):null;
    emit('checkpoint',{sourceRevision:revision,row,label,fixtureID:row,provenance:release?{kind:'native Linux release',versions:{A,B},sentinelA:'reconstructed in scratch from real --version; missing in live source',sentinelB:'copied unchanged',platform,managers:'intercepted',validation:'real ProcessRunner t3 --version',fault:control.readFault?'explicit sentinel read error':null}:{kind:'synthetic/harness',versions:{A,B,C},platform},commands:[...commands],operations:[...operations],unit,programArguments:unit?programArgs(unit):null,parsedProgram:unit?BS.bootServiceProgramOf(unit):null,parsedHome:unit?BS.bootServiceBaseDirOf(unit):null,launcherAndSiblings:tree(np.join(base,'runtime')),state:file(state),restartMarker:file(marker),serviceEnv:file(env),status,...extra});
   });}
   function operation(label:string,eff:any) {return Effect.gen(function*(){emit('operation',{sourceRevision:revision,row,label,provenance:release?'native Linux release':'synthetic/harness'});const ex=yield* Effect.exit(eff);emit('operation.result',{row,label,...serialExit(ex)});return ex;});}
   function install(s:any,label:string,options?:any) {return operation(label+': install '+JSON.stringify(options??{}),s.install(options));}
   function clear(){commands.length=0;operations.length=0;}
   function consistent(version:string) {
    const dir=isHead&&platform==='darwin'?launcher:np.join(base,'runtime','versions',version);
    const source=np.join(base,'runtime','versions',version);
    assert(nfs.existsSync(np.join(dir,'t3')),'published executable exists');
    for(const p of release?['t3','client/index.html','.install-complete']:['t3','assets/manifest.json','assets/nested/data.bin','helper','.install-complete']) assert(hash(nfs.readFileSync(np.join(dir,p)))===hash(nfs.readFileSync(np.join(source,p))),'complete copied asset '+p+' matches '+version);
    assert((nfs.statSync(np.join(dir,'t3')).mode&0o111)===0o111,'published executable mode has all execute bits');
    if(release){const a=fullTree(source),b=fullTree(dir);assert(JSON.stringify(a)===JSON.stringify(b),'complete release manifest, all asset hashes, file types, modes and symlink targets match source');emit('release.copy-verification',{version,source,copy:dir,sourceManifestSHA256:hash(JSON.stringify(a)),copiedManifestSHA256:hash(JSON.stringify(b)),sourceT3SHA256:fileHash(np.join(source,'t3')),copiedT3SHA256:fileHash(np.join(dir,'t3')),otherAsset:'client/index.html',sourceAssetSHA256:fileHash(np.join(source,'client/index.html')),copiedAssetSHA256:fileHash(np.join(dir,'client/index.html')),symlinks:a.filter(x=>x.type==='symlink')});}
    assert(nfs.readdirSync(np.join(base,'runtime')).filter(x=>x.startsWith('launcher.next-')).length===0,'no launcher.next staging leftovers');
    if(isHead&&platform==='darwin')assert(!nfs.existsSync(np.join(dir,'partial')),'no partial clone artifact retained');
   }
   return {row,root,home,base,launcher,state,marker,env,control,fs,commands,operations,service,checkpoint,operation,install,clear,consistent,record};
  });
 }
 function healthy(row:string, platform:'darwin'|'linux'='darwin') {return Effect.gen(function*(){const c=yield* context(row,platform);const s=yield* c.service();const ex=yield* c.install(s,'precondition healthy A',{start:true});assert(Exit.isSuccess(ex),'healthy A installed');yield* c.checkpoint('precondition: healthy installed A',s);c.clear();return {...c,s};});}
 emit('header',{bundle,side,sourceRevision:revision,runRoot,driverSHA256:hash(nfs.readFileSync(import.meta.filename)),versions:{A,B,C},runtime:release?'complete native Linux release A/B (ELF), all original assets; A sentinel reconstructed only in scratch; not Mach-O':'synthetic POSIX shell A/B/C; labelled harness',manager:'launchctl/systemctl/systemd-run intercepted; cp and t3 --version real except named harness rows',linuxLoginctl:process.env.CAPTURE_ALLOW_LOGINCTL==='1'?'explicitly authorized synthetic loginctl':'real',harnessFaults:({K1:['D04 terminal confirmation: synthetic Enter'],K2:['D08 sentinel readFileString redirected to absent sibling for typed filesystem read error'],K3:['D11 clone success implemented by full filesystem copy','D12 partial clone and runner-level error variants','D13 partial clone plus partial fallback copy failure'],K4:['D14 first promotion rename failure','D15 old directory rename failure','D16 promotion failure with real rollback'],K5:['D17 cooperative interrupt at Deferred copy and swap barriers','D18 overlapping complete-B/partial-C copies at Deferred barriers'],K6:['D19 launchctl bootstrap exit 1 until retry'],K7:[],K8:['C02 forced inside-service config; service managers intercepted'],O1:[],O2:['D22 ignored staging removal, ignored readDirectory and surfaced exact-entry removal failures','D23 promotion and rollback rename both fail'],O3:['C03 forced selector inputs','C04 state-only remote-commit characterization, not actual remote update','C05 state/guard and concurrent-write injection']})[bundle],capture:'ordered runtime transcript of real BootService.make, not unit tests'});
 if(bundle==='K1') {
  const c=yield* context('D01');const s=yield* c.service();yield* c.checkpoint('precondition: no unit or launcher; complete runtime A',s);const ex=yield* c.install(s,'D01 first install',{start:true});assert(Exit.isSuccess(ex),'D01 install succeeds');c.consistent(A);yield* c.checkpoint('D01 complete',s);assert((yield* s.status).current,'D01 current');
  {
   const c=yield* context('D02', 'darwin',legacyRoot);const s=yield* c.service();
   if(side==='before') {
    yield* c.install(s,'D02 genuine merge-base legacy seed A',{start:true});yield* c.checkpoint('D02 BASE-GENERATED LEGACY A persisted for head reuse',s,{legacyRoot});
   }else {
    yield* c.checkpoint('D02 genuine base-generated A unit/state reused without rendering in driver',s,{legacyRoot,seedRevision:'36d4d711b79c73eb33131944f73ea4a8c6156484'});
    const b=yield* c.service(B);yield* c.install(b,'D02 migrate legacy A to head B',{start:true});c.consistent(B);yield* c.checkpoint('D02 migrated',b);assert((yield* b.status).current,'D02 migrated current');
   }
  }
  {
   const c=yield* healthy('D03');const unit=(yield* c.s.status).unitPath;const oldProgram=BS.bootServiceProgramOf(nfs.readFileSync(unit,'utf8'))!;const fd=nfs.openSync(oldProgram,'r');
   try {const b=yield* c.service(B);yield* c.install(b,'D03 update A to B',{start:true});const oldFDHash=fileHash(fd);const expectedOldHash=fileHash(np.join(c.base,'runtime','versions',A,'t3'));const newProgram=BS.bootServiceProgramOf(nfs.readFileSync(unit,'utf8'))!;emit('open-descriptor',{oldProgram,newProgram,oldFDHash,expectedOldHash,proof:'entire old open descriptor SHA256 equals release A after path update',pathStable:oldProgram===newProgram});assert((oldProgram===newProgram)===isHead,'D03 expected path stability');assert(oldFDHash===expectedOldHash,'D03 old open descriptor still reads complete A bytes');c.consistent(B);yield* c.checkpoint('D03 B published, old FD read A',b);}finally{nfs.closeSync(fd);}
  }
  {
   const c=yield* healthy('D04');
   const q=yield* Queue.unbounded();yield* Queue.offer(q,{input:Option.some('\r'),key:{name:'return',ctrl:false,meta:false,shift:false}});
   let prompts=0;const terminal=Terminal.make({columns:Effect.succeed(80),rows:Effect.succeed(24),readInput:Effect.sync(()=>{prompts++;emit('harness.prompt',{row:'D04',response:'Enter accepts default yes'});return q;}),readLine:Effect.succeed(''),display:(text:string)=>Effect.sync(()=>emit('terminal',{row:'D04',text}))});
   const reconcile=()=>offerServiceDuringOnboarding.pipe(Effect.provideService(BS.BootService,c.s),Effect.provideService(Terminal.Terminal,terminal),Effect.provideService(HostProcess.Platform,'darwin'));
   yield* c.operation('D04 actual onboarding caller, current A: skips',Effect.scoped(reconcile()));assert(c.commands.length===0,'D04 current caller does not republish');assert(prompts===0,'D04 current caller does not prompt');
   // Seed an extraneous equivalent launcher in base so both revisions receive the same damage.
   if(!nfs.existsSync(c.launcher)) yield* realFs.copy(np.join(c.base,'runtime','versions',A),c.launcher);
   nfs.renameSync(c.launcher,c.launcher+'.saved');
   yield* c.checkpoint('D04 launcher absent',c.s);
   const ex=yield* c.operation('D04 actual onboarding caller with missing launcher; fake yes if prompted',Effect.scoped(reconcile()));assert(Exit.isSuccess(ex),'D04 onboarding result');
   yield* c.checkpoint('D04 after caller reconciliation',c.s,{promptCount:prompts});
   if(!isHead) yield* realFs.copy(c.launcher+'.saved',c.launcher);
   nfs.writeFileSync(np.join(c.launcher,'.install-complete'),'0.1.2\n');
   yield* c.checkpoint('D04 stale launcher sentinel while source/state A',c.s);
   yield* c.install(c.s,'D04 separately labelled direct same-version layer reinstall',{start:true});yield* c.checkpoint('D04 direct reinstall result',c.s);if(isHead)c.consistent(A);
  }
  {
   const c=yield* healthy('D05');const env='# synthetic configuration\r\nT3CODE_EXAMPLE="literal $HOME # value"';nfs.writeFileSync(c.env,env);c.clear();const b=yield* c.service(B);yield* c.install(b,'D05 stage B',{start:false});assert(!c.commands.some(x=>x.command==='launchctl'),'D05 stage causes no stop or activation');assert(nfs.readFileSync(c.env,'utf8')===env,'D05 service.env byte preservation');assert(!(yield* b.status).current,'D05 staged current false');assert(nfs.existsSync(c.marker),'D05 restart marker exists');c.consistent(B);yield* c.checkpoint('D05 staged B, restart pending',b);yield* c.operation('D05 restart',b.restart);yield* c.checkpoint('D05 restarted B',b);assert((yield* b.status).current,'D05 restart clears marker/current true');
  }
 }
 if(bundle==='K2') {
  for(const row of ['D07','D08','D09','D10']) {
   const c=yield* healthy(row);if(!nfs.existsSync(c.launcher))yield* realFs.copy(np.join(c.base,'runtime','versions',A),c.launcher);
   function cp(label:string, expected:boolean) {return Effect.gen(function*(){yield* c.checkpoint(label,c.s);assert((yield* c.s.status).current===expected,row+' '+label+' expected current='+expected);assert((yield* c.s.status).installedVersion===A,row+' installedVersion still A');});}
   if(row==='D07'){nfs.renameSync(np.join(c.launcher,'t3'),np.join(c.launcher,'t3.saved'));yield* cp('launcher entry absent',!isHead);}
   if(row==='D08'){
    nfs.renameSync(np.join(c.launcher,'.install-complete'),np.join(c.launcher,'.install-complete.saved'));yield* cp('launcher sentinel absent',!isHead);nfs.renameSync(np.join(c.launcher,'.install-complete.saved'),np.join(c.launcher,'.install-complete'));
    c.control.readFault=true;emit('harness',{row,fault:'explicit launcher sentinel read error'});yield* cp('harness: launcher sentinel read error',!isHead);c.control.readFault=false;
   }
   if(row==='D09'){
    for(const sentinel of [B+'\n','not-a-semver\n',' \t'+A+'\n ']){nfs.writeFileSync(np.join(c.launcher,'.install-complete'),sentinel);yield* cp('launcher sentinel '+JSON.stringify(sentinel),sentinel.trim()===A||!isHead);}
    nfs.writeFileSync(np.join(c.launcher,'.install-complete'),B+'\n');yield* c.install(c.s,'D09 direct reinstall repairs sentinel');yield* c.checkpoint('D09 sentinel after repair',c.s);if(isHead)assert(nfs.readFileSync(np.join(c.launcher,'.install-complete'),'utf8').trim()===A,'D09 sentinel repaired');
   }
   if(row==='D10'){
    const src=np.join(c.base,'runtime','versions',A);nfs.renameSync(np.join(src,'t3'),np.join(src,'t3.saved'));yield* cp('versioned source entry absent; valid copied launcher',false);nfs.renameSync(np.join(src,'t3.saved'),np.join(src,'t3'));
    nfs.renameSync(np.join(src,'.install-complete'),np.join(src,'.install-complete.saved'));yield* cp('versioned source sentinel absent',false);nfs.renameSync(np.join(src,'.install-complete.saved'),np.join(src,'.install-complete'));nfs.writeFileSync(np.join(src,'.install-complete'),B+'\n');yield* cp('versioned source sentinel mismatched',false);
   }
  }
 }
 if(bundle==='K3R') {
  if(false){
   const c=yield* context('D11');const s=yield* c.service();c.control.cp='success';emit('harness',{row:'D11',fault:'cp success simulated by full real NodeFileSystem.copy, no APFS claim'});yield* c.checkpoint('D11 precondition absent launcher',s);yield* c.install(s,'D11 first publish clone success harness');c.consistent(A);yield* c.checkpoint('D11 first publish',s);const b=yield* c.service(B);yield* c.install(b,'D11 replacement clone success harness');c.consistent(B);yield* c.checkpoint('D11 replacement',b);assert(!c.operations.some(x=>x.op==='copy.start'),'D11 no fallback copy');assert(c.commands.filter(x=>x.command==='cp').every(x=>x.timeoutMs===600000&&x.args[0]==='-c'&&x.args[1]==='-pR'),'D11 exact clone args and ten-minute timeout');
  }
  {
   const c=yield* context('D12');const s=yield* c.service();yield* c.checkpoint('D12 real GNU cp rejection precondition',s);yield* c.install(s,'D12 real GNU cp branch');c.consistent(A);yield* c.checkpoint('D12 real GNU fallback',s);
   if(false)for(const mode of ['partial','runner-error']){emit('harness',{row:'D12',fault:mode});c.control.cp=mode;const b=yield* c.service(mode==='partial'?B:C);c.clear();yield* c.install(b,'D12 injected '+mode);c.consistent(mode==='partial'?B:C);yield* c.checkpoint('D12 fallback complete after '+mode,b);assert(c.operations.filter(x=>x.op==='copy.start').every(x=>x.destinationExists===false),'D12 fallback destination removed first');}
  }
  if(false){const c=yield* healthy('D13');const oldHash=hash(nfs.readFileSync(np.join(c.launcher,'t3')));c.control.cp='partial';c.control.fault='copy-fail';emit('harness',{row:'D13',fault:'nonzero partial clone then partial fallback failure'});const b=yield* c.service(B);const ex=yield* c.install(b,'D13 copy failure',{start:false});assert(Exit.isFailure(ex),'D13 install error retained');assert(hash(nfs.readFileSync(np.join(c.launcher,'t3')))===oldHash,'D13 old launcher intact');yield* c.checkpoint('D13 failed publish; state B and marker expected',b,{oldHash});assert(!c.operations.some(x=>x.op==='rename.complete'&&x.to.endsWith('.plist')),'D13 no unit publication');assert(!nfs.readdirSync(np.join(c.base,'runtime')).some(x=>x.startsWith('launcher.next-')),'D13 staging removed');assert(!(yield* b.status).current,'D13 current false');}
 }
 if(bundle==='K4'&&isHead) {
  for(const [row,fault] of [['D14','promotion'],['D15','old-rename'],['D16','promotion']]) {
   const c=row==='D14'?yield* context(row):yield* healthy(row);const s=yield* c.service(row==='D14'?A:B);const oldHash=nfs.existsSync(np.join(c.launcher,'t3'))?hash(nfs.readFileSync(np.join(c.launcher,'t3'))):null;
   yield* c.checkpoint('precondition before injected rename fault',s,{oldHash});c.control.fault=fault;emit('harness',{row,fault:row==='D14'?'first promotion rename failure':fault});c.clear();const ex=yield* c.install(s,'injected rename error',{start:false});assert(Exit.isFailure(ex),row+' install fails');yield* c.checkpoint('failed publish; raw filesystem cause and state/marker',s,{oldHash});assert(!(yield* s.status).current,row+' current false');assert(!c.operations.some(x=>x.op==='rename.complete'&&x.to.endsWith('.plist')),row+' no new unit published');
   if(oldHash)assert(hash(nfs.readFileSync(np.join(c.launcher,'t3')))===oldHash,row+' previous A hash preserved/restored');else assert(!nfs.existsSync(c.launcher),'D14 no previous launcher or rollback');
   assert(!nfs.readdirSync(np.join(c.base,'runtime')).some(x=>x.startsWith('launcher.next-')),row+' staging removed');
  }
 }
 if(bundle==='K5'&&isHead) {
  {
   const c=yield* healthy('D17-copy');const oldHash=hash(nfs.readFileSync(np.join(c.launcher,'t3')));const entered=yield* Deferred.make();const proceed=yield* Deferred.make();c.control.cp='partial';c.control.copyBarrier=(from:string,to:string)=>Effect.gen(function*(){yield* realFs.makeDirectory(to,{recursive:true});yield* realFs.copyFile(np.join(from,'.install-complete'),np.join(to,'.install-complete'));emit('barrier',{row:'D17',name:'copy',event:'entered partial copy'});yield* Deferred.succeed(entered,undefined);yield* Deferred.await(proceed);yield* realFs.copy(from,to);});const b=yield* c.service(B);emit('harness',{row:'D17',fault:'cooperative interrupt while copy paused on Deferred'});const installing=yield* Effect.forkChild(b.install({start:false}));yield* Deferred.await(entered);yield* c.checkpoint('D17 copy barrier entered, old launcher remains',b);yield* Fiber.interrupt(installing);const ex=yield* Fiber.await(installing);emit('fiber.exit',{row:'D17-copy',...serialExit(ex)});yield* c.checkpoint('D17 copy interruption finalized',b);assert(Exit.isFailure(ex),'D17 copy interrupted');assert(hash(nfs.readFileSync(np.join(c.launcher,'t3')))===oldHash,'D17 copy old hash preserved');assert(!nfs.readdirSync(np.join(c.base,'runtime')).some(x=>x.startsWith('launcher.next-')),'D17 copy staging cleaned');
  }
  {
   const c=yield* healthy('D17-swap');const entered=yield* Deferred.make();const proceed=yield* Deferred.make();c.control.renameBarrier=()=>Effect.gen(function*(){emit('barrier',{row:'D17',name:'between renames',event:'entered after old moved aside'});yield* Deferred.succeed(entered,undefined);yield* Deferred.await(proceed);emit('barrier',{row:'D17',name:'between renames',event:'released'});});const b=yield* c.service(B);emit('harness',{row:'D17',fault:'interrupt requested between uninterruptible swap renames; Deferred release'});const installing=yield* Effect.forkChild(b.install({start:false}));yield* Deferred.await(entered);yield* c.checkpoint('D17 mid-swap: program temporarily absent, swap uninterruptible',b);const interrupting=yield* Effect.forkChild(Fiber.interrupt(installing),{startImmediately:true});emit('interrupt.requested',{row:'D17-swap',completionPending:interrupting.pollUnsafe()===undefined});assert(interrupting.pollUnsafe()===undefined,'D17 interruption waits for uninterruptible region');yield* Deferred.succeed(proceed,undefined);yield* Fiber.join(interrupting);const ex=yield* Fiber.await(installing);emit('fiber.exit',{row:'D17-swap',...serialExit(ex)});yield* c.checkpoint('D17 swap completed before interrupted fiber exit',b);c.consistent(B);
  }
  {
   const c=yield* healthy('D18');const firstCopied=yield* Deferred.make();const resumeFirst=yield* Deferred.make();const secondPartial=yield* Deferred.make();const resumeSecond=yield* Deferred.make();c.control.cp='partial';const destinations:string[]=[];
   c.control.copyBarrier=(from:string,to:string)=>Effect.gen(function*(){destinations.push(to);if(from.endsWith('/'+B)){yield* realFs.copy(from,to);emit('barrier',{row:'D18',name:'B copied',event:'entered',destination:to});yield* Deferred.succeed(firstCopied,undefined);yield* Deferred.await(resumeFirst);emit('barrier',{row:'D18',name:'B copied',event:'released'});}else{yield* realFs.makeDirectory(to,{recursive:true});yield* realFs.copyFile(np.join(from,'.install-complete'),np.join(to,'.install-complete'));emit('barrier',{row:'D18',name:'C partial',event:'entered',destination:to});yield* Deferred.succeed(secondPartial,undefined);yield* Deferred.await(resumeSecond);yield* realFs.copy(from,to);emit('barrier',{row:'D18',name:'C partial',event:'released and full real copy finished'});}});
   const b=yield* c.service(B);const cc=yield* c.service(C);emit('harness',{row:'D18',fault:'deterministic overlapping copies using two Deferred barriers'});const f1=yield* Effect.forkChild(b.install({start:false}));yield* Deferred.await(firstCopied);const f2=yield* Effect.forkChild(cc.install({start:false}));yield* Deferred.await(secondPartial);yield* c.checkpoint('D18 B complete/C partial, both staged',cc);assert(new Set(destinations).size===2,'D18 distinct staging paths');yield* Deferred.succeed(resumeFirst,undefined);const ex1=yield* Fiber.await(f1);emit('fiber.exit',{row:'D18-B',...serialExit(ex1)});yield* c.checkpoint('D18 B released, C still partial',cc);yield* Deferred.succeed(resumeSecond,undefined);const ex2=yield* Fiber.await(f2);emit('fiber.exit',{row:'D18-C',...serialExit(ex2)});yield* c.checkpoint('D18 both exits; final complete C',cc);c.consistent(C);assert(!(yield* cc.status).current,'D18 restart still pending, current false');
  }
 }
 if(bundle==='K6') {
  const c=yield* context('D19');const s=yield* c.service();yield* c.checkpoint('D19 precondition first install',s);emit('harness',{row:'D19',fault:'launchctl bootstrap returns exit 1 until retry'});c.control.bootstrapFail=true;const ex=yield* c.install(s,'D19 install activation failure',{start:true});assert(Exit.isFailure(ex),'D19 activation error');c.consistent(A);yield* c.checkpoint('D19 files published, activation failed',s);assert(!(yield* s.status).current&&nfs.existsSync(c.marker),'D19 retryable restart pending');c.control.bootstrapFail=false;c.clear();yield* c.install(s,'D19 retry',{start:true});yield* c.checkpoint('D19 retry active',s);assert((yield* s.status).current,'D19 retry current true');
 }
 if(bundle==='K7') {
  {
   const c=yield* healthy('D20');if(!nfs.existsSync(c.launcher))yield* realFs.copy(np.join(c.base,'runtime','versions',A),c.launcher);
   for(const name of ['launcher.next-leftover-a','launcher.next-leftover-b','launcher-other','launcher.nextish','launcher.next']){nfs.mkdirSync(np.join(c.base,'runtime',name),{recursive:true});nfs.writeFileSync(np.join(c.base,'runtime',name,'sentinel'),'owned synthetic '+name+'\n');}
   yield* c.checkpoint('D20 unit plus launcher/staging and unrelated siblings',c.s);c.clear();const ex=yield* c.operation('D20 uninstall',c.s.uninstall);assert(Exit.isSuccess(ex)&&ex.value===true,'D20 first uninstall true');yield* c.checkpoint('D20 after uninstall',c.s);assert(nfs.existsSync(c.launcher)===!isHead,'D20 exact launcher removal only at head');for(const name of ['launcher-other','launcher.nextish','launcher.next'])assert(nfs.existsSync(np.join(c.base,'runtime',name)),'D20 preserve unrelated '+name);assert(nfs.existsSync(np.join(c.base,'runtime','versions',A,'t3')),'D20 versions retained');const again=yield* c.operation('D20 second uninstall',c.s.uninstall);assert(Exit.isSuccess(again)&&again.value===false,'D20 second uninstall false');yield* c.checkpoint('D20 second uninstall unchanged',c.s);
  }
  {
   const c=yield* context('D21');const s=yield* c.service();yield* realFs.copy(np.join(c.base,'runtime','versions',A),c.launcher);nfs.mkdirSync(c.launcher+'.next-orphan',{recursive:true});nfs.writeFileSync(np.join(c.launcher+'.next-orphan','partial'),'synthetic orphan');yield* c.checkpoint('D21 no plist, orphan launcher/staging present',s);const ex=yield* c.operation('D21 uninstall without unit',s.uninstall);assert(Exit.isSuccess(ex)&&ex.value===false,'D21 returns false');assert(nfs.existsSync(c.launcher)&&nfs.existsSync(c.launcher+'.next-orphan'),'D21 orphan leftovers preserved');yield* c.checkpoint('D21 early return leaves orphans',s);
  }
 }
 if(bundle==='K8') {
  {
   const c=yield* context('C01','linux');const s=yield* c.service();nfs.mkdirSync(c.launcher,{recursive:true});nfs.writeFileSync(np.join(c.launcher,'sentinel'),'unrelated linux launcher sibling\n');yield* c.checkpoint('C01 precondition no unit; launcher sibling',s);const ex=yield* c.install(s,'C01 linux A first install');
   if(Exit.isSuccess(ex)){
    const b=yield* c.service(B);yield* c.install(b,'C01 update A to B');yield* c.checkpoint('C01 updated B',b);const cc=yield* c.service(C);yield* c.install(cc,'C01 stage C (release B to A, explicit downgrade permission)',{start:false,allowDowngrade:true});yield* c.checkpoint('C01 staged C',cc);yield* c.operation('C01 restart C',cc.restart);yield* c.checkpoint('C01 restarted C',cc);assert((yield* cc.status).current,'C01 Linux current despite sibling');yield* c.operation('C01 uninstall',cc.uninstall);yield* c.checkpoint('C01 uninstalled, sibling retained',cc);assert(nfs.existsSync(np.join(c.launcher,'sentinel')),'C01 linux sibling untouched');assert(!c.commands.some(x=>x.command==='cp'),'C01 no launcher cp');
   }else yield* c.checkpoint('C01 blocked by real loginctl prerequisites; unverified lifecycle',s);
  }
  if(false){
   const c=yield* context('C02','linux');const s=yield* c.service();const ex=yield* c.install(s,'C02 precondition A');if(Exit.isSuccess(ex)){
    const previousState=nfs.readFileSync(c.state,'utf8');const unit=(yield* s.status).unitPath;const previousUnit=nfs.readFileSync(unit,'utf8');c.clear();const b=yield* c.service(B,true);yield* c.checkpoint('C02 inside-service B before handoff',b);const result=yield* c.install(b,'C02 inside service update',{start:true});yield* c.checkpoint('C02 handed off before mutations',b);assert(Exit.isSuccess(result)&&result.value.handedOff===true,'C02 handoff plan');assert(nfs.readFileSync(c.state,'utf8')===previousState&&nfs.readFileSync(unit,'utf8')===previousUnit,'C02 state/unit unchanged');assert(c.commands.filter(x=>x.command==='systemd-run').length===1&&!c.commands.some(x=>x.command==='cp'),'C02 one handoff no cp');
   }else yield* c.checkpoint('C02 blocked by real loginctl precondition',s);
  }
 }

 if(bundle==='O1') {
  const c=yield* context('D06');const s=yield* c.service();yield* c.checkpoint('D06 first install, no unit/launcher',s);yield* c.install(s,'D06 first staged install',{start:false});yield* c.checkpoint('D06 published with no activation',s);assert(!c.commands.some(x=>x.command==='launchctl'),'D06 no activation');assert(!(yield* s.status).current&&nfs.existsSync(c.marker),'D06 restart pending');c.consistent(A);yield* c.operation('D06 later restart',s.restart);yield* c.checkpoint('D06 after restart',s);assert((yield* s.status).current,'D06 restart works');
 }
 if(bundle==='O2'&&isHead) {
  {
   const c=yield* context('D22-staging');const s=yield* c.service();c.control.fault='staging-remove';emit('harness',{row:'D22',fault:'staging removal reports ENOENT from injected sibling, real staging stays'});yield* c.checkpoint('D22 staging cleanup fault precondition',s);const ex=yield* c.install(s,'D22 publish succeeds, staging cleanup error ignored');yield* c.checkpoint('D22 ignored cleanup error leaves staging',s);assert(Exit.isSuccess(ex)&&(yield* s.status).current,'D22 staging cleanup ignored');assert(nfs.readdirSync(np.join(c.base,'runtime')).some(x=>x.startsWith('launcher.next-')),'D22 leftover staging visible');
  }
  {
   const c=yield* healthy('D22-readdir');c.control.fault='readdir';emit('harness',{row:'D22',fault:'runtime readDirectory reports missing sibling path'});const ex=yield* c.operation('D22 uninstall with ignored readdir error',c.s.uninstall);yield* c.checkpoint('D22 readdir failure ignored, launcher retained',c.s);assert(Exit.isSuccess(ex)&&nfs.existsSync(c.launcher),'D22 listing failure ignored');
  }
  {
   const c=yield* healthy('D22-remove');c.control.fault='entry-remove';emit('harness',{row:'D22',fault:'exact launcher removal error after real unit deletion'});const ex=yield* c.operation('D22 uninstall launcher removal fails',c.s.uninstall);yield* c.checkpoint('D22 surfaced removal failure after unit removed',c.s);assert(Exit.isFailure(ex)&&!(yield* c.s.status).installed&&nfs.existsSync(c.launcher),'D22 matching removal failure surfaces');
  }
  {
   const c=yield* healthy('D23');const oldHash=hash(nfs.readFileSync(np.join(c.launcher,'t3')));c.control.fault='double-rename';emit('harness',{row:'D23',fault:'promotion and rollback both fail; final staging cleanup remains real'});const b=yield* c.service(B);yield* c.checkpoint('D23 old launcher A before double failure',b,{oldHash});const ex=yield* c.install(b,'D23 double rename failure',{start:false});yield* c.checkpoint('D23 error retained; rollback error ignored; previous removed by cleanup',b,{oldHash});assert(Exit.isFailure(ex)&&!nfs.existsSync(c.launcher),'D23 double failure loses fixed launcher');assert(c.operations.filter(x=>x.op==='injected.rename-failure').length===2,'D23 both errors recorded');
  }
 }
 if(bundle==='O3') {
  {
   for(const variant of ['unsupported-platform','empty-home','missing-uid','supported-no-unit']) {
    const c=yield* context('C03-'+variant);if(variant==='unsupported-platform')c.control.platform='freebsd';if(variant==='empty-home')c.control.emptyHome=true;if(variant==='missing-uid')c.control.missingUID=true;
    const s=yield* c.service();yield* c.checkpoint('C03 '+variant,s);if(variant!=='supported-no-unit'){yield* c.operation('C03 unsupported install',s.install());yield* c.operation('C03 unsupported uninstall',s.uninstall);assert(!(yield* s.status).supported,'C03 unsupported selector '+variant);}else assert((yield* s.status).supported&&!(yield* s.status).installed,'C03 supported but absent unit');
   }
  }
  {
   const c=yield* healthy('C04');emit('harness',{row:'C04',fault:'characterization only: seed completed remote-update state B; real remote launcher not executed'});nfs.writeFileSync(c.state,JSON.stringify({protocol:SERVICE_LAUNCHER_PROTOCOL,activeVersion:B})+'\n');const b=yield* c.service(B);yield* c.checkpoint('C04 state B committed while plist/launcher A remain',b);assert(!(yield* b.status).current,'C04 both revisions need repair');yield* c.install(b,'C04 direct same-version service repair to match state B');yield* c.checkpoint('C04 repaired B',b);c.consistent(B);assert((yield* b.status).current,'C04 repair current');
  }
  {
   const c=yield* healthy('C05');const originalState=nfs.readFileSync(c.state,'utf8');const unit=(yield* c.s.status).unitPath;const originalUnit=nfs.readFileSync(unit,'utf8');
   if(!nfs.existsSync(c.launcher))yield* realFs.copy(np.join(c.base,'runtime','versions',A),c.launcher);
   const oldHash=hash(nfs.readFileSync(np.join(c.launcher,'t3')));
   for(const variant of ['pending-update','refused-downgrade','concurrently-overwritten-state']) {
    nfs.writeFileSync(c.state,originalState);yield* realFs.remove(c.marker,{force:true});c.clear();
    if(variant==='pending-update')nfs.writeFileSync(c.state,JSON.stringify({protocol:SERVICE_LAUNCHER_PROTOCOL,activeVersion:A,update:{id:'synthetic-pending',fromVersion:A,targetVersion:B,dbPath:'synthetic-not-created.sqlite',status:'pending'}}));
    if(variant==='refused-downgrade')nfs.writeFileSync(c.state,JSON.stringify({protocol:SERVICE_LAUNCHER_PROTOCOL,activeVersion:B}));
    if(variant==='concurrently-overwritten-state')c.control.overwriteState=JSON.stringify({protocol:SERVICE_LAUNCHER_PROTOCOL,activeVersion:C});
    const target=yield* c.service(variant==='concurrently-overwritten-state'?B:A);yield* c.checkpoint('C05 guard precondition '+variant,target,{oldHash});const ex=yield* c.install(target,'C05 '+variant,{start:variant!=='concurrently-overwritten-state'});c.control.overwriteState=undefined;yield* c.checkpoint('C05 guard result '+variant,target,{oldHash});assert(Exit.isFailure(ex),'C05 '+variant+' refused');assert(hash(nfs.readFileSync(np.join(c.launcher,'t3')))===oldHash&&!c.commands.some(x=>x.command==='cp'),'C05 '+variant+' guard precedes publish');
   }
   nfs.writeFileSync(c.state,originalState);yield* realFs.remove(c.marker,{force:true});c.control.path='/a-new-provider/bin:/usr/bin';const changedPath=yield* c.service();yield* c.checkpoint('C05 PATH-only change normalizes current',changedPath);assert((yield* changedPath.status).current,'C05 PATH-only accepted');
   nfs.writeFileSync(unit,originalUnit+'\n<!-- synthetic mismatch -->\n');yield* c.checkpoint('C05 mismatched unit',c.s);assert(!(yield* c.s.status).current,'C05 mismatched unit false');nfs.writeFileSync(unit,originalUnit);nfs.writeFileSync(c.state,'{');yield* c.checkpoint('C05 invalid state',c.s);assert(!(yield* c.s.status).current,'C05 invalid state false');
  }
 }
 emit('bundle.complete',{bundle,side,sourceRevision:revision});
});
const ex=await Effect.runPromiseExit(Effect.scoped(main).pipe(Effect.provide(NodeServices.layer)));
if(Exit.isFailure(ex)){emit('DRIVER_FAILURE',{cause:Cause.pretty(ex.cause)});process.exitCode=1;}
