vetto 0.2.20

Daemon-less sandbox + security layer for AI coding agents (Landlock/Seatbelt, TUI statusline, post-session audit reports)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
//! Read-only, index-first discovery for Codex rollout files.
//!
//! The normal filesystem walk is intentionally kept as an explicit escape
//! hatch (`vetto rescue scan --all`).  Large Codex homes can contain many
//! thousands of rollout files, while the provider's SQLite state store (or a
//! small `session_index.jsonl` file supplied by a future provider version)
//! already identifies the sessions a user is likely trying to recover.  This
//! module consumes those indexes without opening them for writing, verifies
//! every path before returning it, and fails closed when the index cannot be
//! trusted.  It never falls back to a partial directory walk.

use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use rusqlite::{types::ValueRef, Connection};
use serde_json::Value;

#[cfg(unix)]
use std::os::unix::fs::MetadataExt;

use super::{
    safe_fs,
    types::{RescueContext, SessionRef},
};

const MAX_INDEX_ROWS: usize = 100_000;
const MAX_SQLITE_CELL_BYTES: usize = 64 * 1024;
const MAX_SQLITE_DATABASES: usize = 64;
const SQLITE_NAMES: [&str; 3] = ["state_5.sqlite", "state.sqlite", "state.db"];
const SESSION_INDEX_NAME: &str = "session_index.jsonl";
const PATH_COLUMNS: [&str; 3] = ["rollout_path", "session_path", "path"];

/// Result of a verified index-first discovery pass.
#[derive(Debug)]
pub struct IndexDiscovery {
    pub sessions: Vec<SessionRef>,
    /// Number of unique index records verified before applying `--limit`.
    pub candidate_count: usize,
    pub truncated: bool,
    /// Stable source label; this intentionally contains no user paths.
    pub source: String,
}

struct CandidateAccumulator {
    limit: usize,
    /// These sets are bounded by the provider-index row budget. They avoid
    /// retaining every SessionRef while still making candidate_count honest
    /// in the presence of duplicate index rows or aliases.
    seen_raw: HashSet<String>,
    seen_paths: HashSet<PathBuf>,
    sessions: Vec<SessionRef>,
    indexed_rows_seen: usize,
    candidate_count: usize,
    total_bytes: u64,
}

impl CandidateAccumulator {
    fn new(limit: usize, capacity_hint: usize) -> Self {
        Self {
            limit,
            seen_raw: HashSet::new(),
            seen_paths: HashSet::new(),
            // The CLI --limit is unbounded; never preallocate from it directly.
            sessions: Vec::with_capacity(capacity_hint),
            indexed_rows_seen: 0,
            candidate_count: 0,
            total_bytes: 0,
        }
    }

    fn accept(
        &mut self,
        context: &RescueContext,
        configured_root: &Path,
        canonical_root: &Path,
        roots: &[PathBuf],
        raw: String,
    ) -> Result<()> {
        if roots.is_empty() {
            bail!("Codex index is present but no real sessions directory exists");
        }
        self.indexed_rows_seen = self
            .indexed_rows_seen
            .checked_add(1)
            .context("indexed row counter overflow")?;
        if self.indexed_rows_seen > context.max_files {
            bail!(
                "Codex index exceeded the configured {} entry budget",
                context.max_files
            );
        }
        if !self.seen_raw.insert(raw.clone()) {
            return Ok(());
        }
        let session = verify_index_path(context, configured_root, canonical_root, roots, &raw)?;
        if !self.seen_paths.insert(session.source_path.clone()) {
            return Ok(());
        }
        self.candidate_count = self
            .candidate_count
            .checked_add(1)
            .context("indexed session counter overflow")?;
        self.total_bytes = self
            .total_bytes
            .checked_add(session.bytes)
            .context("indexed session byte counter overflow")?;
        if self.total_bytes > context.max_total_bytes {
            bail!(
                "limited rescue scan exceeded the {} byte budget",
                context.max_total_bytes
            );
        }

        self.sessions.push(session);
        self.sessions.sort_by(session_order);
        if self.sessions.len() > self.limit {
            self.sessions.pop();
        }
        Ok(())
    }

    fn finish(self, source: String) -> Result<IndexDiscovery> {
        if self.candidate_count == 0 {
            bail!(
                "Codex index was found but contained no rollout paths; refusing to return a misleading empty limited scan"
            );
        }
        let truncated = self.candidate_count > self.limit;
        Ok(IndexDiscovery {
            sessions: self.sessions,
            candidate_count: self.candidate_count,
            truncated,
            source,
        })
    }
}

fn session_order(left: &SessionRef, right: &SessionRef) -> std::cmp::Ordering {
    right
        .modified_unix_secs
        .cmp(&left.modified_unix_secs)
        .then_with(|| left.key.cmp(&right.key))
}

/// Discover sessions from provider indexes, with an optional caller limit.
///
/// A missing or unreadable index is an error.  In particular, this function
/// does not silently switch to the recursive filesystem walker: a successful
/// limited scan must mean that the requested result came from a verified
/// index.  The caller can request the bounded filesystem walk explicitly with
/// `--all`.
pub fn discover(context: &RescueContext, limit: usize) -> Result<IndexDiscovery> {
    if limit == 0 {
        bail!("rescue scan --limit must be greater than zero");
    }

    let configured_root = context.root.clone();
    let root = canonical_root(&configured_root)?;
    let max_index_rows = context.max_files.min(MAX_INDEX_ROWS);
    if max_index_rows == 0 {
        bail!("limited rescue scan requires a positive max_files budget");
    }
    // Session roots are resolved lazily-honestly: an absent sessions tree
    // must not preempt coarse index budgets (e.g. SQLite fanout), yet no
    // index row may be accepted without a real root to verify against.
    // Real IO failures (e.g. EACCES) are surfaced instead of being flattened
    // into an empty list that would misreport the cause.
    let roots =
        session_roots(&root).context("limited rescue scan could not verify Codex session roots")?;
    let mut candidates = CandidateAccumulator::new(limit, limit.min(context.max_files));
    let mut sources = Vec::new();

    if read_session_index(&root, context, max_index_rows, |raw| {
        candidates.accept(context, &configured_root, &root, &roots, raw)
    })? {
        sources.push("session-index");
    }

    if read_sqlite_indexes(context, &root, max_index_rows, |raw| {
        candidates.accept(context, &configured_root, &root, &roots, raw)
    })? {
        sources.push("sqlite");
    }

    if sources.is_empty() {
        bail!(
            "limited rescue scan requires a readable Codex index (state SQLite or session_index.jsonl); use rescue scan --all for an explicit filesystem walk"
        );
    }
    candidates.finish(sources.join("+"))
}

fn canonical_root(root: &Path) -> Result<PathBuf> {
    safe_fs::canonical_root(root)
        .with_context(|| "Codex rescue root is unavailable; pass --root to a real Codex home")
}

fn session_roots(root: &Path) -> Result<Vec<PathBuf>> {
    let mut roots = Vec::new();
    for name in ["sessions", "archived_sessions"] {
        let path = root.join(name);
        let metadata = match fs::symlink_metadata(&path) {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
            Err(error) => return Err(error).context("inspect Codex session root"),
        };
        if metadata.file_type().is_symlink() || !metadata.is_dir() {
            continue;
        }
        let canonical = fs::canonicalize(path).context("canonicalize Codex session root")?;
        if canonical.starts_with(root) {
            roots.push(canonical);
        }
    }
    if roots.is_empty() {
        bail!("Codex index is present but no real sessions directory exists");
    }
    Ok(roots)
}

fn verify_index_path(
    context: &RescueContext,
    configured_root: &Path,
    canonical_root: &Path,
    roots: &[PathBuf],
    raw: &str,
) -> Result<SessionRef> {
    if raw.is_empty() || raw.contains('\0') {
        bail!("Codex index contains an invalid rollout path");
    }
    let candidate = if Path::new(raw).is_absolute() {
        PathBuf::from(raw)
    } else {
        configured_root.join(raw)
    };
    let verified = safe_fs::open_regular(configured_root, &candidate, "indexed rollout")
        .context("Codex index references an unavailable rollout")?;
    let canonical = verified.path().to_path_buf();
    if canonical.extension().and_then(|value| value.to_str()) != Some("jsonl") {
        bail!("Codex index references a non-JSONL rollout file");
    }
    if !roots
        .iter()
        .any(|session_root| canonical.starts_with(session_root))
    {
        bail!("Codex index references a rollout outside the session roots");
    }
    let canonical_metadata = verified.metadata().context("stat indexed rollout")?;
    if canonical_metadata.len() > context.max_session_bytes {
        bail!(
            "Codex index references a rollout over the {} byte inspection budget",
            context.max_session_bytes
        );
    }
    verified.ensure_unchanged("indexed rollout")?;
    let relative = canonical
        .strip_prefix(canonical_root)
        .context("indexed rollout is outside the Codex root")?
        .to_string_lossy()
        .replace('\\', "/");
    let modified_unix_secs = canonical_metadata
        .modified()
        .ok()
        .and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|duration| duration.as_secs());
    Ok(SessionRef {
        adapter: "codex".to_string(),
        key: relative.clone(),
        relative_path: relative,
        bytes: canonical_metadata.len(),
        modified_unix_secs,
        source_path: canonical,
    })
}

fn read_session_index(
    root: &Path,
    context: &RescueContext,
    max_index_rows: usize,
    mut consume: impl FnMut(String) -> Result<()>,
) -> Result<bool> {
    let path = root.join(SESSION_INDEX_NAME);
    match fs::symlink_metadata(&path) {
        Ok(_) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(error) => return Err(error).context("inspect Codex session index"),
    }
    let first = safe_fs::read_bounded(
        root,
        &path,
        context.max_session_bytes,
        "Codex session index",
    )?;
    let second = safe_fs::read_bounded(
        root,
        &path,
        context.max_session_bytes,
        "Codex session index",
    )?;
    if first != second {
        bail!("Codex session index changed while being read; retry after the writer stops");
    }
    let mut paths_seen = 0usize;
    for (line_number, raw) in first.split(|byte| *byte == b'\n').enumerate() {
        let raw = raw.strip_suffix(b"\r").unwrap_or(raw);
        if raw.is_empty() {
            continue;
        }
        if raw.len() > context.max_record_bytes {
            bail!(
                "Codex session index record {} exceeds the record budget",
                line_number + 1
            );
        }
        let value: Value = serde_json::from_slice(raw).with_context(|| {
            format!(
                "Codex session index record {} is not valid JSON",
                line_number + 1
            )
        })?;
        for path in extract_paths(&value, 0) {
            paths_seen = paths_seen
                .checked_add(1)
                .context("Codex session index row counter overflow")?;
            if paths_seen > max_index_rows {
                bail!(
                    "Codex session index exceeded the configured {} entry budget",
                    context.max_files
                );
            }
            consume(path)?;
        }
    }
    Ok(true)
}

fn extract_paths(value: &Value, depth: usize) -> Vec<String> {
    if depth > 2 {
        return Vec::new();
    }
    let Some(object) = value.as_object() else {
        return Vec::new();
    };
    let mut paths = Vec::new();
    for key in PATH_COLUMNS {
        if let Some(path) = object
            .get(key)
            .and_then(Value::as_str)
            .filter(|path| !path.is_empty())
        {
            paths.push(path.to_string());
        }
    }
    for key in ["thread", "session", "rollout"] {
        if let Some(nested) = object.get(key) {
            paths.extend(extract_paths(nested, depth + 1));
        }
    }
    paths
}

fn read_sqlite_indexes(
    context: &RescueContext,
    root: &Path,
    max_index_rows: usize,
    mut consume: impl FnMut(String) -> Result<()>,
) -> Result<bool> {
    let max_database_candidates = max_index_rows.min(MAX_SQLITE_DATABASES);
    if max_database_candidates == 0 {
        bail!("limited rescue scan requires a positive SQLite candidate budget");
    }
    let mut candidates = Vec::new();
    for name in SQLITE_NAMES.iter().copied() {
        let path = root.join(name);
        match fs::symlink_metadata(&path) {
            Ok(_) => {
                if candidates.len() >= max_database_candidates {
                    bail!(
                        "Codex SQLite index fanout exceeded the configured {} entry budget",
                        context.max_files
                    );
                }
                candidates.push(path);
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error).context("inspect Codex root for SQLite indexes"),
        }
    }

    // Keep support for provider schema revisions that use a different state
    // filename, but inspect only direct children and only database suffixes.
    // This stays streaming and bounded: a hostile Codex root cannot make us
    // collect an unbounded list of arbitrary database filenames.
    let mut known_names = SQLITE_NAMES
        .iter()
        .map(|name| (*name).to_string())
        .collect::<HashSet<_>>();
    for entry in fs::read_dir(root).context("inspect Codex root for SQLite indexes")? {
        let entry = entry.context("inspect Codex root for SQLite indexes")?;
        let path = entry.path();
        let Some(name) = path.file_name().and_then(|value| value.to_str()) else {
            continue;
        };
        let lower = name.to_ascii_lowercase();
        if (lower.ends_with(".sqlite") || lower.ends_with(".sqlite3") || lower.ends_with(".db"))
            && known_names.insert(name.to_string())
        {
            if candidates.len() >= max_database_candidates {
                bail!(
                    "Codex SQLite index fanout exceeded the configured {} entry budget",
                    context.max_files
                );
            }
            candidates.push(path);
        }
    }

    // Preflight every bounded candidate before opening any SQLite connection.
    // This makes the aggregate byte budget meaningful even when several state
    // databases are present: one large file cannot consume the full budget
    // and leave later candidates unchecked.
    let mut verified_candidates = Vec::with_capacity(candidates.len());
    let mut sqlite_total_bytes = 0u64;
    for path in candidates {
        let metadata = match fs::symlink_metadata(&path) {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
            Err(error) => return Err(error).context("inspect Codex SQLite index"),
        };
        if metadata.file_type().is_symlink() || !metadata.is_file() {
            bail!("Codex SQLite index is not a regular file");
        }
        #[cfg(unix)]
        if metadata.nlink() != 1 {
            bail!("Codex SQLite index must not be hardlinked");
        }
        sqlite_total_bytes = sqlite_total_bytes
            .checked_add(metadata.len())
            .context("Codex SQLite index byte counter overflow")?;
        if sqlite_total_bytes > context.max_total_bytes {
            bail!(
                "Codex SQLite indexes exceed the aggregate {} byte budget",
                context.max_total_bytes
            );
        }
        let canonical = safe_fs::canonical_regular_path(root, &path, "Codex SQLite index")?;
        verified_candidates.push(canonical);
    }

    let mut found = false;
    for path in verified_candidates {
        found = true;
        let connection = safe_fs::open_sqlite_read_only(root, &path, "Codex SQLite index")?;
        let tables = table_names(&connection)?;
        if !tables.iter().any(|table| table == "threads") {
            continue;
        }
        let columns = table_columns(&connection, "threads")?;
        let Some(path_column) = PATH_COLUMNS.iter().find(|name| columns.contains(**name)) else {
            continue;
        };
        let sql = format!(
            "SELECT {} FROM \"threads\" LIMIT {}",
            quote_identifier(path_column),
            max_index_rows + 1
        );
        let mut statement = connection
            .prepare(&sql)
            .context("read Codex SQLite rollout index")?;
        let rows = statement
            .query_map([], |row| row.get_ref(0).map(value_text))
            .context("read Codex SQLite rollout index")?;
        let mut local_count = 0usize;
        for row in rows {
            local_count = local_count
                .checked_add(1)
                .context("Codex SQLite index row counter overflow")?;
            if local_count > max_index_rows {
                bail!(
                    "Codex SQLite index exceeded the configured {} entry budget",
                    context.max_files
                );
            }
            if let Some(path) = row
                .context("read Codex SQLite rollout path")?
                .filter(|path| !path.is_empty())
            {
                consume(path)?;
            }
        }
    }
    Ok(found)
}

fn table_names(connection: &Connection) -> Result<Vec<String>> {
    let mut statement = connection
        .prepare("SELECT name FROM sqlite_schema WHERE type='table'")
        .context("read Codex SQLite schema")?;
    let rows = statement
        .query_map([], |row| {
            let value = row.get_ref(0)?;
            Ok(bounded_text_value(value))
        })
        .context("read Codex SQLite schema")?;
    let mut names = Vec::new();
    let mut rows_seen = 0usize;
    for row in rows {
        rows_seen = rows_seen
            .checked_add(1)
            .context("Codex SQLite schema row counter overflow")?;
        if rows_seen > MAX_INDEX_ROWS {
            bail!("Codex SQLite schema exceeded the configured row budget");
        }
        if let Some(value) = row.context("read Codex SQLite schema")? {
            names.push(value);
        }
    }
    Ok(names)
}

fn table_columns(connection: &Connection, table: &str) -> Result<HashSet<String>> {
    let sql = format!("PRAGMA table_info({})", quote_identifier(table));
    let mut statement = connection
        .prepare(&sql)
        .context("read Codex SQLite table schema")?;
    let rows = statement
        .query_map([], |row| {
            let value = row.get_ref(1)?;
            Ok(bounded_text_value(value))
        })
        .context("read Codex SQLite table schema")?;
    let mut columns = HashSet::new();
    let mut rows_seen = 0usize;
    for row in rows {
        rows_seen = rows_seen
            .checked_add(1)
            .context("Codex SQLite table schema row counter overflow")?;
        if rows_seen > MAX_INDEX_ROWS {
            bail!("Codex SQLite table schema exceeded the configured row budget");
        }
        if let Some(value) = row.context("read Codex SQLite table schema")? {
            columns.insert(value);
        }
    }
    Ok(columns)
}

fn quote_identifier(value: &str) -> String {
    format!("\"{}\"", value.replace('"', "\"\""))
}

fn value_text(value: ValueRef<'_>) -> Option<String> {
    match value {
        ValueRef::Text(value) if value.len() <= MAX_SQLITE_CELL_BYTES => {
            std::str::from_utf8(value).ok().map(ToOwned::to_owned)
        }
        ValueRef::Text(_) => None,
        ValueRef::Integer(value) => Some(value.to_string()),
        ValueRef::Real(value) => Some(value.to_string()),
        ValueRef::Null | ValueRef::Blob(_) => None,
    }
}

fn bounded_text_value(value: ValueRef<'_>) -> Option<String> {
    let ValueRef::Text(value) = value else {
        return None;
    };
    if value.len() > MAX_SQLITE_CELL_BYTES {
        return None;
    }
    std::str::from_utf8(value).ok().map(ToOwned::to_owned)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};

    static NEXT_TEMP_ROOT: AtomicU64 = AtomicU64::new(0);

    struct TempRoot(PathBuf);

    impl TempRoot {
        fn new(tag: &str) -> Self {
            let nonce = NEXT_TEMP_ROOT.fetch_add(1, Ordering::Relaxed);
            let path = std::env::temp_dir().join(format!(
                "vetto-index-test-{tag}-{}-{nonce}",
                std::process::id()
            ));
            fs::create_dir_all(&path).expect("create temp root");
            Self(path)
        }

        fn codex_home(&self) -> PathBuf {
            self.0.join("codex-home")
        }
    }

    impl Drop for TempRoot {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    fn rollout(root: &Path, name: &str) -> PathBuf {
        let path = root.join("sessions").join(name);
        fs::create_dir_all(path.parent().expect("rollout parent")).expect("rollout parent");
        fs::write(&path, b"{\"type\":\"turn\"}\n").expect("rollout");
        path
    }

    fn sqlite_index(root: &Path, paths: &[&Path]) {
        let path = root.join("state_5.sqlite");
        let connection = Connection::open(&path).expect("create SQLite fixture");
        connection
            .execute(
                "CREATE TABLE threads (id TEXT PRIMARY KEY, rollout_path TEXT)",
                [],
            )
            .expect("create threads table");
        for (index, rollout) in paths.iter().enumerate() {
            connection
                .execute(
                    "INSERT INTO threads (id, rollout_path) VALUES (?1, ?2)",
                    rusqlite::params![index.to_string(), rollout.to_string_lossy().to_string()],
                )
                .expect("insert index row");
        }
    }

    #[test]
    fn sqlite_index_verifies_candidates_without_walking_unindexed_files() {
        let temp = TempRoot::new("sqlite");
        let root = temp.codex_home();
        let indexed = rollout(&root, "indexed.jsonl");
        let unindexed = rollout(&root, "unindexed.jsonl");
        sqlite_index(&root, &[&indexed]);

        let result = discover(&RescueContext::new(root), 10).expect("index discovery");
        assert_eq!(result.source, "sqlite");
        assert_eq!(result.candidate_count, 1);
        assert!(!result.truncated);
        assert_eq!(
            result.sessions[0].source_path,
            fs::canonicalize(indexed).unwrap()
        );
        assert_ne!(
            result.sessions[0].source_path,
            fs::canonicalize(unindexed).unwrap()
        );
    }

    #[test]
    fn explicit_limit_is_reported_as_truncation() {
        let temp = TempRoot::new("limit");
        let root = temp.codex_home();
        let first = rollout(&root, "first.jsonl");
        let second = rollout(&root, "second.jsonl");
        sqlite_index(&root, &[&first, &second]);

        let result = discover(&RescueContext::new(root), 1).expect("limited discovery");
        assert_eq!(result.candidate_count, 2);
        assert_eq!(result.sessions.len(), 1);
        assert!(result.truncated);
    }

    #[test]
    fn index_rows_respect_the_context_file_budget() {
        let temp = TempRoot::new("max-files");
        let root = temp.codex_home();
        let first = rollout(&root, "first.jsonl");
        let second = rollout(&root, "second.jsonl");
        sqlite_index(&root, &[&first, &second]);
        let mut context = RescueContext::new(root);
        context.max_files = 1;

        let error = discover(&context, 10).expect_err("index row budget");
        assert!(error.to_string().contains("entry budget"), "{error:#}");
    }

    #[test]
    fn sqlite_size_is_rejected_before_the_read_only_open() {
        let temp = TempRoot::new("sqlite-size");
        let root = temp.codex_home();
        let indexed = rollout(&root, "indexed.jsonl");
        sqlite_index(&root, &[&indexed]);
        let mut context = RescueContext::new(root);
        context.max_total_bytes = 1;

        let error = discover(&context, 10).expect_err("oversized SQLite index");
        assert!(
            error.to_string().contains("SQLite") && error.to_string().contains("byte budget"),
            "{error:#}"
        );
    }

    #[test]
    fn aggregate_sqlite_size_is_checked_across_candidates_before_opening() {
        let temp = TempRoot::new("sqlite-aggregate-size");
        let root = temp.codex_home();
        let indexed = rollout(&root, "indexed.jsonl");
        sqlite_index(&root, &[&indexed]);
        let first_db = root.join("state_5.sqlite");
        let second_db = root.join("state.sqlite");
        fs::copy(&first_db, &second_db).expect("copy second SQLite index");
        let first_size = fs::metadata(&first_db)
            .expect("first SQLite metadata")
            .len();
        let second_size = fs::metadata(&second_db)
            .expect("second SQLite metadata")
            .len();
        let mut context = RescueContext::new(root);
        context.max_total_bytes = first_size
            .checked_add(second_size)
            .expect("fixture byte sum")
            .saturating_sub(1);

        let error = discover(&context, 10).expect_err("aggregate SQLite size");
        assert!(
            error.to_string().contains("aggregate") && error.to_string().contains("SQLite indexes"),
            "{error:#}"
        );
    }

    #[test]
    fn sqlite_database_fanout_is_bounded_before_opening_each_candidate() {
        let temp = TempRoot::new("sqlite-fanout");
        let root = temp.codex_home();
        fs::create_dir_all(&root).expect("Codex root");
        // Limited scans now require verifiable session roots before index
        // rows are accepted; give the fixture one so the fanout budget is
        // what actually fails.
        fs::create_dir_all(root.join("sessions")).expect("sessions directory");
        fs::write(root.join("a.sqlite"), b"").expect("first database candidate");
        fs::write(root.join("b.sqlite"), b"").expect("second database candidate");
        let mut context = RescueContext::new(root);
        context.max_files = 1;

        let error = discover(&context, 10).expect_err("SQLite fanout budget");
        assert!(
            error.to_string().contains("fanout") || error.to_string().contains("SQLite index"),
            "{error:#}"
        );
    }

    #[test]
    fn stale_index_fails_closed() {
        let temp = TempRoot::new("stale");
        let root = temp.codex_home();
        fs::create_dir_all(root.join("sessions")).expect("sessions");
        sqlite_index(&root, &[&root.join("sessions/missing.jsonl")]);

        let error = discover(&RescueContext::new(root), 10).expect_err("stale index");
        assert!(
            error.to_string().contains("unavailable") || error.to_string().contains("rollout"),
            "{error:#}"
        );
    }

    #[test]
    fn limited_scan_does_not_fallback_to_the_filesystem() {
        let temp = TempRoot::new("no-index");
        let root = temp.codex_home();
        let _session = rollout(&root, "filesystem-only.jsonl");

        let error = discover(&RescueContext::new(root), 10).expect_err("missing index");
        assert!(error
            .to_string()
            .contains("requires a readable Codex index"));
    }

    #[test]
    fn session_index_is_supported_and_is_read_twice() {
        let temp = TempRoot::new("jsonl");
        let root = temp.codex_home();
        let indexed = rollout(&root, "indexed.jsonl");
        fs::create_dir_all(&root).expect("codex root");
        fs::write(
            root.join(SESSION_INDEX_NAME),
            format!(
                "{}\n",
                serde_json::json!({ "rollout_path": indexed.to_string_lossy() })
            ),
        )
        .expect("session index");

        let result = discover(&RescueContext::new(root), 10).expect("session index discovery");
        assert_eq!(result.source, "session-index");
        assert_eq!(result.sessions.len(), 1);
    }

    #[test]
    fn session_index_rows_respect_the_context_file_budget() {
        let temp = TempRoot::new("session-index-max-files");
        let root = temp.codex_home();
        let first = rollout(&root, "first.jsonl");
        let second = rollout(&root, "second.jsonl");
        fs::write(
            root.join(SESSION_INDEX_NAME),
            format!(
                "{}\n{}\n",
                serde_json::json!({ "rollout_path": first.to_string_lossy() }),
                serde_json::json!({ "rollout_path": second.to_string_lossy() })
            ),
        )
        .expect("session index");
        let mut context = RescueContext::new(root);
        context.max_files = 1;

        let error = discover(&context, 10).expect_err("session index row budget");
        assert!(error.to_string().contains("entry budget"), "{error:#}");
    }

    #[cfg(unix)]
    #[test]
    fn hardlinked_session_index_is_rejected() {
        let temp = TempRoot::new("session-index-hardlink");
        let root = temp.codex_home();
        let indexed = rollout(&root, "indexed.jsonl");
        let index = root.join(SESSION_INDEX_NAME);
        fs::write(
            &index,
            format!("{{\"rollout_path\":\"{}\"}}\n", indexed.to_string_lossy()),
        )
        .expect("session index");
        fs::hard_link(&index, root.join("session-index-alias.jsonl")).expect("hardlink index");

        let error = discover(&RescueContext::new(root), 10).expect_err("hardlinked index");
        assert!(error.to_string().contains("hardlinked"), "{error:#}");
    }

    #[cfg(unix)]
    #[test]
    fn hardlinked_sqlite_index_is_rejected() {
        let temp = TempRoot::new("sqlite-hardlink");
        let root = temp.codex_home();
        let indexed = rollout(&root, "indexed.jsonl");
        sqlite_index(&root, &[&indexed]);
        fs::hard_link(root.join("state_5.sqlite"), root.join("state-alias.sqlite"))
            .expect("hardlink SQLite index");

        let error = discover(&RescueContext::new(root), 10).expect_err("hardlinked SQLite");
        assert!(error.to_string().contains("hardlinked"), "{error:#}");
    }
}