nabu-core 0.1.3

Core storage, indexing, and search for nabu: append-only JSONL capture and a rebuildable SQLite FTS5 index for coding-agent history.
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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//! History search: lexical FTS, hybrid/auto dispatch, reciprocal-rank fusion,
//! snippet/term helpers, and result hydration. The git corroboration engine is
//! the `corroborate` submodule; the feature-gated vector-read path stays in
//! lib.rs (the semantic module, final phase) and is reached via `crate::`.

pub(crate) mod corroborate;

use crate::{
    expand_query_terms, native_jsonl_line_command, normalize_date_or_duration, open_index,
    open_raw_offset_reader, raw_envelope_for_line_scan, read_raw_envelope_at_offset,
    resolved_payload_for_envelope, semantic_search_available, sha256_hex, vector_search_results,
    Error, RankedSearchResult, Result, SearchContinuation, SearchMode, SearchOptions, SearchPage,
    SearchResult, Tool, MAX_SEARCH_LIMIT, MAX_SEARCH_SNIPPET_CHARS,
};
pub(crate) use corroborate::corroborate_text;
use rusqlite::params_from_iter;
use rusqlite::types::Value as SqlValue;
use rusqlite::Connection;
use serde_json::Value;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::str::FromStr;

pub fn search_history(home: &Path, query: &str, limit: usize) -> Result<Vec<SearchResult>> {
    search_history_filtered(
        home,
        query,
        SearchOptions {
            limit,
            ..SearchOptions::default()
        },
    )
}

pub fn search_history_filtered(
    home: &Path,
    query: &str,
    options: SearchOptions,
) -> Result<Vec<SearchResult>> {
    Ok(search_history_page(home, query, options)?.results)
}

pub fn search_history_page(home: &Path, query: &str, options: SearchOptions) -> Result<SearchPage> {
    if query.trim().is_empty() {
        return Err(Error::Validation("query must not be empty".to_string()));
    }
    let mode_requested = options.mode;
    let semantic_available = semantic_search_available(home);
    let mut mode_applied = match mode_requested {
        SearchMode::Auto if semantic_available => SearchMode::Hybrid,
        SearchMode::Auto => SearchMode::Lexical,
        SearchMode::Lexical => SearchMode::Lexical,
        SearchMode::Hybrid if semantic_available => SearchMode::Hybrid,
        SearchMode::Hybrid => {
            return Err(Error::SemanticUnavailable(
                "local embedding model and vector index are not available; run lexical mode or install the semantic model explicitly".to_string(),
            ))
        }
    };
    if mode_applied == SearchMode::Hybrid {
        match search_history_hybrid_page(home, query, options.clone(), semantic_available) {
            Ok(page) => return Ok(page),
            Err(Error::SemanticUnavailable(_)) if mode_requested == SearchMode::Auto => {
                mode_applied = SearchMode::Lexical;
            }
            Err(error) => return Err(error),
        }
    }
    let query_terms = effective_search_terms(query, options.expand_concepts)?;
    let fts_query = quoted_fts_terms(&query_terms);
    let limit = options.limit.clamp(1, MAX_SEARCH_LIMIT);
    let offset = options.offset;
    let max_snippet_chars = options.max_snippet_chars.clamp(1, MAX_SEARCH_SNIPPET_CHARS);
    let raw_fetch_limit = search_overfetch_limit(offset, limit);
    let (results, has_more_raw_rows) = lexical_search_ranked_results(
        home,
        &options,
        &query_terms,
        &fts_query,
        raw_fetch_limit,
        max_snippet_chars,
    )?;

    finalize_search_page(
        &options,
        SearchPageAssembly {
            results,
            has_more_raw_rows,
            mode_requested,
            mode_applied,
            semantic_available,
            limit,
            offset,
            max_snippet_chars,
        },
    )
}

/// Ranked results plus the pagination facts a page needs before its shared
/// finalization. Both the lexical and hybrid paths produce one of these; the
/// only path-specific inputs are `mode_applied` and the ranked list itself.
pub(crate) struct SearchPageAssembly {
    pub(crate) results: Vec<RankedSearchResult>,
    /// The ranked list was overfetch-truncated (more matching rows exist than
    /// were retrieved), so the total is unknown and `total_estimated` is `None`.
    pub(crate) has_more_raw_rows: bool,
    pub(crate) mode_requested: SearchMode,
    pub(crate) mode_applied: SearchMode,
    pub(crate) semantic_available: bool,
    pub(crate) limit: usize,
    pub(crate) offset: usize,
    pub(crate) max_snippet_chars: usize,
}

/// Shared page assembly for every search path: dedupe, total-estimate
/// semantics, window slicing, payload hydration, corroboration, and the
/// pagination cursor. Extracting this keeps the lexical and hybrid paths from
/// drifting — every result path applies the same dedupe/total/corroboration
/// rules, so citation completeness and `--corroborate` behave identically.
fn finalize_search_page(
    options: &SearchOptions,
    assembly: SearchPageAssembly,
) -> Result<SearchPage> {
    let SearchPageAssembly {
        mut results,
        has_more_raw_rows,
        mode_requested,
        mode_applied,
        semantic_available,
        limit,
        offset,
        max_snippet_chars,
    } = assembly;

    if options.dedupe {
        results = dedupe_ranked_search_results(results)?;
    }

    let total_estimated = if has_more_raw_rows {
        None
    } else {
        Some(results.len())
    };
    let has_more_logical_rows = results.len() > offset.saturating_add(limit);
    let mut page_results = results
        .into_iter()
        .skip(offset)
        .take(limit)
        .map(|ranked| ranked.result)
        .collect::<Vec<_>>();
    if options.include_payload {
        hydrate_search_result_payloads(&mut page_results)?;
    }
    if options.corroborate {
        annotate_search_results_with_corroboration(&mut page_results);
    }
    let returned = page_results.len();
    let continuation = if returned > 0 && (has_more_raw_rows || has_more_logical_rows) {
        Some(SearchContinuation {
            next_offset: offset.saturating_add(returned),
        })
    } else {
        None
    };

    Ok(SearchPage {
        results: page_results,
        truncated: continuation.is_some(),
        returned,
        total_estimated,
        continuation,
        mode_requested,
        mode_applied,
        semantic_available,
        limit_applied: limit,
        offset_applied: offset,
        max_snippet_chars_applied: max_snippet_chars,
        include_payload: options.include_payload,
        include_deltas: options.include_deltas,
        dedupe: options.dedupe,
        expand_concepts: options.expand_concepts,
    })
}

/// How a `ref=` search filter compares against the stored `event_refs` rows.
pub(crate) struct RefFilterMatch {
    /// `pr` or `commit`.
    pub(crate) kind: &'static str,
    /// A `LIKE` pattern (with `\` as the escape character) applied to
    /// `event_refs.ref_value`.
    pub(crate) value_pattern: String,
}

/// Resolve a raw `ref=` filter string into the `event_refs` row it should match.
///
/// PR forms (`#54`, `54`, `PR #54`, `org/repo#54`) normalize to an exact match
/// on the `pr` kind value `#54`. A bare hex token is treated as a `commit` SHA
/// and matched by case-insensitive prefix (`abc123` matches `abc123def...`), so
/// abbreviated SHAs resolve the way they are written in transcripts. Any `%`/`_`
/// in the input is escaped so it cannot act as a wildcard.
pub(crate) fn normalize_ref_filter(raw: &str) -> RefFilterMatch {
    let trimmed = raw.trim();
    let pr_digits = trimmed
        .strip_prefix('#')
        .or_else(|| trimmed.rsplit_once('#').map(|(_, tail)| tail))
        .map(str::trim)
        .filter(|tail| !tail.is_empty() && tail.bytes().all(|byte| byte.is_ascii_digit()));
    if let Some(digits) = pr_digits.or_else(|| {
        // `ref=54` (no `#`) is a PR number when it is purely decimal.
        (!trimmed.is_empty() && trimmed.bytes().all(|byte| byte.is_ascii_digit()))
            .then_some(trimmed)
    }) {
        let normalized = digits.trim_start_matches('0');
        let normalized = if normalized.is_empty() {
            "0"
        } else {
            normalized
        };
        return RefFilterMatch {
            kind: "pr",
            value_pattern: escape_like(&format!("#{normalized}")),
        };
    }
    // Otherwise treat the input as a commit SHA (or SHA prefix), matched by
    // prefix against the lowercased stored value.
    RefFilterMatch {
        kind: "commit",
        value_pattern: format!("{}%", escape_like(&trimmed.to_ascii_lowercase())),
    }
}

fn lexical_search_ranked_results(
    home: &Path,
    options: &SearchOptions,
    query_terms: &[String],
    fts_query: &str,
    fetch_limit: usize,
    max_snippet_chars: usize,
) -> Result<(Vec<RankedSearchResult>, bool)> {
    let db_path = home.join("index").join("harness.db");
    let conn = open_index(&db_path)?;
    let mut sql = String::from(
        "SELECT
           e.id,
           e.tool,
           e.session_id,
           e.canonical_type,
           e.captured_at,
           -bm25(events_fts, 8.0, 6.0, 4.0, 1.0, 0.5) AS score,
           NULL AS snippet,
           e.searchable_text,
           e.raw_file,
           e.raw_line,
           e.raw_offset,
           e.compaction_state,
           e.cwd,
           e.project_root
         FROM events_fts
         JOIN events e ON e.id = events_fts.rowid
         WHERE events_fts MATCH ?",
    );
    let mut params = vec![SqlValue::Text(fts_query.to_string())];

    if let Some(tool) = options.tool {
        sql.push_str(" AND e.tool = ?");
        params.push(SqlValue::Text(tool.as_str().to_string()));
    }
    if let Some(session_id) = options.session_id.as_deref() {
        let resolved = resolve_session_filter_ids(&conn, &db_path, options.tool, session_id)?;
        let placeholders = vec!["?"; resolved.len()].join(", ");
        sql.push_str(&format!(" AND e.session_id IN ({placeholders})"));
        for id in resolved {
            params.push(SqlValue::Text(id));
        }
    }
    if let Some(cwd) = options.cwd.as_deref() {
        sql.push_str(" AND e.cwd = ?");
        params.push(SqlValue::Text(cwd.to_string()));
    }
    if let Some(since) = options.since.as_deref() {
        sql.push_str(" AND e.captured_at >= ?");
        params.push(SqlValue::Text(normalize_date_or_duration(since, "since")?));
    }
    if let Some(canonical_type) = options.canonical_type.as_deref() {
        sql.push_str(" AND e.canonical_type = ?");
        params.push(SqlValue::Text(canonical_type.to_string()));
    }
    if !options.include_deltas {
        sql.push_str(" AND e.canonical_type != 'assistant.delta'");
    }
    if let Some(file) = options.file.as_deref() {
        sql.push_str(
            " AND EXISTS (
                SELECT 1
                FROM event_files ef
                JOIN files f ON f.id = ef.file_id
                WHERE ef.event_id = e.id
                  AND (f.path = ? OR f.path LIKE ?)
              )",
        );
        params.push(SqlValue::Text(file.to_string()));
        params.push(SqlValue::Text(format!("%{file}%")));
    }
    if let Some(command) = options.command.as_deref() {
        sql.push_str(
            " AND EXISTS (
                SELECT 1
                FROM tool_events te
                WHERE te.event_id = e.id
                  AND te.command LIKE ?
              )",
        );
        params.push(SqlValue::Text(format!("%{command}%")));
    }
    if let Some(ref_filter) = options.ref_filter.as_deref() {
        let ref_match = normalize_ref_filter(ref_filter);
        sql.push_str(
            " AND EXISTS (
                SELECT 1
                FROM event_refs er
                WHERE er.event_id = e.id
                  AND er.ref_kind = ?
                  AND er.ref_value LIKE ? ESCAPE '\\'
              )",
        );
        params.push(SqlValue::Text(ref_match.kind.to_string()));
        params.push(SqlValue::Text(ref_match.value_pattern));
    }
    sql.push_str(
        " ORDER BY bm25(events_fts, 8.0, 6.0, 4.0, 1.0, 0.5), e.captured_at DESC, e.raw_line ASC
          LIMIT ?",
    );
    params.push(SqlValue::Integer(fetch_limit.saturating_add(1) as i64));

    let mut statement = conn.prepare(&sql).map_err(|source| Error::Sqlite {
        path: db_path.clone(),
        source,
    })?;
    let rows = statement
        .query_map(params_from_iter(params), |row| {
            let tool_text: String = row.get(1)?;
            let searchable_text = row.get::<_, String>(7).unwrap_or_default();
            let canonical_type: String = row.get(3)?;
            let summary_kind = crate::summary_kind_for_canonical_str(&canonical_type);
            let raw_file: String = row.get(8)?;
            let raw_line: i64 = row.get(9)?;
            Ok(RankedSearchResult {
                event_id: row.get(0)?,
                result: SearchResult {
                    tool: Tool::from_str(&tool_text).map_err(|_| rusqlite::Error::InvalidQuery)?,
                    session_id: row.get(2)?,
                    canonical_type,
                    summary_kind,
                    timestamp: row.get(4)?,
                    score: row.get(5)?,
                    snippet: match_centered_snippet(
                        row.get::<_, Option<String>>(6)?,
                        searchable_text.clone(),
                        query_terms,
                        max_snippet_chars,
                    ),
                    native_command: native_jsonl_line_command(&raw_file, raw_line),
                    raw_file,
                    raw_line,
                    raw_offset: row.get(10)?,
                    compaction_state: row.get(11)?,
                    payload: Value::Null,
                    also_at: Vec::new(),
                    corroboration: None,
                    retrieval_key: retrieval_key_for_text(&searchable_text),
                    corroboration_text: searchable_text,
                    cwd: row.get(12)?,
                    project_root: row.get(13)?,
                },
            })
        })
        .map_err(|source| Error::Sqlite {
            path: db_path.clone(),
            source,
        })?;

    let mut results = Vec::new();
    for row in rows {
        results.push(row.map_err(|source| Error::Sqlite {
            path: db_path.clone(),
            source,
        })?);
    }
    let has_more_raw_rows = results.len() > fetch_limit;
    if has_more_raw_rows {
        results.truncate(fetch_limit);
    }
    Ok((results, has_more_raw_rows))
}

fn search_history_hybrid_page(
    home: &Path,
    query: &str,
    options: SearchOptions,
    semantic_available: bool,
) -> Result<SearchPage> {
    let query_terms = effective_search_terms(query, options.expand_concepts)?;
    let limit = options.limit.clamp(1, MAX_SEARCH_LIMIT);
    let offset = options.offset;
    let max_snippet_chars = options.max_snippet_chars.clamp(1, MAX_SEARCH_SNIPPET_CHARS);
    let raw_fetch_limit = search_overfetch_limit(offset, limit);
    let fts_query = quoted_fts_terms(&query_terms);

    let (lexical_results, lexical_has_more_raw_rows) = lexical_search_ranked_results(
        home,
        &options,
        &query_terms,
        &fts_query,
        raw_fetch_limit,
        max_snippet_chars,
    )?;
    let vector_results = vector_search_results(
        home,
        query,
        &options,
        raw_fetch_limit,
        &query_terms,
        max_snippet_chars,
    )?;
    let results = reciprocal_rank_fuse(lexical_results, vector_results);

    finalize_search_page(
        &options,
        SearchPageAssembly {
            results,
            // The fused set inherits the lexical overfetch truncation: if the
            // lexical side dropped rows, the true total is unknown, so
            // total_estimated must be None (matching the lexical path) rather
            // than the fused length.
            has_more_raw_rows: lexical_has_more_raw_rows,
            mode_requested: options.mode,
            mode_applied: SearchMode::Hybrid,
            semantic_available,
            limit,
            offset,
            max_snippet_chars,
        },
    )
}

fn reciprocal_rank_fuse(
    lexical_results: Vec<RankedSearchResult>,
    vector_results: Vec<RankedSearchResult>,
) -> Vec<RankedSearchResult> {
    const RRF_K: f64 = 60.0;
    let lexical_results = unique_ranked_results_by_event(lexical_results);
    let vector_results = unique_ranked_results_by_event(vector_results);
    let mut fused: HashMap<i64, (RankedSearchResult, f64)> = HashMap::new();

    for (rank, result) in lexical_results.into_iter().enumerate() {
        let key = result.event_id;
        let entry = fused.entry(key).or_insert((result, 0.0));
        entry.1 += 1.0 / (RRF_K + rank as f64 + 1.0);
    }
    for (rank, result) in vector_results.into_iter().enumerate() {
        let key = result.event_id;
        let entry = fused.entry(key).or_insert((result, 0.0));
        entry.1 += 1.0 / (RRF_K + rank as f64 + 1.0);
    }

    let mut results = fused
        .into_values()
        .map(|(mut result, score)| {
            result.result.score = score;
            result
        })
        .collect::<Vec<_>>();
    results.sort_by(|left, right| {
        right
            .result
            .score
            .total_cmp(&left.result.score)
            .then_with(|| right.result.timestamp.cmp(&left.result.timestamp))
            .then_with(|| left.result.raw_line.cmp(&right.result.raw_line))
    });
    results
}

pub(crate) fn unique_ranked_results_by_event(
    results: Vec<RankedSearchResult>,
) -> Vec<RankedSearchResult> {
    let mut seen = HashSet::new();
    let mut unique = Vec::new();
    for result in results {
        if seen.insert(result.event_id) {
            unique.push(result);
        }
    }
    unique
}

fn annotate_search_results_with_corroboration(results: &mut [SearchResult]) {
    for result in results {
        result.corroboration = Some(corroborate_text(
            result.cwd.as_deref(),
            result.project_root.as_deref(),
            &result.corroboration_text,
        ));
    }
}

fn search_overfetch_limit(offset: usize, limit: usize) -> usize {
    let requested_window = offset.saturating_add(limit);
    let extra = requested_window.min(500).max(limit);
    requested_window.saturating_add(extra)
}

fn bounded_snippet(snippet: String, max_chars: usize) -> String {
    truncate_chars(snippet.trim().to_string(), max_chars)
}

pub(crate) fn match_centered_snippet(
    sqlite_snippet: Option<String>,
    searchable_text: String,
    query_terms: &[String],
    max_chars: usize,
) -> String {
    if let Some(snippet) = sqlite_snippet.filter(|snippet| !snippet.trim().is_empty()) {
        return bounded_snippet(snippet, max_chars);
    }
    if searchable_text.chars().count() <= max_chars {
        return searchable_text.trim().to_string();
    }
    let lower_text = searchable_text.to_lowercase();
    let first_match = query_terms
        .iter()
        .filter_map(|term| lower_text.find(&term.to_lowercase()))
        .min()
        .unwrap_or(0);
    let half_window = max_chars.saturating_div(2);
    let mut start = first_match.saturating_sub(half_window);
    while start > 0 && !searchable_text.is_char_boundary(start) {
        start -= 1;
    }
    let mut end = start.saturating_add(max_chars).min(searchable_text.len());
    while end > start && !searchable_text.is_char_boundary(end) {
        end -= 1;
    }
    searchable_text[start..end].trim().to_string()
}

fn truncate_chars(mut value: String, max_chars: usize) -> String {
    if value.chars().count() <= max_chars {
        return value;
    }
    let mut cutoff = 0usize;
    for (count, (index, character)) in value.char_indices().enumerate() {
        if count == max_chars {
            break;
        }
        cutoff = index + character.len_utf8();
    }
    value.truncate(cutoff);
    value
}

fn dedupe_ranked_search_results(
    results: Vec<RankedSearchResult>,
) -> Result<Vec<RankedSearchResult>> {
    let mut seen: HashMap<(String, String, String), usize> = HashMap::new();
    let mut deduped: Vec<RankedSearchResult> = Vec::new();
    for result in results {
        let key = retrieval_twin_key(&result.result);
        if let Some(existing) = seen.get(&key).copied() {
            deduped[existing]
                .result
                .also_at
                .push(result.result.raw_line);
        } else {
            seen.insert(key, deduped.len());
            deduped.push(result);
        }
    }
    Ok(deduped)
}

// Retrieval-layer dedupe identity for a hit's text. Hashing the rendered
// `searchable_text` verbatim made the key sensitive to whitespace that carries
// no semantic content: two captures of the same answer that differ only by an
// embedded newline vs. a space (e.g. a native `output_text` block vs. its
// `agent_message` twin) hashed to different keys and survived dedupe as adjacent
// duplicates. Normalizing collapses any run of Unicode whitespace to a single
// space and trims the ends, so whitespace-only divergence yields one key while
// genuinely distinct text stays distinct. The normalization is applied to the
// dedupe key only; `searchable_text`, snippets, and `corroboration_text` keep
// their original bytes.
pub(crate) fn retrieval_key_for_text(searchable_text: &str) -> String {
    let normalized = searchable_text
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    sha256_hex(normalized.as_bytes())
}

fn retrieval_twin_key(result: &SearchResult) -> (String, String, String) {
    (
        result.session_id.clone(),
        result.canonical_type.clone(),
        result.retrieval_key.clone(),
    )
}

// Resolve the literal query into the term list used for FTS matching and
// snippet centering. With `expand_concepts` set, the literal terms are
// OR-extended with curated synonyms (originals kept up front); off, this is
// exactly `searchable_terms`.
fn effective_search_terms(query: &str, expand_concepts: bool) -> Result<Vec<String>> {
    let terms = searchable_terms(query)?;
    if expand_concepts {
        Ok(expand_query_terms(&terms))
    } else {
        Ok(terms)
    }
}

fn searchable_terms(query: &str) -> Result<Vec<String>> {
    let mut terms = Vec::new();
    let mut current = String::new();

    for character in query.chars() {
        if character.is_alphanumeric() || character == '_' {
            current.push(character);
        } else if !current.is_empty() {
            terms.push(std::mem::take(&mut current));
        }
    }
    if !current.is_empty() {
        terms.push(current);
    }

    if terms.is_empty() {
        return Err(Error::Validation(
            "query must contain searchable text".to_string(),
        ));
    }

    Ok(terms)
}

// Join terms with OR, not AND. AND made specificity collapse recall: a
// longer, more-specific query required every term to occur in one event, so
// adding terms could only ever shrink the match set to zero. With OR the FTS
// match set is the union of per-term hits and bm25 (weighted by term rarity
// and the column weights in lexical_search_ranked_results) floats events that
// satisfy more of the query to the top — specificity now improves ranking
// instead of erasing recall.
fn quoted_fts_terms(terms: &[String]) -> String {
    terms
        .iter()
        .map(|term| format!("\"{}\"", term.replace('"', "\"\"")))
        .collect::<Vec<_>>()
        .join(" OR ")
}

fn hydrate_search_result_payloads(results: &mut [SearchResult]) -> Result<()> {
    let mut grouped = BTreeMap::<String, Vec<usize>>::new();
    for (index, result) in results.iter().enumerate() {
        grouped
            .entry(result.raw_file.clone())
            .or_default()
            .push(index);
    }

    for (raw_file, mut indexes) in grouped {
        indexes.sort_by_key(|index| {
            (
                results[*index].raw_offset.unwrap_or(i64::MAX),
                results[*index].raw_line,
            )
        });
        let raw_path = PathBuf::from(&raw_file);
        let mut offset_reader = None;
        for index in indexes {
            let raw_line = results[index].raw_line;
            let raw_offset = results[index].raw_offset;
            let envelope = if let Some(raw_offset) = raw_offset {
                if offset_reader.is_none() {
                    offset_reader = Some(open_raw_offset_reader(&raw_path)?);
                }
                match read_raw_envelope_at_offset(
                    &raw_path,
                    offset_reader.as_mut().expect("offset reader initialized"),
                    raw_offset,
                )? {
                    Some(envelope) => envelope,
                    None => raw_envelope_for_line_scan(&raw_path, raw_line)?,
                }
            } else {
                raw_envelope_for_line_scan(&raw_path, raw_line)?
            };
            results[index].payload = resolved_payload_for_envelope(&raw_path, &envelope)?;
        }
    }
    Ok(())
}

// Resolve a caller-supplied session identifier to the canonical stored
// session_id(s) so the filter fails open instead of closed. An exact
// `session_id = ?` filter returned empty whenever a session was referenced by
// anything other than its full id — most commonly a short id prefix (the
// natural handle, like a short git SHA) or the filename-sanitized form. Those
// are present sessions, so empty was a confidently-wrong answer.
//
// Resolution is tiered, most-specific first: exact session_id, then
// filename_session_id, then id prefix — every session whose id starts with the
// input, so an ambiguous prefix widens the filter rather than emptying it
// (fail-open, never fail-closed). The first non-empty tier wins.
// `tool` is optional — when absent, resolution spans every tool, so the filter
// never silently requires a tool arg. When nothing resolves the literal input
// is returned unchanged: a genuinely-absent session then yields an empty
// result, which is correct rather than false-empty.
pub(crate) fn resolve_session_filter_ids(
    conn: &Connection,
    db_path: &Path,
    tool: Option<Tool>,
    session_id: &str,
) -> Result<Vec<String>> {
    let tiers: [(&str, String); 3] = [
        (
            "SELECT session_id FROM sessions WHERE session_id = ?1",
            session_id.to_string(),
        ),
        (
            "SELECT session_id FROM sessions WHERE filename_session_id = ?1",
            session_id.to_string(),
        ),
        (
            "SELECT session_id FROM sessions WHERE session_id LIKE ?1 ESCAPE '\\'",
            format!("{}%", escape_like(session_id)),
        ),
    ];

    for (base_sql, needle) in tiers {
        let mut sql = base_sql.to_string();
        let mut params = vec![SqlValue::Text(needle)];
        if let Some(tool) = tool {
            sql.push_str(" AND tool = ?2");
            params.push(SqlValue::Text(tool.as_str().to_string()));
        }
        let mut statement = conn.prepare(&sql).map_err(|source| Error::Sqlite {
            path: db_path.to_path_buf(),
            source,
        })?;
        let mut ids = Vec::new();
        let mut seen = HashSet::new();
        let rows = statement
            .query_map(params_from_iter(params), |row| row.get::<_, String>(0))
            .map_err(|source| Error::Sqlite {
                path: db_path.to_path_buf(),
                source,
            })?;
        for row in rows {
            let id = row.map_err(|source| Error::Sqlite {
                path: db_path.to_path_buf(),
                source,
            })?;
            if seen.insert(id.clone()) {
                ids.push(id);
            }
        }
        if !ids.is_empty() {
            return Ok(ids);
        }
    }

    Ok(vec![session_id.to_string()])
}

// Escape SQL LIKE metacharacters so a prefix match treats `%` and `_` in a
// session id literally (paired with `ESCAPE '\'` on the query).
fn escape_like(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for character in value.chars() {
        match character {
            '\\' | '%' | '_' => {
                escaped.push('\\');
                escaped.push(character);
            }
            _ => escaped.push(character),
        }
    }
    escaped
}

#[cfg(test)]
mod page_assembly_tests {
    //! Exercises the finalization the lexical and hybrid paths share. Before the
    //! extraction, the hybrid page carried its own copy that skipped
    //! corroboration and set `total_estimated` to the fused length even after
    //! overfetch truncation; these tests pin the shared function so the two paths
    //! cannot drift apart again.
    use super::*;

    fn ranked(event_id: i64, raw_line: i64) -> RankedSearchResult {
        RankedSearchResult {
            event_id,
            result: SearchResult {
                tool: Tool::Claude,
                session_id: "session".to_string(),
                canonical_type: "assistant.message".to_string(),
                summary_kind: None,
                timestamp: "2026-01-01T00:00:00Z".to_string(),
                score: 1.0,
                snippet: "snippet".to_string(),
                native_command: None,
                raw_file: "/tmp/nabu-page-assembly.jsonl".to_string(),
                raw_line,
                raw_offset: None,
                compaction_state: "none".to_string(),
                payload: Value::Null,
                also_at: Vec::new(),
                corroboration: None,
                retrieval_key: format!("retrieval-key-{event_id}"),
                // A PR ref resolves without touching the filesystem or git.
                corroboration_text: "resolved in PR #42".to_string(),
                cwd: None,
                project_root: None,
            },
        }
    }

    // A hybrid-shaped assembly: `mode_applied` is Hybrid, matching what
    // `search_history_hybrid_page` builds.
    fn hybrid_assembly(
        results: Vec<RankedSearchResult>,
        has_more_raw_rows: bool,
    ) -> SearchPageAssembly {
        SearchPageAssembly {
            results,
            has_more_raw_rows,
            mode_requested: SearchMode::Auto,
            mode_applied: SearchMode::Hybrid,
            semantic_available: true,
            limit: 10,
            offset: 0,
            max_snippet_chars: 200,
        }
    }

    #[test]
    fn hybrid_page_honors_corroborate() {
        let options = SearchOptions {
            corroborate: true,
            dedupe: false,
            ..SearchOptions::default()
        };
        let page = finalize_search_page(
            &options,
            hybrid_assembly(vec![ranked(1, 1), ranked(2, 2)], false),
        )
        .unwrap();
        assert_eq!(page.mode_applied, SearchMode::Hybrid);
        assert_eq!(page.results.len(), 2);
        for result in &page.results {
            assert!(
                result.corroboration.is_some(),
                "corroborate=true must annotate every hybrid result"
            );
        }
    }

    #[test]
    fn page_without_corroborate_leaves_it_unset() {
        let options = SearchOptions {
            corroborate: false,
            dedupe: false,
            ..SearchOptions::default()
        };
        let page =
            finalize_search_page(&options, hybrid_assembly(vec![ranked(1, 1)], false)).unwrap();
        assert!(page.results[0].corroboration.is_none());
    }

    #[test]
    fn hybrid_total_estimated_is_none_when_overfetch_truncated() {
        let options = SearchOptions {
            dedupe: false,
            ..SearchOptions::default()
        };
        let truncated = finalize_search_page(
            &options,
            hybrid_assembly(vec![ranked(1, 1), ranked(2, 2)], true),
        )
        .unwrap();
        assert_eq!(
            truncated.total_estimated, None,
            "a truncated overfetch means the true total is unknown"
        );
        assert!(
            truncated.continuation.is_some(),
            "truncation must advance the pagination cursor"
        );

        let complete = finalize_search_page(
            &options,
            hybrid_assembly(vec![ranked(1, 1), ranked(2, 2)], false),
        )
        .unwrap();
        assert_eq!(complete.total_estimated, Some(2));
    }
}