11import { createHash } from "node:crypto" ;
22import { closeSync , existsSync , fsyncSync , lstatSync , mkdirSync , openSync , readFileSync , readSync , statSync , unlinkSync , writeSync } from "node:fs" ;
3- import { dirname , isAbsolute , join , resolve } from "node:path" ;
3+ import { dirname , join , resolve } from "node:path" ;
44import { zstdDecompressSync } from "node:zlib" ;
55import { Database } from "bun:sqlite" ;
66import { resolveCodexStateDbPath } from "./paths" ;
77import { atomicWriteFile , getConfigDir } from "../config" ;
8+ import {
9+ CODEX_HISTORY_RESUMABLE_SOURCES ,
10+ codexHistoryBackupId ,
11+ sameCodexHistoryPath ,
12+ validateCodexHistoryBackupManifest ,
13+ type CodexHistoryBackupEntry ,
14+ type CodexHistoryBackupManifest ,
15+ } from "./history-manifest" ;
816
917/**
1018 * Cap for decompressing a lone `.jsonl.zst` rollout during quarantine restore.
@@ -21,11 +29,8 @@ export const MAX_ROLLOUT_ZST_DECOMPRESSED_BYTES = 64 * 1024 * 1024;
2129 * the same way, since a manifest addressed differently is a different manifest.
2230 */
2331export function historyBackupPathFor ( stateDbPath : string ) : string {
24- const normalized = process . platform === "win32" ? resolve ( stateDbPath ) . toLowerCase ( ) : resolve ( stateDbPath ) ;
25- const id = createHash ( "sha256" ) . update ( normalized ) . digest ( "hex" ) . slice ( 0 , 16 ) ;
26- return join ( getConfigDir ( ) , `codex-history-backup-${ id } .json` ) ;
32+ return join ( getConfigDir ( ) , `codex-history-backup-${ codexHistoryBackupId ( stateDbPath ) } .json` ) ;
2733}
28- const RESUMABLE_SOURCES = [ "cli" , "vscode" ] as const ;
2934
3035/**
3136 * Open the live `state_5.sqlite` the way the Codex app expects a *secondary* writer to behave:
@@ -256,20 +261,6 @@ function hasFirstUserMessage(value: string | null): boolean {
256261 return typeof value === "string" && value . trim ( ) . length > 0 ;
257262}
258263
259- interface BackupEntry {
260- id : string ;
261- rolloutPath : string ;
262- modelProvider : string ;
263- source : string ;
264- hasUserEvent : number ;
265- }
266-
267- interface BackupManifest {
268- version : 1 ;
269- stateDbPath ?: string ;
270- entries : Record < string , BackupEntry > ;
271- }
272-
273264export interface CodexHistoryVerifiedNoopProof {
274265 readonly kind : "verified-noop" ;
275266 readonly pendingRows : 0 ;
@@ -311,7 +302,7 @@ type StrictBackupRead =
311302 | {
312303 readonly kind : "known" ;
313304 readonly present : boolean ;
314- readonly manifest : BackupManifest ;
305+ readonly manifest : CodexHistoryBackupManifest ;
315306 readonly fingerprint : string ;
316307 }
317308 | {
@@ -352,12 +343,6 @@ export function setBeforeHistoryApplyTransactionForTests(hook: (() => void) | un
352343 beforeHistoryApplyTransactionForTests = hook ;
353344}
354345
355- function samePath ( a : string , b : string ) : boolean {
356- const left = resolve ( a ) ;
357- const right = resolve ( b ) ;
358- return process . platform === "win32" ? left . toLowerCase ( ) === right . toLowerCase ( ) : left === right ;
359- }
360-
361346function readBackupStrict ( path : string , stateDbPath : string ) : StrictBackupRead {
362347 let pathStat : ReturnType < typeof lstatSync > ;
363348 try {
@@ -401,50 +386,18 @@ function readBackupStrict(path: string, stateDbPath: string): StrictBackupRead {
401386 } catch {
402387 return { kind : "unknown" , present : true , reason : "manifest-read" } ;
403388 }
404- if ( ! parsed || typeof parsed !== "object" || Array . isArray ( parsed ) ) {
405- return { kind : "unknown" , present : true , reason : "manifest-schema" } ;
406- }
407- const manifest = parsed as Partial < BackupManifest > ;
408- if ( manifest . version !== 1
409- || typeof manifest . stateDbPath !== "string"
410- || ! manifest . stateDbPath . trim ( )
411- || ! isAbsolute ( manifest . stateDbPath ) ) {
412- return { kind : "unknown" , present : true , reason : "manifest-schema" } ;
413- }
414- if ( ! samePath ( manifest . stateDbPath , stateDbPath ) ) {
415- return { kind : "unknown" , present : true , reason : "manifest-foreign" } ;
416- }
417- if ( ! manifest . entries || typeof manifest . entries !== "object" || Array . isArray ( manifest . entries ) ) {
418- return { kind : "unknown" , present : true , reason : "manifest-schema" } ;
419- }
420- for ( const [ id , value ] of Object . entries ( manifest . entries ) ) {
421- if ( ! value || typeof value !== "object" || Array . isArray ( value ) ) {
422- return { kind : "unknown" , present : true , reason : "manifest-schema" } ;
423- }
424- const entry = value as Partial < BackupEntry > ;
425- if ( ! id
426- || entry . id !== id
427- || typeof entry . rolloutPath !== "string"
428- || ! entry . rolloutPath . trim ( )
429- || ! isAbsolute ( entry . rolloutPath )
430- || typeof entry . modelProvider !== "string"
431- || ! entry . modelProvider . trim ( )
432- || typeof entry . source !== "string"
433- || ! entry . source . trim ( )
434- || typeof entry . hasUserEvent !== "number"
435- || ! Number . isSafeInteger ( entry . hasUserEvent )
436- || ( entry . hasUserEvent !== 0 && entry . hasUserEvent !== 1 )
437- || ! (
438- ( entry . modelProvider === "openai" && RESUMABLE_SOURCES . includes ( entry . source as ( typeof RESUMABLE_SOURCES ) [ number ] ) )
439- || ( entry . modelProvider === "opencodex" && entry . source === "exec" )
440- ) ) {
441- return { kind : "unknown" , present : true , reason : "manifest-schema" } ;
442- }
389+ const validated = validateCodexHistoryBackupManifest ( parsed , stateDbPath ) ;
390+ if ( ! validated . ok ) {
391+ return {
392+ kind : "unknown" ,
393+ present : true ,
394+ reason : validated . reason === "foreign-database" ? "manifest-foreign" : "manifest-schema" ,
395+ } ;
443396 }
444397 return {
445398 kind : "known" ,
446399 present : true ,
447- manifest : manifest as BackupManifest ,
400+ manifest : validated . manifest ,
448401 fingerprint : createHash ( "sha256" ) . update ( raw ) . digest ( "hex" ) ,
449402 } ;
450403}
@@ -500,7 +453,7 @@ function consumeBackupIfUnchanged(path: string, stateDbPath: string, expectedFin
500453 unlinkSync ( path ) ;
501454}
502455
503- function writeBackup ( path : string , manifest : BackupManifest , stateDbPath ?: string ) : void {
456+ function writeBackup ( path : string , manifest : CodexHistoryBackupManifest , stateDbPath ?: string ) : void {
504457 if ( Object . keys ( manifest . entries ) . length === 0 ) {
505458 if ( existsSync ( path ) ) unlinkSync ( path ) ;
506459 return ;
@@ -509,7 +462,7 @@ function writeBackup(path: string, manifest: BackupManifest, stateDbPath?: strin
509462 atomicWriteFile ( path , JSON . stringify ( { ...manifest , stateDbPath : manifest . stateDbPath ?? stateDbPath } , null , 2 ) + "\n" ) ;
510463}
511464
512- function rememberOriginal ( manifest : BackupManifest , row : ThreadRow ) : void {
465+ function rememberOriginal ( manifest : CodexHistoryBackupManifest , row : ThreadRow ) : void {
513466 if ( manifest . entries [ row . id ] ) return ;
514467 manifest . entries [ row . id ] = {
515468 id : row . id ,
@@ -531,7 +484,7 @@ function rowMatchesRestoreTuple(
531484 && row . has_user_event === hasUserEvent ;
532485}
533486
534- function rowMatchesExpectedPostImage ( row : RestoreRowSnapshot , entry : BackupEntry ) : boolean {
487+ function rowMatchesExpectedPostImage ( row : RestoreRowSnapshot , entry : CodexHistoryBackupEntry ) : boolean {
535488 if ( entry . modelProvider === "openai" ) {
536489 const postHasUserEvent = hasFirstUserMessage ( row . first_user_message ) ? 1 : entry . hasUserEvent ;
537490 return rowMatchesRestoreTuple ( row , "opencodex" , entry . source , postHasUserEvent ) ;
@@ -564,7 +517,7 @@ function normalizedSessionMetaTuple(meta: ParsedSessionMeta): { provider: string
564517
565518function rolloutMatchesRestoreTuple (
566519 meta : ParsedSessionMeta ,
567- entry : BackupEntry ,
520+ entry : CodexHistoryBackupEntry ,
568521 provider : string ,
569522 source : string ,
570523) : boolean {
@@ -574,7 +527,7 @@ function rolloutMatchesRestoreTuple(
574527 && tuple . source === source ;
575528}
576529
577- function rolloutMatchesExpectedPostImage ( meta : ParsedSessionMeta , entry : BackupEntry ) : boolean {
530+ function rolloutMatchesExpectedPostImage ( meta : ParsedSessionMeta , entry : CodexHistoryBackupEntry ) : boolean {
578531 if ( entry . modelProvider === "openai" ) {
579532 const tuple = normalizedSessionMetaTuple ( meta ) ;
580533 const rawSource = meta . record . payload . source ;
@@ -591,7 +544,7 @@ function rolloutMatchesExpectedPostImage(meta: ParsedSessionMeta, entry: BackupE
591544 || rolloutMatchesRestoreTuple ( meta , entry , "openai" , "cli" ) ;
592545}
593546
594- function snapshotRolloutForRestore ( entry : BackupEntry ) : RestoreRolloutSnapshot {
547+ function snapshotRolloutForRestore ( entry : CodexHistoryBackupEntry ) : RestoreRolloutSnapshot {
595548 const identityBefore = historyFileIdentity ( entry . rolloutPath ) ;
596549 if ( identityBefore === null ) {
597550 throw new CodexHistoryIntegrityError ( "history_backup_rollout_unrestorable" ) ;
@@ -632,7 +585,7 @@ interface RestoreTargetPreflight {
632585 */
633586function preflightRestoreTargets (
634587 getCurrent : ( id : string ) => RestoreRowSnapshot | null ,
635- entries : BackupEntry [ ] ,
588+ entries : CodexHistoryBackupEntry [ ] ,
636589) : RestoreTargetPreflight {
637590 const snapshots = preflightRestoreRows ( getCurrent , entries ) ;
638591 const rolloutSnapshots = new Map < string , RestoreRolloutSnapshot > ( ) ;
@@ -647,12 +600,12 @@ function preflightRestoreTargets(
647600/** Cheap manifest-to-database authority check used by recurring no-op probes. */
648601function preflightRestoreRows (
649602 getCurrent : ( id : string ) => RestoreRowSnapshot | null ,
650- entries : BackupEntry [ ] ,
603+ entries : CodexHistoryBackupEntry [ ] ,
651604) : Map < string , RestoreRowSnapshot > {
652605 const snapshots = new Map < string , RestoreRowSnapshot > ( ) ;
653606 for ( const entry of entries ) {
654607 const row = getCurrent ( entry . id ) ;
655- if ( ! row || typeof row . rollout_path !== "string" || ! samePath ( row . rollout_path , entry . rolloutPath ) ) {
608+ if ( ! row || typeof row . rollout_path !== "string" || ! sameCodexHistoryPath ( row . rollout_path , entry . rolloutPath ) ) {
656609 throw new CodexHistoryIntegrityError ( "history_backup_target_mismatch" ) ;
657610 }
658611 if ( ! rowMatchesRestoreTuple ( row , entry . modelProvider , entry . source , entry . hasUserEvent )
@@ -666,12 +619,12 @@ function preflightRestoreRows(
666619
667620function assertRestoreReadback (
668621 getCurrent : ( id : string ) => RestoreRowSnapshot | null ,
669- entries : BackupEntry [ ] ,
622+ entries : CodexHistoryBackupEntry [ ] ,
670623) : void {
671624 for ( const entry of entries ) {
672625 const row = getCurrent ( entry . id ) ;
673626 if ( ! row
674- || ! samePath ( row . rollout_path , entry . rolloutPath )
627+ || ! sameCodexHistoryPath ( row . rollout_path , entry . rolloutPath )
675628 || ! rowMatchesRestoreTuple ( row , entry . modelProvider , entry . source , entry . hasUserEvent ) ) {
676629 throw new CodexHistoryIntegrityError ( "history_backup_database_readback_mismatch" ) ;
677630 }
@@ -1177,15 +1130,15 @@ function syncCodexHistoryProviderUnsafe(provider: CodexHistoryProvider, stateDbP
11771130
11781131 const db = openStateDb ( stateDbPath ) ;
11791132 try {
1180- const placeholders = RESUMABLE_SOURCES . map ( ( ) => "?" ) . join ( "," ) ;
1133+ const placeholders = CODEX_HISTORY_RESUMABLE_SOURCES . map ( ( ) => "?" ) . join ( "," ) ;
11811134 const openaiRows = db
11821135 . query < ApplyRowSnapshot , string [ ] > ( `
11831136 SELECT id, rollout_path, model_provider, source, has_user_event, first_user_message
11841137 FROM threads
11851138 WHERE model_provider = 'openai'
11861139 AND source IN (${ placeholders } )
11871140 ` )
1188- . all ( ...RESUMABLE_SOURCES ) ;
1141+ . all ( ...CODEX_HISTORY_RESUMABLE_SOURCES ) ;
11891142 const execRows = db
11901143 . query < ApplyRowSnapshot , [ ] > ( `
11911144 SELECT id, rollout_path, model_provider, source, has_user_event, first_user_message
@@ -1470,7 +1423,7 @@ export function snapshotCodexHistoryNoop(
14701423 const stateDbPresent = existsSync ( stateDbPath ) ;
14711424 const backupPresent = existsSync ( backupPath ) ;
14721425 const base = { canonicalStateDbPath, stateDbPresent, canonicalBackupPath, backupPresent } ;
1473- if ( ! samePath ( backupPath , historyBackupPathFor ( stateDbPath ) ) ) {
1426+ if ( ! sameCodexHistoryPath ( backupPath , historyBackupPathFor ( stateDbPath ) ) ) {
14741427 return { kind : "unknown" , pendingRows : null , backupEntries : null , ...base , reason : "backup-path" } ;
14751428 }
14761429 const backup = inspectBackupForNoop ( backupPath , stateDbPath ) ;
0 commit comments