@@ -3,13 +3,15 @@ import {
33 chmodSync ,
44 closeSync ,
55 existsSync ,
6+ fstatSync ,
67 lstatSync ,
78 mkdirSync ,
89 openSync ,
910 readFileSync ,
1011 readSync ,
1112 renameSync ,
1213 statSync ,
14+ type Stats ,
1315 unlinkSync ,
1416 writeFileSync ,
1517} from "node:fs" ;
@@ -22,6 +24,8 @@ import { isWslRuntime, wslAutomountRoot } from "./home";
2224const SHIM_MARKER = "opencodex codex autostart shim" ;
2325const CODEX_SHIM_PROBE_BYTES = 16 * 1024 ;
2426export const CODEX_SHIM_REPLACEMENT_STABLE_MS = 100 ;
27+ export const CODEX_SHIM_STATE_MAX_BYTES = 1024 * 1024 ;
28+ const CODEX_SHIM_RESTORE_LOCK_STALE_MS = 30_000 ;
2529let lastShimDiscoveryError : string | null = null ;
2630/** Last human-readable reason discovery returned null (exposed for doctor/tests). */
2731export function lastCodexDiscoveryError ( ) : string | null {
@@ -105,7 +109,8 @@ interface InstallCodexShimInternalOptions {
105109}
106110
107111export type CodexShimAutoRestoreResult =
108- | { status : "not-installed" | "healthy" | "ineligible" | "deferred" | "disabled" }
112+ | { status : "not-installed" | "healthy" | "disabled" }
113+ | { status : "ineligible" | "deferred" ; message ?: string }
109114 | { status : "restored" ; message : string } ;
110115
111116function cliEntry ( ) : { bun : string ; cli : string } {
@@ -214,10 +219,8 @@ function stableShimPathProbe(path: string): StableShimPathProbe | null {
214219 return contentSize > 0 ? { fingerprint, prefix } : null ;
215220}
216221
217- function fingerprintIsOldEnough ( fingerprint : ShimPathFingerprint , nowMs : number ) : boolean {
218- const timestamps = [ fingerprint . mtimeMs , fingerprint . ctimeMs ] ;
219- if ( fingerprint . target ) timestamps . push ( fingerprint . target . mtimeMs , fingerprint . target . ctimeMs ) ;
220- return nowMs - Math . max ( ...timestamps ) >= CODEX_SHIM_REPLACEMENT_STABLE_MS ;
222+ function sameStableShimPathProbe ( left : StableShimPathProbe , right : StableShimPathProbe ) : boolean {
223+ return left . prefix === right . prefix && sameFingerprint ( left . fingerprint , right . fingerprint ) ;
221224}
222225
223226function isHealthyShimProbe ( probe : StableShimPathProbe , platform : NodeJS . Platform ) : boolean {
@@ -490,12 +493,62 @@ exit $LASTEXITCODE
490493` ;
491494}
492495
493- function readState ( ) : ShimState | null {
496+ interface ShimStateReadResult {
497+ state : ShimState | null ;
498+ warning ?: string ;
499+ }
500+
501+ function fileErrorCode ( error : unknown ) : string | undefined {
502+ return error && typeof error === "object" && "code" in error
503+ ? String ( ( error as { code ?: unknown } ) . code )
504+ : undefined ;
505+ }
506+
507+ function readBoundedRegularFile ( path : string , maxBytes : number ) : { content : string } | { warning : string } | null {
508+ let fd : number ;
509+ try {
510+ fd = openSync ( path , "r" ) ;
511+ } catch ( error ) {
512+ if ( fileErrorCode ( error ) === "ENOENT" ) return null ;
513+ return { warning : `Codex shim state could not be opened as a regular file at ${ path } .` } ;
514+ }
515+ try {
516+ const before = fstatSync ( fd ) ;
517+ if ( ! before . isFile ( ) ) return { warning : `Codex shim state is not a regular file at ${ path } ; auto-restore skipped.` } ;
518+ if ( before . size > maxBytes ) {
519+ return { warning : `Codex shim state exceeds the 1 MiB startup limit at ${ path } ; auto-restore skipped.` } ;
520+ }
521+ const buffer = Buffer . allocUnsafe ( before . size ) ;
522+ let offset = 0 ;
523+ while ( offset < buffer . length ) {
524+ const bytesRead = readSync ( fd , buffer , offset , buffer . length - offset , offset ) ;
525+ if ( bytesRead === 0 ) return { warning : `Codex shim state changed while being read at ${ path } ; auto-restore skipped.` } ;
526+ offset += bytesRead ;
527+ }
528+ const extra = Buffer . allocUnsafe ( 1 ) ;
529+ if ( readSync ( fd , extra , 0 , 1 , offset ) !== 0 ) {
530+ return { warning : `Codex shim state exceeds the 1 MiB startup limit at ${ path } ; auto-restore skipped.` } ;
531+ }
532+ const after = fstatSync ( fd ) ;
533+ if ( before . dev !== after . dev || before . ino !== after . ino || before . size !== after . size
534+ || before . mtimeMs !== after . mtimeMs || before . ctimeMs !== after . ctimeMs ) {
535+ return { warning : `Codex shim state changed while being read at ${ path } ; auto-restore skipped.` } ;
536+ }
537+ return { content : buffer . toString ( "utf8" ) } ;
538+ } finally {
539+ closeSync ( fd ) ;
540+ }
541+ }
542+
543+ function readStateResult ( ) : ShimStateReadResult {
544+ const bounded = readBoundedRegularFile ( statePath ( ) , CODEX_SHIM_STATE_MAX_BYTES ) ;
545+ if ( ! bounded ) return { state : null } ;
546+ if ( "warning" in bounded ) return { state : null , warning : bounded . warning } ;
494547 try {
495- const value = JSON . parse ( readFileSync ( statePath ( ) , "utf8" ) ) as unknown ;
496- if ( ! value || typeof value !== "object" ) return null ;
548+ const value = JSON . parse ( bounded . content ) as unknown ;
549+ if ( ! value || typeof value !== "object" ) return { state : null } ;
497550 const state = value as Record < string , unknown > ;
498- if ( typeof state . platform !== "string" ) return null ;
551+ if ( typeof state . platform !== "string" ) return { state : null } ;
499552 const validFile = ( item : unknown ) : item is ShimFileState => {
500553 if ( ! item || typeof item !== "object" ) return false ;
501554 const file = item as Record < string , unknown > ;
@@ -506,16 +559,20 @@ function readState(): ShimState | null {
506559 && ( file . preserveOnly === undefined || typeof file . preserveOnly === "boolean" ) ;
507560 } ;
508561 if ( state . wrappers !== undefined ) {
509- if ( ! Array . isArray ( state . wrappers ) || state . wrappers . length === 0 || ! state . wrappers . every ( validFile ) ) return null ;
562+ if ( ! Array . isArray ( state . wrappers ) || state . wrappers . length === 0 || ! state . wrappers . every ( validFile ) ) return { state : null } ;
510563 } else if ( ! validFile ( state ) ) {
511- return null ;
564+ return { state : null } ;
512565 }
513- return state as unknown as ShimState ;
566+ return { state : state as unknown as ShimState } ;
514567 } catch {
515- return null ;
568+ return { state : null } ;
516569 }
517570}
518571
572+ function readState ( ) : ShimState | null {
573+ return readStateResult ( ) . state ;
574+ }
575+
519576function statePath ( ) : string {
520577 return join ( getConfigDir ( ) , "codex-shim.json" ) ;
521578}
@@ -619,6 +676,70 @@ interface GuardedRefreshJournalEntry {
619676
620677let guardedRefreshTransactionId = 0 ;
621678
679+ interface ShimRestoreLock {
680+ release ( ) : void ;
681+ }
682+
683+ function restoreLockPath ( ) : string {
684+ return join ( getConfigDir ( ) , "codex-shim.autorestore.lock" ) ;
685+ }
686+
687+ function sameFileIdentity ( left : Stats , right : Stats ) : boolean {
688+ return left . dev === right . dev && left . ino === right . ino ;
689+ }
690+
691+ function reclaimStaleRestoreLock ( path : string ) : boolean {
692+ const before = statFingerprint ( path , false ) ;
693+ if ( ! before || before . kind !== "file" || Date . now ( ) - before . mtimeMs <= CODEX_SHIM_RESTORE_LOCK_STALE_MS ) return false ;
694+ const after = statFingerprint ( path , false ) ;
695+ if ( ! after || ! sameFingerprint ( before , after ) ) return false ;
696+ try {
697+ unlinkSync ( path ) ;
698+ return true ;
699+ } catch ( error ) {
700+ if ( fileErrorCode ( error ) === "ENOENT" ) return true ;
701+ return false ;
702+ }
703+ }
704+
705+ function tryAcquireShimRestoreLock ( ) : ShimRestoreLock | null {
706+ const dir = getConfigDir ( ) ;
707+ if ( ! existsSync ( dir ) ) mkdirSync ( dir , { recursive : true , mode : 0o700 } ) ;
708+ const path = restoreLockPath ( ) ;
709+ for ( let attempt = 0 ; attempt < 2 ; attempt += 1 ) {
710+ let fd : number | null = null ;
711+ let identity : Stats | null = null ;
712+ try {
713+ fd = openSync ( path , "wx" , 0o600 ) ;
714+ identity = fstatSync ( fd ) ;
715+ writeFileSync ( fd , `${ JSON . stringify ( { acquiredAt : Date . now ( ) , pid : process . pid } ) } \n` , "utf8" ) ;
716+ identity = fstatSync ( fd ) ;
717+ let released = false ;
718+ return {
719+ release ( ) : void {
720+ if ( released ) return ;
721+ released = true ;
722+ try { closeSync ( fd ! ) ; } catch { /* stale recovery handles an uncertain lock */ }
723+ try {
724+ if ( identity && sameFileIdentity ( identity , lstatSync ( path ) ) ) unlinkSync ( path ) ;
725+ } catch { /* stale recovery handles release failures */ }
726+ } ,
727+ } ;
728+ } catch ( error ) {
729+ if ( fd !== null ) {
730+ try { closeSync ( fd ) ; } catch { /* best-effort close before ownership cleanup */ }
731+ try {
732+ if ( identity && sameFileIdentity ( identity , lstatSync ( path ) ) ) unlinkSync ( path ) ;
733+ } catch { /* leave an uncertain lock for stale recovery */ }
734+ }
735+ if ( fileErrorCode ( error ) !== "EEXIST" ) throw error ;
736+ if ( attempt === 0 && reclaimStaleRestoreLock ( path ) ) continue ;
737+ return null ;
738+ }
739+ }
740+ return null ;
741+ }
742+
622743function planGuardedRefreshTransaction (
623744 files : readonly ShimFileState [ ] ,
624745 expectedReplacements : ReadonlyMap < string , ShimPathFingerprint > ,
@@ -835,18 +956,24 @@ export function installCodexShim(): { installed: boolean; message: string } {
835956
836957export function autoRestoreCodexShim ( options : {
837958 enabled : ( ) => boolean ;
838- nowMs ?: number ;
959+ stabilitySleep ?: ( ms : number ) => void ;
960+ /** Narrow deterministic seam used to hold the interprocess lock in tests. */
961+ afterRestoreLockAcquired ?: ( ) => void ;
839962 /** Narrow deterministic race seam for the guarded transaction tests. */
840963 beforeGuardedRefresh ?: ( wrapperPath : string , index : number ) => void ;
841964} ) : CodexShimAutoRestoreResult {
842- const state = readState ( ) ;
843- if ( ! state ) return { status : existsSync ( statePath ( ) ) ? "ineligible" : "not-installed" } ;
965+ const stateRead = readStateResult ( ) ;
966+ const state = stateRead . state ;
967+ if ( ! state ) {
968+ if ( stateRead . warning ) return { status : "ineligible" , message : stateRead . warning } ;
969+ return { status : existsSync ( statePath ( ) ) ? "ineligible" : "not-installed" } ;
970+ }
844971 if ( state . platform !== process . platform ) return { status : "ineligible" } ;
845972
846973 const files = stateFiles ( state ) ;
847- const expectedReplacements = new Map < string , ShimPathFingerprint > ( ) ;
974+ const replacementProbes = new Map < string , StableShimPathProbe > ( ) ;
848975 const seen = new Set < string > ( ) ;
849- const nowMs = options . nowMs ?? Date . now ( ) ;
976+ let healthyCount = 0 ;
850977 for ( const file of files ) {
851978 if ( seen . has ( file . wrapperPath ) ) return { status : "ineligible" } ;
852979 seen . add ( file . wrapperPath ) ;
@@ -859,22 +986,44 @@ export function autoRestoreCodexShim(options: {
859986 if ( ! probe ) return { status : "deferred" } ;
860987 if ( probe . prefix . includes ( SHIM_MARKER ) ) {
861988 if ( ! isHealthyShimProbe ( probe , state . platform ) ) return { status : "ineligible" } ;
989+ healthyCount += 1 ;
862990 continue ;
863991 }
864- if ( ! fingerprintIsOldEnough ( probe . fingerprint , nowMs ) ) return { status : "deferred" } ;
865- expectedReplacements . set ( file . wrapperPath , probe . fingerprint ) ;
992+ replacementProbes . set ( file . wrapperPath , probe ) ;
866993 }
867994
868- if ( expectedReplacements . size === 0 ) return { status : "healthy" } ;
995+ if ( replacementProbes . size === 0 ) return { status : "healthy" } ;
869996 if ( ! options . enabled ( ) ) return { status : "disabled" } ;
870- const result = installCodexShimInternal ( {
871- allowFreshInstall : false ,
872- expectedReplacements,
873- beforeGuardedRefresh : options . beforeGuardedRefresh ,
874- } ) ;
875- return result . installed
876- ? { status : "restored" , message : result . message }
877- : { status : "deferred" } ;
997+ if ( files . length > 1 && healthyCount > 0 ) {
998+ return {
999+ status : "deferred" ,
1000+ message : "Codex shim auto-restore deferred because tracked launcher siblings are in a mixed shim/replacement state." ,
1001+ } ;
1002+ }
1003+
1004+ const lock = tryAcquireShimRestoreLock ( ) ;
1005+ if ( ! lock ) return { status : "deferred" } ;
1006+ try {
1007+ options . afterRestoreLockAcquired ?.( ) ;
1008+ ( options . stabilitySleep ?? Bun . sleepSync ) ( CODEX_SHIM_REPLACEMENT_STABLE_MS ) ;
1009+ const expectedReplacements = new Map < string , ShimPathFingerprint > ( ) ;
1010+ for ( const [ path , firstProbe ] of replacementProbes ) {
1011+ const secondProbe = stableShimPathProbe ( path ) ;
1012+ if ( ! secondProbe || secondProbe . prefix . includes ( SHIM_MARKER )
1013+ || ! sameStableShimPathProbe ( firstProbe , secondProbe ) ) return { status : "deferred" } ;
1014+ expectedReplacements . set ( path , secondProbe . fingerprint ) ;
1015+ }
1016+ const result = installCodexShimInternal ( {
1017+ allowFreshInstall : false ,
1018+ expectedReplacements,
1019+ beforeGuardedRefresh : options . beforeGuardedRefresh ,
1020+ } ) ;
1021+ return result . installed
1022+ ? { status : "restored" , message : result . message }
1023+ : { status : "deferred" } ;
1024+ } finally {
1025+ lock . release ( ) ;
1026+ }
8781027}
8791028
8801029export function uninstallCodexShim ( ) : { removed : boolean ; message : string } {
0 commit comments