ctb_io_csc/
search_engine.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Fast indexed search engine querying .cscindex.sqlite Turso databases.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::args::{FsearchArgs, SearchOutputFormat, SearchSortField};
30use crate::index_engine::check_has_full_text;
31use ctb_formats_time::{format_timestamp, parse_time_spec};
32use ctb_io::file::entity::FileEntityType;
33use regex::Regex;
34use serde::Serialize;
35use std::fmt::Write as _;
36use turso::Value;
37
38/// A single matched entry returned from search.
39#[derive(Debug, Clone, Serialize)]
40pub struct SearchResultEntry {
41    pub path: String,
42    pub filename: String,
43    pub parent_dir: String,
44    pub kind: String,
45    pub size: u64,
46    pub mtime_sec: i64,
47    pub ctime_sec: i64,
48    pub mode: u32,
49    pub symlink_target: Option<String>,
50    pub sha256: Option<String>,
51    pub source_name: String,
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub context_lines: Option<Vec<String>>,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57enum SearchTarget {
58    Path,
59    Name,
60    Text,
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64enum SearchKind {
65    Regex,
66    Glob,
67    Keyword,
68}
69
70struct ResolvedSearch {
71    kind: SearchKind,
72    target: SearchTarget,
73    pattern: String,
74}
75
76fn resolve_search(
77    args: &FsearchArgs,
78    has_full_text: bool,
79) -> Result<Option<ResolvedSearch>> {
80    let explicit_keyword = if args.keyword.is_empty() {
81        args.keyword_path.clone()
82    } else {
83        Some(args.keyword.join(" "))
84    };
85
86    let has_explicit = args.regex_path.is_some()
87        || args.regex.is_some()
88        || args.regex_text.is_some()
89        || args.regex_name.is_some()
90        || args.glob_path.is_some()
91        || args.path_glob.is_some()
92        || args.glob_text.is_some()
93        || args.glob_name.is_some()
94        || args.name_glob.is_some()
95        || explicit_keyword.is_some()
96        || args.keyword_text.is_some()
97        || args.keyword_name.is_some()
98        || args.substring_path.is_some()
99        || args.substring_text.is_some()
100        || args.substring_name.is_some();
101
102    if has_explicit && !args.query.is_empty() {
103        anyhow::bail!(
104            "Cannot specify both explicit search filter flags and positional query terms: {}",
105            args.query.join(" ")
106        );
107    }
108
109    // 1. Explicit regex options
110    if let Some(pat) = args.regex_path.as_deref().or(args.regex.as_deref()) {
111        return Ok(Some(ResolvedSearch {
112            kind: SearchKind::Regex,
113            target: SearchTarget::Path,
114            pattern: pat.to_string(),
115        }));
116    }
117    if let Some(ref pat) = args.regex_text {
118        anyhow::ensure!(
119            has_full_text,
120            "Cannot perform regex full-text search: database was not indexed with --fulltext"
121        );
122        return Ok(Some(ResolvedSearch {
123            kind: SearchKind::Regex,
124            target: SearchTarget::Text,
125            pattern: pat.clone(),
126        }));
127    }
128    if let Some(ref pat) = args.regex_name {
129        return Ok(Some(ResolvedSearch {
130            kind: SearchKind::Regex,
131            target: SearchTarget::Name,
132            pattern: pat.clone(),
133        }));
134    }
135
136    // 2. Explicit substring options (equivalent to regex with escaped pattern)
137    if let Some(ref pat) = args.substring_path {
138        let pattern = if cfg!(windows) {
139            pat.replace('/', "\\")
140        } else {
141            pat.clone()
142        };
143        return Ok(Some(ResolvedSearch {
144            kind: SearchKind::Regex,
145            target: SearchTarget::Path,
146            pattern: regex::escape(&pattern),
147        }));
148    }
149    if let Some(ref pat) = args.substring_text {
150        anyhow::ensure!(
151            has_full_text,
152            "Cannot perform substring full-text search: database was not indexed with --fulltext"
153        );
154        return Ok(Some(ResolvedSearch {
155            kind: SearchKind::Regex,
156            target: SearchTarget::Text,
157            pattern: regex::escape(pat),
158        }));
159    }
160    if let Some(ref pat) = args.substring_name {
161        return Ok(Some(ResolvedSearch {
162            kind: SearchKind::Regex,
163            target: SearchTarget::Name,
164            pattern: regex::escape(pat),
165        }));
166    }
167
168    // 3. Explicit glob options
169    if let Some(pat) = args.glob_path.as_deref().or(args.path_glob.as_deref()) {
170        let pattern = if cfg!(windows) {
171            pat.replace('/', "\\")
172        } else {
173            pat.to_string()
174        };
175        return Ok(Some(ResolvedSearch {
176            kind: SearchKind::Glob,
177            target: SearchTarget::Path,
178            pattern,
179        }));
180    }
181    if let Some(ref pat) = args.glob_text {
182        anyhow::ensure!(
183            has_full_text,
184            "Cannot perform glob full-text search: database was not indexed with --fulltext"
185        );
186        return Ok(Some(ResolvedSearch {
187            kind: SearchKind::Glob,
188            target: SearchTarget::Text,
189            pattern: pat.clone(),
190        }));
191    }
192    if let Some(pat) = args.glob_name.as_deref().or(args.name_glob.as_deref()) {
193        return Ok(Some(ResolvedSearch {
194            kind: SearchKind::Glob,
195            target: SearchTarget::Name,
196            pattern: pat.to_string(),
197        }));
198    }
199
200    // 4. Explicit keyword options
201    if let Some(pat) = explicit_keyword {
202        return Ok(Some(ResolvedSearch {
203            kind: SearchKind::Keyword,
204            target: SearchTarget::Path,
205            pattern: pat,
206        }));
207    }
208    if let Some(ref pat) = args.keyword_text {
209        anyhow::ensure!(
210            has_full_text,
211            "Cannot perform keyword full-text search: database was not indexed with --fulltext"
212        );
213        return Ok(Some(ResolvedSearch {
214            kind: SearchKind::Keyword,
215            target: SearchTarget::Text,
216            pattern: pat.clone(),
217        }));
218    }
219    if let Some(ref pat) = args.keyword_name {
220        return Ok(Some(ResolvedSearch {
221            kind: SearchKind::Keyword,
222            target: SearchTarget::Name,
223            pattern: pat.clone(),
224        }));
225    }
226
227    // 5. Positional query resolution
228    if let [q] = args.query.as_slice() {
229        if q.contains('*') {
230            if q.contains('/') || (cfg!(windows) && q.contains('\\')) {
231                let pattern = if cfg!(windows) {
232                    q.replace('/', "\\")
233                } else {
234                    q.clone()
235                };
236                Ok(Some(ResolvedSearch {
237                    kind: SearchKind::Glob,
238                    target: SearchTarget::Path,
239                    pattern,
240                }))
241            } else {
242                Ok(Some(ResolvedSearch {
243                    kind: SearchKind::Glob,
244                    target: SearchTarget::Name,
245                    pattern: q.clone(),
246                }))
247            }
248        } else if has_full_text {
249            Ok(Some(ResolvedSearch {
250                kind: SearchKind::Regex,
251                target: SearchTarget::Text,
252                pattern: regex::escape(q),
253            }))
254        } else {
255            let pattern = if cfg!(windows) {
256                q.replace('/', "\\")
257            } else {
258                q.clone()
259            };
260            Ok(Some(ResolvedSearch {
261                kind: SearchKind::Regex,
262                target: SearchTarget::Path,
263                pattern: regex::escape(&pattern),
264            }))
265        }
266    } else if args.query.len() > 1 {
267        let combined = args.query.join(" ");
268        if has_full_text {
269            Ok(Some(ResolvedSearch {
270                kind: SearchKind::Keyword,
271                target: SearchTarget::Text,
272                pattern: combined,
273            }))
274        } else {
275            let pattern = if cfg!(windows) {
276                combined.replace('/', "\\")
277            } else {
278                combined
279            };
280            Ok(Some(ResolvedSearch {
281                kind: SearchKind::Keyword,
282                target: SearchTarget::Path,
283                pattern,
284            }))
285        }
286    } else {
287        Ok(None)
288    }
289}
290
291fn extract_context_lines(
292    text: &str,
293    resolved: Option<&ResolvedSearch>,
294    regex: Option<&Regex>,
295    n: usize,
296) -> Option<Vec<String>> {
297    let lines: Vec<&str> = text.lines().collect();
298    if lines.is_empty() {
299        return None;
300    }
301
302    let match_idx = if let Some(re) = regex {
303        lines.iter().position(|line| re.is_match(line))
304    } else if let Some(res) = resolved {
305        match res.kind {
306            SearchKind::Keyword => {
307                let terms: Vec<String> = res
308                    .pattern
309                    .split_whitespace()
310                    .map(|w| w.trim_matches('"').to_ascii_lowercase())
311                    .filter(|w| !w.is_empty())
312                    .collect();
313                lines.iter().position(|line| {
314                    let l_lower = line.to_ascii_lowercase();
315                    terms.iter().any(|term| l_lower.contains(term))
316                })
317            }
318            SearchKind::Glob => {
319                let pat_lower =
320                    res.pattern.trim_matches('*').to_ascii_lowercase();
321                lines.iter().position(|line| {
322                    line.to_ascii_lowercase().contains(&pat_lower)
323                })
324            }
325            SearchKind::Regex => None,
326        }
327    } else {
328        None
329    }?;
330
331    let start = match_idx.saturating_sub(n);
332    let end = (match_idx.saturating_add(n).saturating_add(1)).min(lines.len());
333
334    let mut ctx = Vec::with_capacity(end.saturating_sub(start));
335    for (idx, line) in lines.iter().enumerate().take(end).skip(start) {
336        let line_num = idx.saturating_add(1);
337        let sep = if idx == match_idx { ":" } else { "-" };
338        ctx.push(format!("{line_num}{sep} {line}"));
339    }
340
341    Some(ctx)
342}
343
344/// Executes fast indexed search query against a .cscindex.sqlite database.
345pub async fn run_fsearch(args: FsearchArgs) -> Result<ToolResult> {
346    anyhow::ensure!(
347        args.database.exists(),
348        "Database file does not exist: {}",
349        args.database.display()
350    );
351
352    let db = crate::index_meta::open_index_database(
353        &args.database,
354        false,
355        args.password_file.as_deref(),
356        args.password_stdin,
357    )
358    .await?;
359    let conn = db.connect()?;
360
361    let has_full_text = check_has_full_text(&conn).await?;
362
363    if args.context.is_some() && !has_full_text {
364        anyhow::bail!(
365            "Cannot display context lines: database was not indexed with --fulltext"
366        );
367    }
368
369    let resolved = resolve_search(&args, has_full_text)?;
370
371    // Build SQL query dynamically
372    let mut sql = if has_full_text {
373        String::from(
374            "SELECT
375                e.path, e.filename, e.parent_dir, e.kind, e.size,
376                e.mtime_sec, e.ctime_sec, e.mode, e.symlink_target, e.sha256,
377                s.name AS source_name,
378                e.full_text
379            FROM entries e
380            JOIN sources s ON e.source_id = s.id
381            WHERE 1=1",
382        )
383    } else {
384        String::from(
385            "SELECT
386                e.path, e.filename, e.parent_dir, e.kind, e.size,
387                e.mtime_sec, e.ctime_sec, e.mode, e.symlink_target, e.sha256,
388                s.name AS source_name
389            FROM entries e
390            JOIN sources s ON e.source_id = s.id
391            WHERE 1=1",
392        )
393    };
394
395    let mut params: Vec<Value> = Vec::new();
396
397    // 1. Source filter
398    if let Some(ref src) = args.source {
399        sql.push_str(" AND s.name LIKE ?");
400        params.push(Value::Text(format!("%{src}%")));
401    }
402
403    // 2. Pattern filter
404    let mut regex_filter: Option<Regex> = None;
405    if let Some(ref res) = resolved {
406        match res.kind {
407            SearchKind::Keyword => {
408                match res.target {
409                    SearchTarget::Name => {
410                        sql.push_str(" AND e.filename_keywords MATCH ?");
411                        params.push(Value::Text(res.pattern.clone()));
412                    }
413                    SearchTarget::Path => {
414                        sql.push_str(" AND (e.filename_keywords, e.path_keywords) MATCH ?");
415                        params.push(Value::Text(res.pattern.clone()));
416                    }
417                    SearchTarget::Text => {
418                        sql.push_str(
419                        " AND ((e.filename_keywords, e.path_keywords) MATCH ? OR (e.full_text IS NOT NULL AND e.full_text MATCH ?))",
420                    );
421                        params.push(Value::Text(res.pattern.clone()));
422                        params.push(Value::Text(res.pattern.clone()));
423                    }
424                }
425            }
426            SearchKind::Glob => match res.target {
427                SearchTarget::Name => {
428                    sql.push_str(" AND e.filename GLOB ?");
429                    params.push(Value::Text(res.pattern.clone()));
430                }
431                SearchTarget::Path => {
432                    sql.push_str(" AND e.path GLOB ?");
433                    params.push(Value::Text(res.pattern.clone()));
434                }
435                SearchTarget::Text => {
436                    sql.push_str(
437                        " AND (e.path GLOB ? OR e.filename GLOB ? OR (e.full_text IS NOT NULL AND e.full_text GLOB ?))",
438                    );
439                    params.push(Value::Text(res.pattern.clone()));
440                    params.push(Value::Text(res.pattern.clone()));
441                    params.push(Value::Text(res.pattern.clone()));
442                }
443            },
444            SearchKind::Regex => {
445                let re = Regex::new(&res.pattern).with_context(|| {
446                    format!("Invalid regular expression: {}", res.pattern)
447                })?;
448                regex_filter = Some(re);
449            }
450        }
451    }
452
453    // 3. Entity type filter
454    if let Some(ref entry_type_str) = args.entry_type {
455        let entity_type = FileEntityType::parse(entry_type_str)?;
456        sql.push_str(" AND e.kind = ?");
457        params.push(Value::Text(entity_type.as_str().to_string()));
458    }
459
460    // 4. Size filters
461    if let Some(ref min_s) = args.size_min {
462        let bytes = parse_bytes(min_s)?;
463        let i_bytes = i64::try_from(bytes).with_context(|| {
464            format!("Size filter '--size-min {min_s}' exceeds maximum supported 64-bit integer size")
465        })?;
466        sql.push_str(" AND e.size >= ?");
467        params.push(Value::Integer(i_bytes));
468    }
469    if let Some(ref max_s) = args.size_max {
470        let bytes = parse_bytes(max_s)?;
471        let i_bytes = i64::try_from(bytes).with_context(|| {
472            format!("Size filter '--size-max {max_s}' exceeds maximum supported 64-bit integer size")
473        })?;
474        sql.push_str(" AND e.size <= ?");
475        params.push(Value::Integer(i_bytes));
476    }
477
478    // 5. Timestamps filters
479    if let Some(ref ma) = args.mtime_after {
480        let sec = parse_time_spec(ma)?;
481        sql.push_str(" AND e.mtime_sec >= ?");
482        params.push(Value::Integer(sec));
483    }
484    if let Some(ref mb) = args.mtime_before {
485        let sec = parse_time_spec(mb)?;
486        sql.push_str(" AND e.mtime_sec <= ?");
487        params.push(Value::Integer(sec));
488    }
489    if let Some(ref ca) = args.ctime_after {
490        let sec = parse_time_spec(ca)?;
491        sql.push_str(" AND e.ctime_sec >= ?");
492        params.push(Value::Integer(sec));
493    }
494    if let Some(ref cb) = args.ctime_before {
495        let sec = parse_time_spec(cb)?;
496        sql.push_str(" AND e.ctime_sec <= ?");
497        params.push(Value::Integer(sec));
498    }
499
500    // 6. Sort ordering
501    let order_col = match args.sort {
502        SearchSortField::Path => "e.path",
503        SearchSortField::Name => "e.filename",
504        SearchSortField::Mtime => "e.mtime_sec",
505        SearchSortField::Ctime => "e.ctime_sec",
506        SearchSortField::Size => "e.size",
507    };
508    let order_dir = if args.sort_desc { "DESC" } else { "ASC" };
509    write!(sql, " ORDER BY {order_col} {order_dir}")?;
510
511    // 7. Limit (only if regex post-filter is not active)
512    let has_regex = regex_filter.is_some();
513    if !has_regex {
514        if let Some(limit) = args.limit {
515            let lim_i64 = i64::try_from(limit).with_context(|| {
516                format!("Limit value '{limit}' exceeds maximum supported 64-bit integer limit")
517            })?;
518            sql.push_str(" LIMIT ?");
519            params.push(Value::Integer(lim_i64));
520        }
521    }
522
523    let mut stmt = conn.prepare(&sql).await?;
524    let mut rows = stmt.query(params).await?;
525
526    let mut matches: Vec<SearchResultEntry> = Vec::new();
527
528    while let Some(row) = rows.next().await? {
529        let path = match row.get_value(0)? {
530            Value::Text(s) => s,
531            _ => continue,
532        };
533
534        let filename = match row.get_value(1)? {
535            Value::Text(s) => s,
536            _ => String::new(),
537        };
538        let parent_dir = match row.get_value(2)? {
539            Value::Text(s) => s,
540            _ => String::new(),
541        };
542        let kind = match row.get_value(3)? {
543            Value::Text(s) => s,
544            _ => "regular".to_string(),
545        };
546        let size = match row.get_value(4)? {
547            Value::Integer(i) => u64::try_from(i).with_context(|| {
548                format!("Corrupted database record for '{path}': size column has negative value {i}")
549            })?,
550            _ => anyhow::bail!("Corrupted database record for '{path}': expected integer in size column"),
551        };
552        let mtime_sec = match row.get_value(5)? {
553            Value::Integer(i) => i,
554            _ => anyhow::bail!(
555                "Corrupted database record for '{path}': expected integer in mtime column"
556            ),
557        };
558        let ctime_sec = match row.get_value(6)? {
559            Value::Integer(i) => i,
560            _ => anyhow::bail!(
561                "Corrupted database record for '{path}': expected integer in ctime column"
562            ),
563        };
564        let mode = match row.get_value(7)? {
565            Value::Integer(i) => u32::try_from(i).with_context(|| {
566                format!("Corrupted database record for '{path}': mode column has out-of-range value {i}")
567            })?,
568            _ => anyhow::bail!("Corrupted database record for '{path}': expected integer in mode column"),
569        };
570        let symlink_target = match row.get_value(8)? {
571            Value::Text(s) => Some(s),
572            _ => None,
573        };
574        let sha256 = match row.get_value(9)? {
575            Value::Text(s) => Some(s),
576            _ => None,
577        };
578        let source_name = match row.get_value(10)? {
579            Value::Text(s) => s,
580            _ => String::new(),
581        };
582
583        let full_text = if has_full_text {
584            match row.get_value(11)? {
585                Value::Text(s) => Some(s),
586                _ => None,
587            }
588        } else {
589            None
590        };
591
592        if let Some(ref re) = regex_filter {
593            let res = resolved
594                .as_ref()
595                .context("Expected resolved search for regex")?;
596            let is_matched = match res.target {
597                SearchTarget::Name => re.is_match(&filename),
598                SearchTarget::Path => re.is_match(&path),
599                SearchTarget::Text => {
600                    re.is_match(&path)
601                        || re.is_match(&filename)
602                        || full_text.as_deref().is_some_and(|t| re.is_match(t))
603                }
604            };
605            if !is_matched {
606                continue;
607            }
608        }
609
610        let context_lines = if let Some(n) = args.context {
611            full_text.as_deref().and_then(|t| {
612                extract_context_lines(
613                    t,
614                    resolved.as_ref(),
615                    regex_filter.as_ref(),
616                    n,
617                )
618            })
619        } else {
620            None
621        };
622
623        matches.push(SearchResultEntry {
624            path,
625            filename,
626            parent_dir,
627            kind,
628            size,
629            mtime_sec,
630            ctime_sec,
631            mode,
632            symlink_target,
633            sha256,
634            source_name,
635            context_lines,
636        });
637
638        if let Some(limit) = args.limit {
639            if matches.len() >= limit {
640                break;
641            }
642        }
643    }
644
645    // Format output
646    let mut out = String::new();
647    match args.format {
648        SearchOutputFormat::Path => {
649            for item in &matches {
650                writeln!(out, "{}", item.path)?;
651                if let Some(ref ctx) = item.context_lines {
652                    for line in ctx {
653                        writeln!(out, "  {line}")?;
654                    }
655                }
656            }
657        }
658        SearchOutputFormat::Long => {
659            for item in &matches {
660                let perm_str = format_permissions(&item.kind, item.mode);
661                let date_str = format_timestamp(item.mtime_sec);
662                // Reason for fallback: non-symlink entities have no target link, displaying empty suffix
663                let target_str = item
664                    .symlink_target
665                    .as_deref()
666                    .map_or(String::new(), |t| format!(" -> {t}"));
667
668                writeln!(
669                    out,
670                    "{} {:>10} {} [{}] {}{}",
671                    perm_str,
672                    item.size,
673                    date_str,
674                    item.source_name,
675                    item.path,
676                    target_str
677                )?;
678                if let Some(ref ctx) = item.context_lines {
679                    for line in ctx {
680                        writeln!(out, "  {line}")?;
681                    }
682                }
683            }
684        }
685        SearchOutputFormat::Json => {
686            out = serde_json::to_string_pretty(&matches)?;
687            out.push('\n');
688        }
689    }
690
691    Ok(ToolResult::immediate_ok(out.into_bytes()))
692}
693#[cfg(test)]
694#[allow(
695    clippy::panic,
696    clippy::expect_used,
697    clippy::unwrap_used,
698    clippy::unwrap_in_result,
699    clippy::panic_in_result_fn,
700    clippy::indexing_slicing,
701    clippy::arithmetic_side_effects,
702    reason = "Standard repository test boilerplate"
703)]
704mod tests {
705    use super::*;
706    use crate::args::{default_fsearch_args, default_fsindex_args};
707    use ctb_utilities::cli::ToolResult;
708    use std::fs;
709    use tempfile::tempdir;
710
711    #[crate::ctb_test("tokio")]
712    async fn test_camelcase_keyword_indexing_and_searching() {
713        use crate::index_engine::{
714            expand_search_keywords, run_fsindex, split_camel_case,
715        };
716        use crate::search_engine::run_fsearch;
717
718        // Test unit tokenization
719        let sub = split_camel_case("FooBarRegular");
720        assert_eq!(sub, vec!["Foo", "Bar", "Regular"]);
721
722        let kw = expand_search_keywords("FooBarRegular.ttf");
723        assert!(kw.contains("foobar"));
724        assert!(kw.contains("foo"));
725        assert!(kw.contains("bar"));
726        assert!(kw.contains("regular"));
727
728        let temp = tempdir().expect("create tempdir");
729        let src = temp.path().join("fonts_src");
730        fs::create_dir_all(&src).expect("create fonts_src");
731        fs::write(src.join("FooBarRegular.ttf"), b"dummy font data")
732            .expect("write font");
733
734        let db_path = temp.path().join("fonts.cscindex.sqlite");
735        let idx_args =
736            default_fsindex_args(vec![src.clone()], Some(db_path.clone()));
737        run_fsindex(idx_args).await.expect("run fsindex");
738
739        // 1. Match on -kn foobar
740        let mut s_kn1 = default_fsearch_args(db_path.clone());
741        s_kn1.keyword_name = Some("foobar".to_string());
742        let res1 = run_fsearch(s_kn1).await.expect("search -kn foobar");
743        if let ctb_utilities::ToolResult::Immediate { stdout, .. } = res1 {
744            let out = String::from_utf8_lossy(&stdout);
745            assert!(
746                out.contains("FooBarRegular.ttf"),
747                "Expected match on foobar: {out}"
748            );
749        } else {
750            panic!("Expected immediate result");
751        }
752
753        // 2. Match on -kn "foo bar"
754        let mut s_kn2 = default_fsearch_args(db_path.clone());
755        s_kn2.keyword_name = Some("foo bar".to_string());
756        let res2 = run_fsearch(s_kn2).await.expect("search -kn foo bar");
757        if let ctb_utilities::ToolResult::Immediate { stdout, .. } = res2 {
758            let out = String::from_utf8_lossy(&stdout);
759            assert!(
760                out.contains("FooBarRegular.ttf"),
761                "Expected match on foo bar: {out}"
762            );
763        } else {
764            panic!("Expected immediate result");
765        }
766
767        // 3. Match on individual words
768        let mut s_kn3 = default_fsearch_args(db_path.clone());
769        s_kn3.keyword_name = Some("bar".to_string());
770        let res3 = run_fsearch(s_kn3).await.expect("search -kn bar");
771        if let ctb_utilities::ToolResult::Immediate { stdout, .. } = res3 {
772            let out = String::from_utf8_lossy(&stdout);
773            assert!(
774                out.contains("FooBarRegular.ttf"),
775                "Expected match on bar: {out}"
776            );
777        } else {
778            panic!("Expected immediate result");
779        }
780
781        // 4. Match on -kp foobar
782        let mut s_kp = default_fsearch_args(db_path.clone());
783        s_kp.keyword_path = Some("foobar".to_string());
784        let res4 = run_fsearch(s_kp).await.expect("search -kp foobar");
785        if let ctb_utilities::ToolResult::Immediate { stdout, .. } = res4 {
786            let out = String::from_utf8_lossy(&stdout);
787            assert!(
788                out.contains("FooBarRegular.ttf"),
789                "Expected match on -kp foobar: {out}"
790            );
791        } else {
792            panic!("Expected immediate result");
793        }
794    }
795
796    #[crate::ctb_test("tokio")]
797    async fn test_substring_fsearch_options_and_default_behavior() {
798        use crate::index_engine::run_fsindex;
799        use crate::search_engine::run_fsearch;
800
801        let temp = tempdir().expect("create tempdir");
802        let src = temp.path().join("sub_src");
803        fs::create_dir_all(&src).expect("create sub_src");
804        fs::write(src.join("foo.bar.baz.txt"), b"sample content")
805            .expect("write foo.bar");
806        fs::write(
807            src.join("special[regex]+file.log"),
808            b"log data with target.substring in it",
809        )
810        .expect("write special");
811
812        let db_path = temp.path().join("sub.cscindex.sqlite");
813        let mut idx_args =
814            default_fsindex_args(vec![src.clone()], Some(db_path.clone()));
815        idx_args.fulltext = true;
816        run_fsindex(idx_args).await.expect("run fsindex");
817
818        // 1. Substring name matching with special characters (dot must not act as regex any-char)
819        let mut s_sn = default_fsearch_args(db_path.clone());
820        s_sn.substring_name = Some("bar.baz".to_string());
821        let res_sn = run_fsearch(s_sn).await.expect("search -sn");
822        if let ctb_utilities::ToolResult::Immediate { stdout, .. } = res_sn {
823            let out = String::from_utf8_lossy(&stdout);
824            assert!(out.contains("foo.bar.baz.txt"));
825        } else {
826            panic!("Expected immediate result");
827        }
828
829        // 2. Substring path matching with regex metacharacters [ ] and +
830        let mut s_sp = default_fsearch_args(db_path.clone());
831        s_sp.substring_path = Some("[regex]+file".to_string());
832        let res_sp = run_fsearch(s_sp).await.expect("search -sp");
833        if let ctb_utilities::ToolResult::Immediate { stdout, .. } = res_sp {
834            let out = String::from_utf8_lossy(&stdout);
835            assert!(out.contains("special[regex]+file.log"));
836        } else {
837            panic!("Expected immediate result");
838        }
839
840        // 3. Substring text matching with escaped characters
841        let mut s_st = default_fsearch_args(db_path.clone());
842        s_st.substring_text = Some("target.substring".to_string());
843        let res_st = run_fsearch(s_st).await.expect("search -st");
844        if let ctb_utilities::ToolResult::Immediate { stdout, .. } = res_st {
845            let out = String::from_utf8_lossy(&stdout);
846            assert!(out.contains("special[regex]+file.log"));
847        } else {
848            panic!("Expected immediate result");
849        }
850
851        // 4. Default search behavior: single positional argument does substring search
852        let mut s_single = default_fsearch_args(db_path.clone());
853        s_single.query = vec!["bar.baz".to_string()];
854        let res_single = run_fsearch(s_single)
855            .await
856            .expect("search single positional argument");
857        if let ctb_utilities::ToolResult::Immediate { stdout, .. } = res_single
858        {
859            let out = String::from_utf8_lossy(&stdout);
860            assert!(
861                out.contains("foo.bar.baz.txt"),
862                "Single positional term must do substring search: {out}"
863            );
864        } else {
865            panic!("Expected immediate result");
866        }
867    }
868
869    #[crate::ctb_test("tokio")]
870    async fn test_encrypted_fsindex_and_fsearch() {
871        use crate::index_engine::run_fsindex;
872        use crate::index_meta::{
873            is_database_encrypted, load_index_meta, resolve_meta_path,
874        };
875        use crate::search_engine::run_fsearch;
876        use std::io::Read;
877
878        let temp = tempdir().expect("tempdir");
879        let src = temp.path().join("secret_src");
880        fs::create_dir_all(src.join("sub")).expect("create dirs");
881        fs::write(src.join("secret_doc.txt"), b"Confidential memo")
882            .expect("write doc");
883        fs::write(src.join("sub/notes.md"), b"Secret notes")
884            .expect("write notes");
885
886        let pw_file = temp.path().join("correct_pw.txt");
887        fs::write(&pw_file, b"super-secret-index-pass-987\n")
888            .expect("write pw");
889
890        let db_path = temp.path().join("encrypted.cscindex.sqlite");
891
892        // 1. Index with encryption
893        let mut idx_args =
894            default_fsindex_args(vec![src.clone()], Some(db_path.clone()));
895        idx_args.encrypt = true;
896        idx_args.password_file = Some(pw_file.clone());
897
898        let res = run_fsindex(idx_args).await.expect("run encrypted fsindex");
899        match res {
900            ToolResult::Immediate {
901                exit_code, stdout, ..
902            } => {
903                assert_eq!(exit_code, 0);
904                let out = String::from_utf8_lossy(&stdout);
905                assert!(out.contains("Indexing completed successfully"));
906            }
907            _ => panic!("Expected immediate result"),
908        }
909
910        // 2. Verify database exists and has b"Turso" magic header
911        assert!(db_path.exists());
912        let is_enc = is_database_encrypted(&db_path).expect("check encrypted");
913        assert!(
914            is_enc,
915            "Database should be detected as encrypted via Turso header"
916        );
917
918        let mut f = std::fs::File::open(&db_path).expect("open db");
919        let mut magic = [0u8; 5];
920        f.read_exact(&mut magic).expect("read magic header");
921        assert_eq!(&magic, b"Turso");
922
923        // 3. Verify companion *.cscidxmeta exists and has valid metadata
924        let meta_path = resolve_meta_path(&db_path);
925        assert!(meta_path.exists(), "Companion *.cscidxmeta must exist");
926        let meta = load_index_meta(&meta_path).expect("load metadata");
927        assert_eq!(meta.cipher, "aegis256");
928        assert_eq!(meta.kdf, "argon2id");
929        assert_eq!(meta.format_version, 1);
930        assert!(!meta.wrapped_dek.is_empty());
931        assert!(!meta.kek_params.salt_base64.is_empty());
932
933        // 4. Query with fsearch using correct password file
934        let mut search_args = default_fsearch_args(db_path.clone());
935        search_args.query = vec!["*.txt".to_string()];
936        search_args.password_file = Some(pw_file.clone());
937
938        let search_res = run_fsearch(search_args).await.expect("run fsearch");
939        match search_res {
940            ToolResult::Immediate {
941                stdout, exit_code, ..
942            } => {
943                assert_eq!(exit_code, 0);
944                let out = String::from_utf8_lossy(&stdout);
945                assert!(out.contains("secret_doc.txt"));
946                assert!(!out.contains("notes.md"));
947            }
948            _ => panic!("Expected immediate result"),
949        }
950    }
951
952    #[crate::ctb_test("tokio")]
953    async fn test_encrypted_fsindex_wrong_password_rejected() {
954        use crate::index_engine::run_fsindex;
955        use crate::search_engine::run_fsearch;
956
957        let temp = tempdir().expect("tempdir");
958        let src = temp.path().join("secure_src");
959        fs::create_dir_all(&src).expect("create src");
960        fs::write(src.join("vault.data"), b"Treasury records")
961            .expect("write vault");
962
963        let correct_pw = temp.path().join("correct.txt");
964        let wrong_pw = temp.path().join("wrong.txt");
965        fs::write(&correct_pw, b"valid-pass-1234\n").expect("write correct pw");
966        fs::write(&wrong_pw, b"incorrect-pass-5678\n").expect("write wrong pw");
967
968        let db_path = temp.path().join("secure_vault.cscindex.sqlite");
969
970        // Index with encryption
971        let mut idx_args =
972            default_fsindex_args(vec![src], Some(db_path.clone()));
973        idx_args.encrypt = true;
974        idx_args.password_file = Some(correct_pw);
975        run_fsindex(idx_args).await.expect("run encrypted fsindex");
976
977        // Attempt search with wrong password
978        let mut search_args = default_fsearch_args(db_path);
979        search_args.query = vec!["vault*".to_string()];
980        search_args.password_file = Some(wrong_pw);
981
982        let err = match run_fsearch(search_args).await {
983            Ok(_) => panic!("fsearch with wrong password should fail"),
984            Err(e) => e,
985        };
986        let err_msg = format!("{err:#}");
987        assert!(
988            err_msg.contains("Incorrect password")
989                || err_msg.contains("password"),
990            "Expected password rejection, got: {err_msg}"
991        );
992    }
993
994    #[crate::ctb_test("tokio")]
995    async fn test_encrypted_fsindex_append_and_flush() {
996        use crate::index_engine::run_fsindex;
997        use crate::search_engine::run_fsearch;
998
999        let temp = tempdir().expect("tempdir");
1000        let src_a = temp.path().join("src_a");
1001        let src_b = temp.path().join("src_b");
1002        fs::create_dir_all(&src_a).expect("create src_a");
1003        fs::create_dir_all(&src_b).expect("create src_b");
1004
1005        let file_to_delete = src_a.join("temporary.log");
1006        fs::write(&file_to_delete, b"temporary log line")
1007            .expect("write temp log");
1008        fs::write(src_a.join("permanent.txt"), b"permanent text")
1009            .expect("write perm text");
1010        fs::write(src_b.join("appended.txt"), b"appended text")
1011            .expect("write appended text");
1012
1013        let pw_file = temp.path().join("vault_pw.txt");
1014        fs::write(&pw_file, b"vault-pass-alpha\n").expect("write pw");
1015
1016        let db_path = temp.path().join("shared_vault.cscindex.sqlite");
1017
1018        let journal_a = temp.path().join("src_a.cscjournal");
1019
1020        // 1. Initial index of src_a with encryption
1021        let mut args_a =
1022            default_fsindex_args(vec![src_a.clone()], Some(db_path.clone()));
1023        args_a.journal_path = Some(journal_a.clone());
1024        args_a.encrypt = true;
1025        args_a.password_file = Some(pw_file.clone());
1026        run_fsindex(args_a).await.expect("index src_a");
1027
1028        // 2. append src_b into existing encrypted index
1029        let mut args_b =
1030            default_fsindex_args(vec![src_b.clone()], Some(db_path.clone()));
1031        args_b.password_file = Some(pw_file.clone());
1032        run_fsindex(args_b).await.expect("append src_b");
1033
1034        // Search: should find permanent.txt and appended.txt
1035        let mut s1 = default_fsearch_args(db_path.clone());
1036        s1.query = vec!["*.txt".to_string()];
1037        s1.password_file = Some(pw_file.clone());
1038        let res1 = run_fsearch(s1).await.expect("search both sources");
1039        if let ToolResult::Immediate { stdout, .. } = res1 {
1040            let out = String::from_utf8_lossy(&stdout);
1041            assert!(out.contains("permanent.txt"));
1042            assert!(out.contains("appended.txt"));
1043        }
1044
1045        // 3. Delete temporary.log and flush deleted using journal_a
1046        fs::remove_file(&file_to_delete).expect("remove temporary.log");
1047        let mut args_flush =
1048            default_fsindex_args(vec![journal_a], Some(db_path.clone()));
1049        args_flush.flush_deleted = true;
1050        args_flush.password_file = Some(pw_file.clone());
1051        let res_flush = run_fsindex(args_flush).await.expect("flush deleted");
1052        if let ToolResult::Immediate { stdout, .. } = res_flush {
1053            let out = String::from_utf8_lossy(&stdout);
1054            assert!(out.contains("Entries flushed:  1"));
1055        }
1056
1057        // Search: temporary.log should no longer be indexed
1058        let mut s2 = default_fsearch_args(db_path);
1059        s2.query = vec!["temporary.log".to_string()];
1060        s2.password_file = Some(pw_file);
1061        let res2 = run_fsearch(s2).await.expect("search flushed");
1062        if let ToolResult::Immediate { stdout, .. } = res2 {
1063            let out = String::from_utf8_lossy(&stdout);
1064            assert!(!out.contains("temporary.log"));
1065        }
1066    }
1067
1068    #[crate::ctb_test("tokio")]
1069    async fn test_unencrypted_index_no_metadata_file() {
1070        use crate::index_engine::run_fsindex;
1071        use crate::index_meta::{is_database_encrypted, resolve_meta_path};
1072        use crate::search_engine::run_fsearch;
1073        use std::io::Read;
1074
1075        let temp = tempdir().expect("tempdir");
1076        let src = temp.path().join("public_src");
1077        fs::create_dir_all(&src).expect("create src");
1078        fs::write(src.join("public.txt"), b"Public domain data")
1079            .expect("write public.txt");
1080
1081        let db_path = temp.path().join("public.cscindex.sqlite");
1082
1083        // Index WITHOUT --encrypt
1084        let idx_args = default_fsindex_args(vec![src], Some(db_path.clone()));
1085        run_fsindex(idx_args).await.expect("index unencrypted");
1086
1087        // 1. Verify db exists and is standard SQLite (not Turso encrypted)
1088        assert!(db_path.exists());
1089        let is_enc = is_database_encrypted(&db_path).expect("check encrypted");
1090        assert!(
1091            !is_enc,
1092            "Unencrypted index must NOT be detected as encrypted"
1093        );
1094
1095        let mut f = std::fs::File::open(&db_path).expect("open db");
1096        let mut magic = [0u8; 16];
1097        f.read_exact(&mut magic).expect("read sqlite header");
1098        assert_eq!(&magic, b"SQLite format 3\0");
1099
1100        // 2. Verify companion *.cscidxmeta file DOES NOT exist
1101        let meta_path = resolve_meta_path(&db_path);
1102        assert!(
1103            !meta_path.exists(),
1104            "Unencrypted index must NOT create a *.cscidxmeta companion file"
1105        );
1106
1107        // 3. Search without any password flags
1108        let mut s_args = default_fsearch_args(db_path);
1109        s_args.query = vec!["public.txt".to_string()];
1110        let res = run_fsearch(s_args).await.expect("search unencrypted");
1111        if let ToolResult::Immediate {
1112            stdout, exit_code, ..
1113        } = res
1114        {
1115            assert_eq!(exit_code, 0);
1116            let out = String::from_utf8_lossy(&stdout);
1117            assert!(out.contains("public.txt"));
1118        }
1119    }
1120}