codex-recall 0.1.3

Local search and recall for Codex session JSONL archives
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
use crate::commands::date::resolve_date_window;
use crate::commands::exclude::resolve_excluded_sessions;
use crate::commands::kind::{event_kinds, KindArg};
use crate::config::default_db_path;
use crate::output::{compact_whitespace, now_timestamp, preview, shell_quote};
use crate::store::{source_priority_for_path, SearchOptions, SearchResult, SearchTrace, Store};
use anyhow::{bail, Result};
use clap::Args;
use serde_json::json;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Args)]
pub struct SearchArgs {
    #[arg(help = "Search terms")]
    pub query: String,
    #[arg(long, help = "SQLite index path")]
    pub db: Option<PathBuf>,
    #[arg(long, default_value_t = 10, help = "Maximum sessions to print")]
    pub limit: usize,
    #[arg(long, help = "Restrict matches to a repo name")]
    pub repo: Option<String>,
    #[arg(long, help = "Search across all repos instead of auto-filtering")]
    pub all_repos: bool,
    #[arg(long, help = "Restrict matches to sessions under this cwd")]
    pub cwd: Option<String>,
    #[arg(long, help = "Restrict by age, for example 7d, today, or 2026-04-01")]
    pub since: Option<String>,
    #[arg(long, help = "Restrict to sessions at or after this date/time")]
    pub from: Option<String>,
    #[arg(long, help = "Restrict to sessions before this date/time")]
    pub until: Option<String>,
    #[arg(long, help = "Restrict to one local calendar day, YYYY-MM-DD")]
    pub day: Option<String>,
    #[arg(
        long = "kind",
        value_enum,
        value_name = "KIND",
        help = "Restrict matches by event kind; repeatable"
    )]
    pub kinds: Vec<KindArg>,
    #[arg(long, help = "Include duplicate active/archive copies")]
    pub include_duplicates: bool,
    #[arg(
        long = "exclude-session",
        help = "Exclude a session id or session key; repeatable"
    )]
    pub exclude_sessions: Vec<String>,
    #[arg(long, help = "Exclude the current Codex session from results")]
    pub exclude_current: bool,
    #[arg(long, help = "Emit machine-readable JSON")]
    pub json: bool,
    #[arg(long, help = "Include retrieval trace fields in JSON output")]
    pub trace: bool,
}

#[derive(Debug, Clone, Args)]
pub struct BundleArgs {
    #[arg(help = "Search terms")]
    pub query: String,
    #[arg(long, help = "SQLite index path")]
    pub db: Option<PathBuf>,
    #[arg(long, default_value_t = 5, help = "Maximum sessions to include")]
    pub limit: usize,
    #[arg(long, help = "Restrict matches to a repo name")]
    pub repo: Option<String>,
    #[arg(long, help = "Search across all repos instead of auto-filtering")]
    pub all_repos: bool,
    #[arg(long, help = "Restrict matches to sessions under this cwd")]
    pub cwd: Option<String>,
    #[arg(long, help = "Restrict by age, for example 7d, today, or 2026-04-01")]
    pub since: Option<String>,
    #[arg(long, help = "Restrict to sessions at or after this date/time")]
    pub from: Option<String>,
    #[arg(long, help = "Restrict to sessions before this date/time")]
    pub until: Option<String>,
    #[arg(long, help = "Restrict to one local calendar day, YYYY-MM-DD")]
    pub day: Option<String>,
    #[arg(
        long = "kind",
        value_enum,
        value_name = "KIND",
        help = "Restrict matches by event kind; repeatable"
    )]
    pub kinds: Vec<KindArg>,
    #[arg(long, help = "Include duplicate active/archive copies")]
    pub include_duplicates: bool,
    #[arg(
        long = "exclude-session",
        help = "Exclude a session id or session key; repeatable"
    )]
    pub exclude_sessions: Vec<String>,
    #[arg(long, help = "Exclude the current Codex session from results")]
    pub exclude_current: bool,
}

#[derive(Debug, Clone, Args)]
pub struct ShowArgs {
    #[arg(help = "Session id or session key")]
    pub session_ref: String,
    #[arg(long, help = "SQLite index path")]
    pub db: Option<PathBuf>,
    #[arg(long, default_value_t = 80, help = "Maximum events to print")]
    pub limit: usize,
    #[arg(
        long = "kind",
        value_enum,
        value_name = "KIND",
        help = "Restrict events by kind; repeatable"
    )]
    pub kinds: Vec<KindArg>,
    #[arg(long, help = "Emit machine-readable JSON")]
    pub json: bool,
}

pub fn run_search(args: SearchArgs) -> Result<()> {
    let db_path = args.db.unwrap_or(default_db_path()?);
    let store = Store::open_readonly(&db_path)?;
    let (since, from, until) = resolve_date_window(args.since, args.from, args.until, args.day)?;
    let exclude_sessions = resolve_excluded_sessions(args.exclude_sessions, args.exclude_current)?;
    let kinds = event_kinds(&args.kinds);
    let current_repo = if args.repo.is_none() && !args.all_repos {
        detect_current_repo()
    } else {
        None
    };
    let search_limit = if args.json {
        args.limit
    } else {
        args.limit.saturating_mul(5)
    };
    let (trace, results) = store.search_with_trace(SearchOptions {
        query: args.query.clone(),
        limit: search_limit,
        repo: args.repo,
        cwd: args.cwd,
        since,
        from,
        until,
        include_duplicates: args.include_duplicates,
        exclude_sessions,
        kinds,
        current_repo,
    })?;
    if args.json {
        print_search_json(&args.query, &results, &trace, args.trace)?;
        return Ok(());
    }

    if results.is_empty() {
        println!("no matches");
        return Ok(());
    }

    print_grouped_search_results(&results, args.limit);
    Ok(())
}

pub fn run_bundle(args: BundleArgs) -> Result<()> {
    let db_path = args.db.unwrap_or(default_db_path()?);
    let store = Store::open_readonly(&db_path)?;
    let (since, from, until) = resolve_date_window(args.since, args.from, args.until, args.day)?;
    let exclude_sessions = resolve_excluded_sessions(args.exclude_sessions, args.exclude_current)?;
    let kinds = event_kinds(&args.kinds);
    let current_repo = if args.repo.is_none() && !args.all_repos {
        detect_current_repo()
    } else {
        None
    };
    let results = store.search_with_options(SearchOptions {
        query: args.query.clone(),
        limit: args.limit.saturating_mul(5).max(args.limit),
        repo: args.repo.clone(),
        cwd: args.cwd.clone(),
        since: since.clone(),
        from: from.clone(),
        until: until.clone(),
        include_duplicates: args.include_duplicates,
        exclude_sessions: exclude_sessions.clone(),
        kinds: kinds.clone(),
        current_repo,
    })?;

    let filters = BundleFilters {
        repo: &args.repo,
        cwd: &args.cwd,
        since: &since,
        from: &from,
        until: &until,
        kinds: &args.kinds,
        include_duplicates: args.include_duplicates,
        exclude_sessions: &exclude_sessions,
    };
    print_bundle(&args.query, &db_path, args.limit, filters, &results);
    Ok(())
}

pub fn run_show(args: ShowArgs) -> Result<()> {
    let db_path = args.db.unwrap_or(default_db_path()?);
    let store = Store::open_readonly(&db_path)?;
    let matches = store.resolve_session_reference(&args.session_ref)?;
    if matches.is_empty() {
        println!("no indexed events for {}", args.session_ref);
        return Ok(());
    }
    if matches.len() > 1 {
        let choices = matches
            .iter()
            .map(|session| {
                format!(
                    "  {}  {}  {}",
                    session.session_key,
                    session.cwd,
                    session.source_file_path.display()
                )
            })
            .collect::<Vec<_>>()
            .join("\n");
        bail!(
            "multiple indexed sessions match `{}`; use one session_key:\n{choices}",
            args.session_ref
        );
    }

    let session = &matches[0];
    let kinds = event_kinds(&args.kinds);
    let events = store.session_events_with_kinds(&session.session_key, args.limit, &kinds)?;
    if events.is_empty() {
        println!("no indexed events for {}", args.session_ref);
        return Ok(());
    }
    if args.json {
        print_show_json(session, &events)?;
        return Ok(());
    }

    println!("{}  {}", session.session_key, session.session_id);
    println!("{}", events[0].cwd);
    for event in events {
        println!(
            "\n{}  {}:{}",
            event.kind.as_str(),
            event.source_file_path.display(),
            event.source_line_number
        );
        println!("{}", preview(&event.text, 900));
    }

    Ok(())
}

fn print_grouped_search_results(results: &[SearchResult], limit: usize) {
    let mut session_order = Vec::<&str>::new();
    for result in results {
        if !session_order
            .iter()
            .any(|session_id| *session_id == result.session_key)
        {
            session_order.push(&result.session_key);
        }
        if session_order.len() == limit {
            break;
        }
    }

    for (index, session_id) in session_order.iter().enumerate() {
        let session_results = results
            .iter()
            .filter(|result| &result.session_key == session_id)
            .collect::<Vec<_>>();
        let first = session_results[0];
        println!(
            "{}. {}  {}  {}",
            index + 1,
            first.session_key,
            first.session_id,
            first.cwd
        );
        for result in session_results.iter().take(3) {
            println!(
                "   - {}  {}:{}",
                result.kind.as_str(),
                result.source_file_path.display(),
                result.source_line_number
            );
            println!("     {}", compact_whitespace(&result.snippet));
        }
    }
}

struct BundleFilters<'a> {
    repo: &'a Option<String>,
    cwd: &'a Option<String>,
    since: &'a Option<String>,
    from: &'a Option<String>,
    until: &'a Option<String>,
    kinds: &'a [KindArg],
    include_duplicates: bool,
    exclude_sessions: &'a [String],
}

fn print_bundle(
    query: &str,
    db_path: &Path,
    limit: usize,
    filters: BundleFilters<'_>,
    results: &[SearchResult],
) {
    println!("# codex-recall bundle");
    println!();
    println!("Query: {query}");
    println!("Database: {}", db_path.display());
    let filter_labels = bundle_filters(filters);
    if !filter_labels.is_empty() {
        println!("Filters: {}", filter_labels.join(", "));
    }
    println!("Generated: {}", now_timestamp());

    if results.is_empty() {
        println!();
        println!("No matches.");
        return;
    }

    let session_keys = top_session_keys(results, limit);
    println!();
    println!("## Top Sessions");
    for (index, session_key) in session_keys.iter().enumerate() {
        let session_results = results
            .iter()
            .filter(|result| &result.session_key == session_key)
            .collect::<Vec<_>>();
        let first = session_results[0];
        println!(
            "{}. {}  {}  {}",
            index + 1,
            first.session_key,
            first.session_id,
            first.cwd
        );
        println!("   when: {}", first.session_timestamp);
        println!(
            "   show: codex-recall show {} --limit 120",
            shell_quote(&first.session_key)
        );
        println!("   receipts: {}", session_results.len().min(3));
    }

    println!();
    println!("## Receipts");
    for session_key in &session_keys {
        println!();
        println!("### {session_key}");
        for result in results
            .iter()
            .filter(|result| &result.session_key == session_key)
            .take(3)
        {
            println!(
                "- {}  {}:{}",
                result.kind.as_str(),
                result.source_file_path.display(),
                result.source_line_number
            );
            println!("  {}", preview(&result.text, 500));
        }
    }

    println!();
    println!("## Next Commands");
    for session_key in session_keys {
        println!(
            "- codex-recall show {} --limit 120",
            shell_quote(session_key)
        );
    }
}

fn bundle_filters(filters: BundleFilters<'_>) -> Vec<String> {
    let mut labels = Vec::new();
    if let Some(repo) = filters.repo {
        labels.push(format!("repo={repo}"));
    }
    if let Some(cwd) = filters.cwd {
        labels.push(format!("cwd={cwd}"));
    }
    if let Some(since) = filters.since {
        labels.push(format!("since={since}"));
    }
    if let Some(from) = filters.from {
        labels.push(format!("from={from}"));
    }
    if let Some(until) = filters.until {
        labels.push(format!("until={until}"));
    }
    for kind in filters.kinds {
        labels.push(format!("kind={}", kind.as_str()));
    }
    if filters.include_duplicates {
        labels.push("include-duplicates=true".to_owned());
    }
    for excluded_session in filters.exclude_sessions {
        labels.push(format!("exclude-session={excluded_session}"));
    }
    labels
}

fn top_session_keys(results: &[SearchResult], limit: usize) -> Vec<&str> {
    let mut session_keys = Vec::<&str>::new();
    for result in results {
        if !session_keys
            .iter()
            .any(|session_key| *session_key == result.session_key)
        {
            session_keys.push(&result.session_key);
        }
        if session_keys.len() == limit {
            break;
        }
    }
    session_keys
}

fn print_show_json(
    session: &crate::store::SessionMatch,
    events: &[crate::store::SessionEvent],
) -> Result<()> {
    let events = events
        .iter()
        .map(|event| {
            let source = format!(
                "{}:{}",
                event.source_file_path.display(),
                event.source_line_number
            );
            json!({
                "kind": event.kind.as_str(),
                "text": event.text,
                "cwd": event.cwd,
                "source_file_path": event.source_file_path,
                "source_line_number": event.source_line_number,
                "source": source,
                "source_timestamp": event.source_timestamp,
            })
        })
        .collect::<Vec<_>>();

    let value = json!({
        "session_key": session.session_key,
        "session_id": session.session_id,
        "repo": session.repo,
        "cwd": session.cwd,
        "source_file_path": session.source_file_path,
        "count": events.len(),
        "events": events,
    });
    println!("{}", serde_json::to_string_pretty(&value)?);
    Ok(())
}

fn print_search_json(
    query: &str,
    results: &[SearchResult],
    trace: &SearchTrace,
    include_trace: bool,
) -> Result<()> {
    let results = results
        .iter()
        .map(|result| {
            let source = format!(
                "{}:{}",
                result.source_file_path.display(),
                result.source_line_number
            );
            let mut value = json!({
                "session_key": result.session_key,
                "session_id": result.session_id,
                "repo": result.repo,
                "kind": result.kind.as_str(),
                "cwd": result.cwd,
                "session_timestamp": result.session_timestamp,
                "source_file_path": result.source_file_path,
                "source_line_number": result.source_line_number,
                "source": source,
                "source_timestamp": result.source_timestamp,
                "score": result.score,
                "snippet": compact_whitespace(&result.snippet),
                "text_preview": preview(&result.text, 500),
            });
            if include_trace {
                value["trace"] = json!({
                    "match_strategy": trace.match_strategy.as_str(),
                    "repo_matches_current": result.repo_matches_current,
                    "session_hit_count": result.session_hit_count,
                    "best_kind_weight": result.best_kind_weight,
                    "fts_score": result.score,
                    "source_priority": source_priority_for_path(&result.source_file_path),
                    "duplicate_session_id": result.session_id.as_str(),
                });
            }
            value
        })
        .collect::<Vec<_>>();

    let mut value = json!({
        "query": query,
        "match_strategy": trace.match_strategy.as_str(),
        "count": results.len(),
        "results": results,
    });
    if include_trace {
        value["trace"] = json!({
            "match_strategy": trace.match_strategy.as_str(),
            "query_terms": &trace.query_terms,
            "fts_query": trace.fts_query.as_str(),
            "fetch_limit": trace.fetch_limit,
            "current_repo": &trace.current_repo,
            "include_duplicates": trace.include_duplicates,
        });
    }
    println!("{}", serde_json::to_string_pretty(&value)?);
    Ok(())
}

fn detect_current_repo() -> Option<String> {
    let mut path = std::env::current_dir().ok()?;
    loop {
        if path.join(".git").exists() {
            return path
                .file_name()
                .and_then(|name| name.to_str())
                .map(str::to_owned);
        }
        if !path.pop() {
            return None;
        }
    }
}