ctb_io_csc/
index_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//! Resumable filesystem indexer and compiler to Turso SQLite 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::FsindexArgs;
30use crate::journal::{JournalSnapshot, StateJournal, resolve_journal_path};
31use ctb_io::file::entity::{FileEntity, FileEntityKind};
32use std::fmt::Write as _;
33use std::path::{Path, PathBuf};
34use std::time::{SystemTime, UNIX_EPOCH};
35use turso::{Connection, Value};
36
37/// Derives a clean, trimmed source name for the database from a journal path.
38#[must_use]
39pub fn derive_source_name(
40    journal_path: &Path,
41    explicit_name: Option<&str>,
42) -> String {
43    if let Some(explicit) = explicit_name {
44        return explicit.trim().to_string();
45    }
46
47    // Reason for fallback: When path has no file_name component (e.g. root or empty), default to "root" source name.
48    let base = journal_path
49        .file_name()
50        .map_or("source", |f| f.to_str().unwrap_or("source"));
51
52    // Reason for fallback: base filename lacking recognized archive extension retains original string unchanged
53    let without_journal = base
54        .strip_suffix(".cscjournal")
55        .or_else(|| base.strip_suffix(".cscdesc"))
56        .or_else(|| base.strip_suffix(".sqlite"))
57        .unwrap_or(base);
58
59    without_journal.to_string()
60}
61
62/// Executes directory indexing into a .cscjournal and/or compiles journals into
63/// an indexed SQLite database.
64pub async fn run_fsindex(args: FsindexArgs) -> Result<ToolResult> {
65    let _env_scope = if args.full_provenance {
66        ctb_io_environment::GlobalEnvironmentScope::enter_full()
67    } else {
68        ctb_io_environment::GlobalEnvironmentScope::enter_fresh()
69    };
70    let mut targets = args.targets.clone();
71    if targets.is_empty() {
72        if let Some(ref jp) = args.journal_path {
73            targets.push(jp.clone());
74        }
75    }
76    anyhow::ensure!(
77        !targets.is_empty(),
78        "Must provide at least one target path or --journal-path"
79    );
80
81    let progress = Progress::new(!args.quiet);
82    let mut journal_paths: Vec<PathBuf> = Vec::new();
83
84    // 1. Process targets (traverse directories into journals, or collect existing journals)
85    for target in &targets {
86        if target.is_dir() {
87            let journal_path =
88                index_directory_to_journal(target, &args, &progress)?;
89            journal_paths.push(journal_path);
90        } else {
91            let journal_path = resolve_journal_path(target)?;
92            journal_paths.push(journal_path);
93        }
94    }
95
96    if args.journal_only {
97        anyhow::ensure!(
98            !args.flush_deleted,
99            "--flush-deleted operates on the database index, but --journal-only was specified"
100        );
101        let mut msg = String::new();
102        for p in &journal_paths {
103            writeln!(msg, "Generated journal: {}", p.display())?;
104        }
105        return Ok(ToolResult::immediate_ok(msg.into_bytes()));
106    }
107
108    // 2. Determine target SQLite database path
109    let db_path = if let Some(ref db) = args.database {
110        db.clone()
111    } else {
112        let first_target = targets
113            .first()
114            .context("No target paths provided to index")?;
115        // Reason for fallback: target path lacking valid UTF-8 filename defaults to "index" database stem
116        let stem = first_target
117            .file_name()
118            .map_or("index", |s| s.to_str().unwrap_or("index"));
119        // Reason for fallback: stem lacking recognized archive extension retains original stem unchanged
120        let stem_trimmed = stem
121            .strip_suffix(".cscjournal")
122            .or_else(|| stem.strip_suffix(".cscdesc"))
123            .unwrap_or(stem);
124
125        // Reason for fallback: When target has no parent path, use current working directory ".".
126        let parent = first_target.parent().unwrap_or(Path::new("."));
127        parent.join(format!("{stem_trimmed}.cscindex.sqlite"))
128    };
129
130    let all_targets_are_journals = targets.iter().all(|t| !t.is_dir());
131
132    if all_targets_are_journals && args.flush_deleted {
133        anyhow::ensure!(
134            db_path.exists(),
135            "Database file does not exist: {}",
136            db_path.display()
137        );
138        let db = crate::index_meta::open_index_database(
139            &db_path,
140            args.encrypt,
141            args.password_file.as_deref(),
142            args.password_stdin,
143        )
144        .await?;
145        let conn = db.connect()?;
146        conn.busy_timeout(std::time::Duration::from_millis(5000))?;
147        init_database_schema(&conn).await?;
148
149        let mut total_flushed: u64 = 0;
150        let mut sources_checked: usize = 0;
151        for j_path in &journal_paths {
152            let explicit_name = if journal_paths.len() == 1 {
153                args.source_name.as_deref()
154            } else {
155                None
156            };
157            let flushed = flush_deleted_files_from_index(
158                &conn,
159                j_path,
160                explicit_name,
161                &progress,
162                &args.journal_projection_policy(),
163            )
164            .await?;
165            total_flushed = total_flushed.saturating_add(flushed);
166            sources_checked = sources_checked.saturating_add(1);
167        }
168
169        let mut summary = String::new();
170        writeln!(summary, "--- FSINDEX Summary ---")?;
171        writeln!(summary, "Database:         {}", db_path.display())?;
172        writeln!(summary, "Sources checked:  {sources_checked}")?;
173        writeln!(summary, "Entries flushed:  {total_flushed}")?;
174        writeln!(
175            summary,
176            "Status:           Indexing completed successfully."
177        )?;
178        return Ok(ToolResult::immediate_ok(summary.into_bytes()));
179    }
180
181    // 3. Connect to Turso SQLite database and create schema
182    let db = crate::index_meta::open_index_database(
183        &db_path,
184        args.encrypt,
185        args.password_file.as_deref(),
186        args.password_stdin,
187    )
188    .await?;
189    let conn = db.connect()?;
190    conn.busy_timeout(std::time::Duration::from_millis(5000))?;
191
192    init_database_schema(&conn).await?;
193
194    let is_fulltext = args.fulltext || args.fulltext_max != "20k";
195    let fulltext_limit = if is_fulltext {
196        let parsed = parse_bytes(&args.fulltext_max)?;
197        Some(
198            usize::try_from(parsed)
199                .context("fulltext_max size exceeds memory limits")?,
200        )
201    } else {
202        None
203    };
204
205    if is_fulltext {
206        let has_full_text = check_has_full_text(&conn).await?;
207        if !has_full_text {
208            conn.execute("ALTER TABLE entries ADD COLUMN full_text TEXT", ())
209                .await?;
210        }
211        conn.execute(
212            "CREATE INDEX IF NOT EXISTS idx_entries_text_fts ON entries USING fts (full_text)",
213            (),
214        )
215        .await?;
216    }
217
218    let mut total_flushed: u64 = 0;
219    if args.flush_deleted {
220        for j_path in &journal_paths {
221            let explicit_name = if journal_paths.len() == 1 {
222                args.source_name.as_deref()
223            } else {
224                None
225            };
226            let flushed = flush_deleted_files_from_index(
227                &conn,
228                j_path,
229                explicit_name,
230                &progress,
231                &args.journal_projection_policy(),
232            )
233            .await?;
234            total_flushed = total_flushed.saturating_add(flushed);
235        }
236    }
237
238    // 4. Ingest each journal into the database
239    let mut total_indexed_files: u64 = 0;
240    let mut sources_indexed: usize = 0;
241
242    for (idx, j_path) in journal_paths.iter().enumerate() {
243        progress.message(&format!("Ingesting journal: {}", j_path.display()));
244
245        let explicit_name = if journal_paths.len() == 1 {
246            args.source_name.as_deref()
247        } else {
248            None
249        };
250        let src_name = derive_source_name(j_path, explicit_name);
251        let snapshot = crate::journal::read_journal_snapshot_with_policy(
252            j_path,
253            &args.journal_projection_policy(),
254        )?;
255        let env_json =
256            snapshot.environment.as_ref().and_then(|e| e.to_json().ok());
257        let src_id =
258            get_or_create_source(&conn, &src_name, j_path, env_json.as_deref())
259                .await?;
260
261        let count = ingest_journal_snapshot(
262            &conn,
263            src_id,
264            &snapshot,
265            args.batch_size,
266            &progress,
267            fulltext_limit,
268        )
269        .await?;
270
271        total_indexed_files = total_indexed_files.saturating_add(count);
272        sources_indexed = sources_indexed.saturating_add(1);
273
274        if idx.saturating_add(1) < journal_paths.len() {
275            progress.message(&format!("Appended {src_name} into database"));
276        }
277    }
278
279    let mut summary = String::new();
280    writeln!(summary, "--- FSINDEX Summary ---")?;
281    writeln!(summary, "Database:         {}", db_path.display())?;
282    writeln!(summary, "Sources indexed:  {sources_indexed}")?;
283    writeln!(summary, "Entries inserted: {total_indexed_files}")?;
284    if args.flush_deleted {
285        writeln!(summary, "Entries flushed:  {total_flushed}")?;
286    }
287    writeln!(
288        summary,
289        "Status:           Indexing completed successfully."
290    )?;
291
292    Ok(ToolResult::immediate_ok(summary.into_bytes()))
293}
294
295/// Recursively traverses `target_dir` and writes committed entries to a `.cscjournal`.
296fn index_directory_to_journal(
297    target_dir: &Path,
298    args: &FsindexArgs,
299    progress: &Progress,
300) -> Result<PathBuf> {
301    let target_dir = std::fs::canonicalize(target_dir).with_context(|| {
302        format!("Failed to canonicalize directory {}", target_dir.display())
303    })?;
304
305    let (mut journal, snapshot) = if args.resume
306        || args.resume_journal.is_some()
307    {
308        let journal_path = if let Some(ref rj) = args.resume_journal {
309            resolve_journal_path(rj)?
310        } else if let Some(ref jp) = args.journal_path {
311            resolve_journal_path(jp)?
312        } else {
313            resolve_journal_path(&target_dir)?
314        };
315        let desc_path = journal_path.with_extension("cscdesc");
316        let snap = crate::journal::read_journal_snapshot_with_policy(
317            &journal_path,
318            &args.journal_projection_policy(),
319        )?;
320        progress.message(&format!(
321            "Resuming indexing from journal: {}",
322            journal_path.display()
323        ));
324        let jw =
325            StateJournal::open_for_resume(&journal_path, &desc_path, &snap)?;
326        (jw, Some(snap))
327    } else {
328        let (journal_path, desc_path) = if let Some(ref custom_jp) =
329            args.journal_path
330        {
331            let jp = if custom_jp.extension().and_then(|e| e.to_str())
332                == Some("cscdesc")
333            {
334                custom_jp.with_extension("cscjournal")
335            } else if custom_jp.extension().and_then(|e| e.to_str())
336                == Some("cscjournal")
337            {
338                custom_jp.clone()
339            } else {
340                custom_jp.with_extension("cscjournal")
341            };
342            let dp = jp.with_extension("cscdesc");
343            anyhow::ensure!(
344                !jp.exists() && !dp.exists(),
345                "Journal file already exists at {}: will not overwrite existing file (pass --resume to resume an interrupted session)",
346                jp.display()
347            );
348            (jp, dp)
349        } else {
350            let now = SystemTime::now()
351                .duration_since(UNIX_EPOCH)
352                .context("Clock before epoch")?;
353            let secs = now.as_secs();
354            let pid = std::process::id();
355            // Reason for fallback: When directory has no component name, default to "dir".
356            let dir_stem = target_dir
357                .file_name()
358                .map_or("dir", |s| s.to_str().unwrap_or("dir"));
359
360            // Reason for fallback: When target directory has no parent, default to current working directory ".".
361            let parent = target_dir.parent().unwrap_or(Path::new("."));
362            let jp = parent.join(format!("{dir_stem}_{secs}_{pid}.cscjournal"));
363            let dp = parent.join(format!("{dir_stem}_{secs}_{pid}.cscdesc"));
364            (jp, dp)
365        };
366
367        progress.message(&format!(
368            "Creating state journal: {}",
369            journal_path.display()
370        ));
371        let jw = StateJournal::create_at_path(
372            &journal_path,
373            &desc_path,
374            std::slice::from_ref(&target_dir),
375            &target_dir,
376        )?;
377        (jw, None)
378    };
379
380    let traversal_opts = ctb_io::file::TraversalOptions::new()
381        .order(ctb_io::file::TraversalOrder::BreadthFirst)
382        .one_file_system(args.one_file_system)
383        .yield_root(true)
384        .error_policy(ctb_io::file::OnTraversalError::Skip);
385
386    let traverser = ctb_io::file::traverse_dir(&target_dir, traversal_opts)?;
387
388    let mut uncommitted_count: usize = 0;
389    let mut total_scanned: u64 = 0;
390
391    for item_res in traverser {
392        let item = match item_res {
393            Ok(it) => it,
394            Err(e) => {
395                log_fmt!("Error traversing filesystem: {e}");
396                continue;
397            }
398        };
399
400        let entity = item.to_file_entity(Some(&target_dir), args.checksum)?;
401
402        let mut should_record = true;
403        if let Some(ref snap) = snapshot {
404            if let Some(raw) = entity.identity.path_bytes() {
405                if snap.is_committed(raw) {
406                    should_record = false;
407                }
408            }
409        }
410
411        if should_record {
412            journal.record_entity(&entity);
413            uncommitted_count = uncommitted_count.saturating_add(1);
414            total_scanned = total_scanned.saturating_add(1);
415
416            if uncommitted_count >= args.batch_size {
417                journal.commit_batch()?;
418                uncommitted_count = 0;
419            }
420        }
421    }
422
423    journal.mark_completed()?;
424    progress.message(&format!(
425        "Completed scan: {total_scanned} entries committed to journal"
426    ));
427    Ok(journal.journal_path().to_path_buf())
428}
429
430pub use ctb_formats_string::split_camel_case;
431
432/// Generates an expanded set of search keywords for a filename or path component,
433/// splitting on punctuation, whitespace, and CamelCase word boundaries, and emitting
434/// individual words, contiguous compound combinations, and the original text.
435#[must_use]
436pub fn expand_search_keywords(text: &str) -> String {
437    let mut tokens: Vec<String> = Vec::new();
438    let mut seen: std::collections::HashSet<String> =
439        std::collections::HashSet::new();
440
441    let mut add_token = |t: &str| {
442        let lower = t.to_ascii_lowercase();
443        if !lower.is_empty() && seen.insert(lower.clone()) {
444            tokens.push(lower);
445        }
446    };
447
448    add_token(text);
449
450    let parts: Vec<&str> = text
451        .split(|c: char| !c.is_alphanumeric())
452        .filter(|s| !s.is_empty())
453        .collect();
454
455    for part in parts {
456        add_token(part);
457
458        let subwords = split_camel_case(part);
459        if subwords.len() > 1 {
460            for w in &subwords {
461                add_token(w);
462            }
463
464            for win_size in 2..=subwords.len() {
465                for win in subwords.windows(win_size) {
466                    let compound = win
467                        .iter()
468                        .map(|s: &String| s.to_ascii_lowercase())
469                        .collect::<String>();
470                    add_token(&compound);
471                }
472            }
473        }
474    }
475
476    tokens.join(" ")
477}
478
479/// Initializes database tables, PRAGMAs, and B-tree indices.
480pub(crate) async fn init_database_schema(conn: &Connection) -> Result<()> {
481    let mut stmt = conn.prepare("PRAGMA journal_mode = WAL").await?;
482    let _ = stmt.query(()).await?;
483    conn.execute("PRAGMA synchronous = NORMAL", ()).await?;
484
485    conn.execute(
486        "CREATE TABLE IF NOT EXISTS metadata (
487            key TEXT PRIMARY KEY,
488            value TEXT NOT NULL
489        )",
490        (),
491    )
492    .await?;
493
494    conn.execute(
495        "CREATE TABLE IF NOT EXISTS sources (
496            id INTEGER PRIMARY KEY AUTOINCREMENT,
497            name TEXT UNIQUE NOT NULL,
498            journal_path TEXT NOT NULL,
499            indexed_at INTEGER NOT NULL,
500            environment TEXT
501        )",
502        (),
503    )
504    .await?;
505
506    // Check if `environment` column exists in `sources` table, and add it if absent
507    let mut stmt = conn.prepare("PRAGMA table_info(sources)").await?;
508    let mut rows = stmt.query(()).await?;
509    let mut has_env_col = false;
510    while let Some(row) = rows.next().await? {
511        if let Ok(Value::Text(col)) = row.get_value(1) {
512            if col == "environment" {
513                has_env_col = true;
514                break;
515            }
516        }
517    }
518    if !has_env_col {
519        let _ = conn
520            .execute("ALTER TABLE sources ADD COLUMN environment TEXT", ())
521            .await;
522    }
523
524    conn.execute(
525        "CREATE TABLE IF NOT EXISTS entries (
526            id INTEGER PRIMARY KEY AUTOINCREMENT,
527            source_id INTEGER NOT NULL REFERENCES sources(id),
528            path TEXT NOT NULL,
529            filename TEXT NOT NULL,
530            parent_dir TEXT NOT NULL,
531            kind TEXT NOT NULL CHECK (kind IN ('regular', 'dir', 'symlink', 'hardlink', 'fifo', 'chardev', 'blockdev', 'socket', 'door', 'bundle')),
532            size INTEGER NOT NULL,
533            mtime_sec INTEGER NOT NULL,
534            mtime_nsec INTEGER NOT NULL,
535            ctime_sec INTEGER NOT NULL,
536            ctime_nsec INTEGER NOT NULL,
537            mode INTEGER NOT NULL,
538            nlink INTEGER NOT NULL,
539            symlink_target TEXT,
540            sha256 TEXT,
541            filename_keywords TEXT NOT NULL DEFAULT '',
542            path_keywords TEXT NOT NULL DEFAULT ''
543        )",
544        (),
545    )
546    .await?;
547
548    conn.execute(
549        "CREATE INDEX IF NOT EXISTS idx_entries_filename ON entries(filename)",
550        (),
551    )
552    .await?;
553    conn.execute(
554        "CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_path ON entries(path)",
555        (),
556    )
557    .await?;
558    conn.execute(
559        "CREATE INDEX IF NOT EXISTS idx_entries_parent ON entries(parent_dir)",
560        (),
561    )
562    .await?;
563    conn.execute(
564        "CREATE INDEX IF NOT EXISTS idx_entries_source ON entries(source_id)",
565        (),
566    )
567    .await?;
568    conn.execute(
569        "CREATE INDEX IF NOT EXISTS idx_entries_mtime ON entries(mtime_sec)",
570        (),
571    )
572    .await?;
573    conn.execute(
574        "CREATE INDEX IF NOT EXISTS idx_entries_ctime ON entries(ctime_sec)",
575        (),
576    )
577    .await?;
578    conn.execute(
579        "CREATE INDEX IF NOT EXISTS idx_entries_size ON entries(size)",
580        (),
581    )
582    .await?;
583    conn.execute("CREATE INDEX IF NOT EXISTS idx_entries_name_fts ON entries USING fts (filename_keywords)", ()).await?;
584    conn.execute("CREATE INDEX IF NOT EXISTS idx_entries_fts ON entries USING fts (filename_keywords, path_keywords)", ()).await?;
585
586    Ok(())
587}
588
589/// Checks if the `entries` table has the `full_text` column.
590pub async fn check_has_full_text(conn: &Connection) -> Result<bool> {
591    let mut stmt = conn.prepare("PRAGMA table_info(entries)").await?;
592    let mut rows = stmt.query(()).await?;
593    while let Some(row) = rows.next().await? {
594        if let Ok(Value::Text(col)) = row.get_value(1) {
595            if col == "full_text" {
596                return Ok(true);
597            }
598        }
599    }
600    Ok(false)
601}
602
603/// Retrieves or inserts a source entry, returning its integer `source_id`.
604pub(crate) async fn get_or_create_source(
605    conn: &Connection,
606    source_name: &str,
607    journal_path: &Path,
608    environment: Option<&str>,
609) -> Result<i64> {
610    let mut stmt = conn
611        .prepare("SELECT id, environment FROM sources WHERE name = ?")
612        .await?;
613    let mut rows = stmt
614        .query(vec![Value::Text(source_name.to_string())])
615        .await?;
616
617    if let Some(row) = rows.next().await? {
618        if let Ok(Value::Integer(id)) = row.get_value(0) {
619            if let Some(env_str) = environment {
620                let current_env = row.get_value(1).ok();
621                let is_null = matches!(current_env, Some(Value::Null) | None);
622                if is_null {
623                    let _ = conn
624                        .execute(
625                            "UPDATE sources SET environment = ? WHERE id = ?",
626                            vec![
627                                Value::Text(env_str.to_string()),
628                                Value::Integer(id),
629                            ],
630                        )
631                        .await;
632                }
633            }
634            return Ok(id);
635        }
636    }
637
638    let now_sec = <i64 as TryFrom<_>>::try_from(
639        SystemTime::now()
640            .duration_since(UNIX_EPOCH)
641            .context("Clock error")?
642            .as_secs(),
643    )?;
644
645    conn.execute(
646        "INSERT INTO sources (name, journal_path, indexed_at, environment) VALUES (?, ?, ?, ?)",
647        vec![
648            Value::Text(source_name.to_string()),
649            Value::Text(journal_path.to_string_lossy().to_string()),
650            Value::Integer(now_sec),
651            // Reason for fallback: absent environment metadata stores SQL NULL in the sources table
652            environment.map_or(Value::Null, |s| Value::Text(s.to_string())),
653        ],
654    )
655    .await?;
656
657    let mut stmt_id = conn.prepare("SELECT last_insert_rowid()").await?;
658    let mut rows_id = stmt_id.query(()).await?;
659    if let Some(row) = rows_id.next().await? {
660        if let Ok(Value::Integer(id)) = row.get_value(0) {
661            return Ok(id);
662        }
663    }
664
665    anyhow::bail!("Failed to retrieve generated source_id for {source_name}")
666}
667
668/// Ingests all committed entities from a journal snapshot into the SQLite database.
669pub(crate) async fn ingest_journal_snapshot(
670    conn: &Connection,
671    source_id: i64,
672    snapshot: &JournalSnapshot,
673    batch_size: usize,
674    progress: &Progress,
675    fulltext_limit: Option<usize>,
676) -> Result<u64> {
677    let mut inserted_count: u64 = 0;
678    let entities: Vec<&FileEntity> =
679        snapshot.committed_entities.values().collect();
680
681    let chunks = entities.chunks(batch_size);
682    let total_chunks = chunks.len();
683
684    let has_full_text = check_has_full_text(conn).await?;
685    // Reason for fallback: snapshot without explicit sources defaults to indexing destination directory
686    let root_dir = snapshot.sources.first().unwrap_or(&snapshot.destination);
687
688    let sql_insert_without_ft = "INSERT INTO entries (
689        source_id, path, filename, parent_dir, kind, size,
690        mtime_sec, mtime_nsec, ctime_sec, ctime_nsec, mode, nlink,
691        symlink_target, sha256, filename_keywords, path_keywords
692    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
693    ON CONFLICT(path) DO UPDATE SET
694        source_id = excluded.source_id,
695        filename = excluded.filename,
696        parent_dir = excluded.parent_dir,
697        kind = excluded.kind,
698        size = excluded.size,
699        mtime_sec = excluded.mtime_sec,
700        mtime_nsec = excluded.mtime_nsec,
701        ctime_sec = excluded.ctime_sec,
702        ctime_nsec = excluded.ctime_nsec,
703        mode = excluded.mode,
704        nlink = excluded.nlink,
705        symlink_target = excluded.symlink_target,
706        sha256 = excluded.sha256,
707        filename_keywords = excluded.filename_keywords,
708        path_keywords = excluded.path_keywords";
709
710    let sql_insert_with_ft = "INSERT INTO entries (
711        source_id, path, filename, parent_dir, kind, size,
712        mtime_sec, mtime_nsec, ctime_sec, ctime_nsec, mode, nlink,
713        symlink_target, sha256, filename_keywords, path_keywords, full_text
714    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
715    ON CONFLICT(path) DO UPDATE SET
716        source_id = excluded.source_id,
717        filename = excluded.filename,
718        parent_dir = excluded.parent_dir,
719        kind = excluded.kind,
720        size = excluded.size,
721        mtime_sec = excluded.mtime_sec,
722        mtime_nsec = excluded.mtime_nsec,
723        ctime_sec = excluded.ctime_sec,
724        ctime_nsec = excluded.ctime_nsec,
725        mode = excluded.mode,
726        nlink = excluded.nlink,
727        symlink_target = excluded.symlink_target,
728        sha256 = excluded.sha256,
729        filename_keywords = excluded.filename_keywords,
730        path_keywords = excluded.path_keywords,
731        full_text = excluded.full_text";
732
733    let sql_insert = if has_full_text {
734        sql_insert_with_ft
735    } else {
736        sql_insert_without_ft
737    };
738
739    for (chunk_idx, chunk) in chunks.enumerate() {
740        conn.execute("BEGIN IMMEDIATE TRANSACTION", ()).await?;
741
742        for entity in chunk {
743            // Reason for fallback: absent relative path defaults to empty string in search database index
744            let path_str = entity
745                .identity
746                .relative_path
747                .as_deref()
748                .map_or(String::new(), |p| p.to_string_lossy().to_string());
749            // Reason for fallback: Root or empty relative path has empty filename.
750            let filename = entity
751                .identity
752                .relative_path
753                .as_deref()
754                .and_then(|p| p.file_name())
755                .map_or(String::new(), |s| s.to_string_lossy().to_string());
756            // Reason for fallback: Root or single-component relative path has empty parent dir string.
757            let parent_dir = entity
758                .identity
759                .relative_path
760                .as_deref()
761                .and_then(|p| p.parent())
762                .map_or(String::new(), |p| p.to_string_lossy().to_string());
763
764            let kind_str = entity.kind.kind_str();
765            let (size_val, symlink_target, sha256_str) = match &entity.kind {
766                FileEntityKind::Regular { size, sha256, .. } => {
767                    let sha_hex = if sha256.iter().any(|&b| b != 0) {
768                        Some(hex::encode(sha256))
769                    } else {
770                        None
771                    };
772                    // Reason for fallback: file size exceeding signed 64-bit integer limit is clamped to i64::MAX for SQLite storage
773                    let size_i64 = <i64 as TryFrom<_>>::try_from(*size)
774                        .unwrap_or(i64::MAX);
775                    (size_i64, None, sha_hex)
776                }
777                FileEntityKind::Symlink { target } => {
778                    (0_i64, Some(target.to_string()), None)
779                }
780                FileEntityKind::Hardlink {
781                    target_relative_path,
782                } => (0_i64, Some(target_relative_path.to_string()), None),
783                _ => (0_i64, None, None),
784            };
785
786            // Reason for fallback: absent metadata timestamps default to 0 epoch seconds
787            let mtime_sec = entity
788                .metadata
789                .timestamps
790                .as_ref()
791                .map_or(0, |ts| ts.mtime_sec);
792            // Reason for fallback: absent metadata timestamps default to 0 nanoseconds
793            let mtime_nsec = entity
794                .metadata
795                .timestamps
796                .as_ref()
797                .map_or(0, |ts| i64::from(ts.mtime_nsec));
798            // Reason for fallback: absent metadata timestamps default to 0 epoch seconds
799            let ctime_sec = entity
800                .metadata
801                .timestamps
802                .as_ref()
803                .map_or(0, |ts| ts.ctime_sec);
804            // Reason for fallback: absent metadata timestamps default to 0 nanoseconds
805            let ctime_nsec = entity
806                .metadata
807                .timestamps
808                .as_ref()
809                .map_or(0, |ts| i64::from(ts.ctime_nsec));
810            // Reason for fallback: absent mode defaults to 0 permissions in search index
811            let mode = entity.metadata.mode.map_or(0, i64::from);
812            // Reason for fallback: hardlink count exceeding signed 64-bit integer limit defaults to 1
813            let nlink = <i64 as TryFrom<_>>::try_from(entity.identity.nlink)
814                .unwrap_or(1);
815
816            let filename_kw = expand_search_keywords(&filename);
817            let path_kw = expand_search_keywords(&path_str);
818
819            let mut params = vec![
820                Value::Integer(source_id),
821                Value::Text(path_str.clone()),
822                Value::Text(filename.clone()),
823                Value::Text(parent_dir),
824                Value::Text(kind_str.to_string()),
825                Value::Integer(size_val),
826                Value::Integer(mtime_sec),
827                Value::Integer(mtime_nsec),
828                Value::Integer(ctime_sec),
829                Value::Integer(ctime_nsec),
830                Value::Integer(mode),
831                Value::Integer(nlink),
832                // Reason for fallback: entities without symlink target or SHA-256 hash record NULL in SQLite
833                symlink_target.map_or(Value::Null, Value::Text),
834                sha256_str.map_or(Value::Null, Value::Text),
835                Value::Text(filename_kw),
836                Value::Text(path_kw),
837            ];
838
839            if has_full_text {
840                let full_text_val = if fulltext_limit.is_some()
841                    && matches!(entity.kind, FileEntityKind::Regular { .. })
842                {
843                    let full_path = match &entity.identity.relative_path {
844                        Some(rel) => root_dir.join(rel),
845                        None => root_dir.clone(),
846                    };
847                    if let Ok(mut f) = std::fs::File::open(&full_path) {
848                        ctb_formats_text_extraction::to_text(
849                            &mut f,
850                            fulltext_limit,
851                        )
852                        .ok()
853                    } else {
854                        None
855                    }
856                } else {
857                    None
858                };
859                // Reason for fallback: absent full-text content maps to SQL NULL in database column
860                params.push(full_text_val.map_or(Value::Null, Value::Text));
861            }
862
863            conn.execute(sql_insert, params).await?;
864            inserted_count = inserted_count.saturating_add(1);
865        }
866
867        conn.execute("COMMIT", ()).await?;
868
869        if progress.is_enabled() && chunk_idx.saturating_add(1) % 5 == 0 {
870            progress.message(&format!(
871                "Ingested {}/{} batches ({} entries)",
872                chunk_idx.saturating_add(1),
873                total_chunks,
874                inserted_count
875            ));
876        }
877    }
878
879    Ok(inserted_count)
880}
881
882/// Iterates through the SQLite index associated with the given journal, checks
883/// whether each file remains on disk, and deletes nonexistent files from the
884/// index.
885///
886/// Note: The `.cscjournal` file itself is completely untouched.
887pub async fn flush_deleted_files_from_index(
888    conn: &Connection,
889    journal_path: &Path,
890    explicit_name: Option<&str>,
891    progress: &Progress,
892    policy: &ctb_formats_dcstring::DcProjectionPolicy,
893) -> Result<u64> {
894    let snapshot = crate::journal::read_journal_snapshot_with_policy(
895        journal_path,
896        policy,
897    )?;
898    // Reason for fallback: snapshot without explicit sources defaults to inspecting destination directory
899    let root_dir = snapshot.sources.first().unwrap_or(&snapshot.destination);
900
901    anyhow::ensure!(
902        root_dir.exists(),
903        "Root directory {} recorded in journal {} does not exist",
904        root_dir.display(),
905        journal_path.display()
906    );
907
908    let src_path_str = journal_path.to_string_lossy().to_string();
909    let src_name = derive_source_name(journal_path, explicit_name);
910    let mut stmt = conn
911        .prepare("SELECT id FROM sources WHERE journal_path = ? OR name = ?")
912        .await?;
913    let mut rows = stmt
914        .query(vec![Value::Text(src_path_str), Value::Text(src_name)])
915        .await?;
916
917    let source_id = if let Some(row) = rows.next().await? {
918        if let Ok(Value::Integer(id)) = row.get_value(0) {
919            id
920        } else {
921            return Ok(0);
922        }
923    } else {
924        return Ok(0);
925    };
926
927    let mut entries_stmt = conn
928        .prepare("SELECT id, path FROM entries WHERE source_id = ?")
929        .await?;
930    let mut entries_rows =
931        entries_stmt.query(vec![Value::Integer(source_id)]).await?;
932
933    let mut ids_to_delete: Vec<i64> = Vec::new();
934
935    while let Some(row) = entries_rows.next().await? {
936        let Ok(Value::Integer(entry_id)) = row.get_value(0) else {
937            continue;
938        };
939        let Ok(Value::Text(rel_path_str)) = row.get_value(1) else {
940            continue;
941        };
942
943        let full_path = root_dir.join(&rel_path_str);
944        if std::fs::symlink_metadata(&full_path).is_err() {
945            ids_to_delete.push(entry_id);
946        }
947    }
948
949    if ids_to_delete.is_empty() {
950        progress.message("No deleted files found in index.");
951        return Ok(0);
952    }
953
954    let count = u64::try_from(ids_to_delete.len())?;
955    progress
956        .message(&format!("Flushing {count} deleted file(s) from index..."));
957
958    for chunk in ids_to_delete.chunks(500) {
959        conn.execute("BEGIN IMMEDIATE TRANSACTION", ()).await?;
960        for id in chunk {
961            conn.execute(
962                "DELETE FROM entries WHERE id = ?",
963                vec![Value::Integer(*id)],
964            )
965            .await?;
966        }
967        conn.execute("COMMIT", ()).await?;
968    }
969
970    Ok(count)
971}
972#[cfg(test)]
973#[allow(
974    clippy::panic,
975    clippy::expect_used,
976    clippy::unwrap_used,
977    clippy::unwrap_in_result,
978    clippy::panic_in_result_fn,
979    clippy::indexing_slicing,
980    clippy::arithmetic_side_effects,
981    reason = "Standard repository test boilerplate"
982)]
983mod tests {
984    use super::*;
985    use crate::args::{default_fsearch_args, default_fsindex_args};
986    use ctb_utilities::cli::ToolResult;
987    use std::fs;
988    use tempfile::tempdir;
989
990    #[crate::ctb_test("tokio")]
991    async fn test_fsindex_and_fsearch_pipeline() {
992        use crate::args::{SearchOutputFormat, SearchSortField};
993        use crate::index_engine::run_fsindex;
994        use crate::search_engine::run_fsearch;
995        use ctb_utilities::ToolResult;
996
997        let temp = tempdir().expect("create tempdir");
998        let src_a = temp.path().join("source_a");
999        let src_b = temp.path().join("source_b");
1000        fs::create_dir_all(src_a.join("nested/deep")).expect("create src_a");
1001        fs::create_dir_all(src_b.join("sub")).expect("create src_b");
1002
1003        fs::write(src_a.join("hello.txt"), b"Hello Source A")
1004            .expect("write hello.txt");
1005        fs::write(src_a.join("nested/doc.md"), b"# Markdown document")
1006            .expect("write doc.md");
1007        fs::write(src_a.join("nested/deep/data.bin"), vec![0u8; 1024])
1008            .expect("write data.bin");
1009        #[cfg(unix)]
1010        std::os::unix::fs::symlink("hello.txt", src_a.join("link_to_hello"))
1011            .expect("create symlink");
1012
1013        fs::write(src_b.join("world.txt"), b"World Source B")
1014            .expect("write world.txt");
1015        fs::write(src_b.join("sub/extra.log"), b"log entry 1\nlog entry 2\n")
1016            .expect("write extra.log");
1017
1018        let db_path = temp.path().join("combined.cscindex.sqlite");
1019
1020        // 1. Run fsindex on source_a
1021        let mut args_a =
1022            default_fsindex_args(vec![src_a.clone()], Some(db_path.clone()));
1023        args_a.source_name = Some("source_a_tag".to_string());
1024        let res_a = run_fsindex(args_a).await.expect("run_fsindex source_a");
1025        match res_a {
1026            ToolResult::Immediate { exit_code, .. } => assert_eq!(exit_code, 0),
1027            _ => panic!("Expected immediate tool result"),
1028        }
1029
1030        // 2. append source_b into the same database
1031        let mut args_b =
1032            default_fsindex_args(vec![src_b.clone()], Some(db_path.clone()));
1033        args_b.source_name = Some("source_b_tag".to_string());
1034        let res_b = run_fsindex(args_b)
1035            .await
1036            .expect("run_fsindex source_b (append)");
1037        match res_b {
1038            ToolResult::Immediate { exit_code, .. } => assert_eq!(exit_code, 0),
1039            _ => panic!("Expected immediate tool result"),
1040        }
1041
1042        // 3. Search: filename glob "*.txt" -> should match hello.txt and world.txt across both sources
1043        let mut search_txt = default_fsearch_args(db_path.clone());
1044        search_txt.query = vec!["*.txt".to_string()];
1045        let res_search_txt =
1046            run_fsearch(search_txt).await.expect("run_fsearch *.txt");
1047        if let ToolResult::Immediate { stdout, .. } = res_search_txt {
1048            let out_str = String::from_utf8_lossy(&stdout);
1049            assert!(out_str.contains("hello.txt"));
1050            assert!(out_str.contains("world.txt"));
1051            assert!(!out_str.contains("doc.md"));
1052        } else {
1053            panic!("Expected immediate result");
1054        }
1055
1056        // 4. Search with source filter: only source_a_tag
1057        let mut search_src_a = default_fsearch_args(db_path.clone());
1058        search_src_a.query = vec!["*.txt".to_string()];
1059        search_src_a.source = Some("source_a_tag".to_string());
1060        let res_src_a = run_fsearch(search_src_a)
1061            .await
1062            .expect("run_fsearch source filter");
1063        if let ToolResult::Immediate { stdout, .. } = res_src_a {
1064            let out_str = String::from_utf8_lossy(&stdout);
1065            assert!(out_str.contains("hello.txt"));
1066            assert!(!out_str.contains("world.txt"));
1067        } else {
1068            panic!("Expected immediate result");
1069        }
1070
1071        // 5. Search with path glob "nested/*"
1072        let mut search_path = default_fsearch_args(db_path.clone());
1073        search_path.path_glob = Some("nested/*".to_string());
1074        search_path.format = SearchOutputFormat::Long;
1075        let res_path = run_fsearch(search_path)
1076            .await
1077            .expect("run_fsearch path glob");
1078        if let ToolResult::Immediate { stdout, .. } = res_path {
1079            let out_str = String::from_utf8_lossy(&stdout);
1080            assert!(out_str.contains("doc.md"));
1081            assert!(out_str.contains("data.bin"));
1082        } else {
1083            panic!("Expected immediate result");
1084        }
1085
1086        // 6. Search with JSON output and type filter (symlinks)
1087        #[cfg(unix)]
1088        {
1089            let mut search_sym = default_fsearch_args(db_path.clone());
1090            search_sym.entry_type = Some("symlink".to_string());
1091            search_sym.sort = SearchSortField::Name;
1092            search_sym.format = SearchOutputFormat::Json;
1093            let res_sym = run_fsearch(search_sym)
1094                .await
1095                .expect("run_fsearch symlink json");
1096            if let ToolResult::Immediate { stdout, .. } = res_sym {
1097                let out_str = String::from_utf8_lossy(&stdout);
1098                assert!(out_str.contains("\"filename\": \"link_to_hello\""));
1099                assert!(out_str.contains("\"symlink_target\": \"hello.txt\""));
1100            } else {
1101                panic!("Expected immediate result");
1102            }
1103        }
1104
1105        // 7. Search with size filter: >= 500 bytes (should match data.bin which is 1024 bytes)
1106        let mut search_size = default_fsearch_args(db_path.clone());
1107        search_size.size_min = Some("500".to_string());
1108        search_size.sort = SearchSortField::Size;
1109        search_size.sort_desc = true;
1110        let res_size = run_fsearch(search_size)
1111            .await
1112            .expect("run_fsearch size filter");
1113        if let ToolResult::Immediate { stdout, .. } = res_size {
1114            let out_str = String::from_utf8_lossy(&stdout);
1115            assert!(out_str.contains("data.bin"));
1116            assert!(!out_str.contains("hello.txt"));
1117        } else {
1118            panic!("Expected immediate result");
1119        }
1120
1121        // 8. Search with entry_type filter: "f" / "file"
1122        let mut search_type = default_fsearch_args(db_path.clone());
1123        search_type.entry_type = Some("f".to_string());
1124        let res_type = run_fsearch(search_type)
1125            .await
1126            .expect("run_fsearch type filter");
1127        if let ToolResult::Immediate { stdout, .. } = res_type {
1128            let out_str = String::from_utf8_lossy(&stdout);
1129            assert!(out_str.contains("hello.txt"));
1130            assert!(out_str.contains("world.txt"));
1131        }
1132    }
1133
1134    #[crate::ctb_test("tokio")]
1135    async fn test_fsindex_configurable_journal_path() {
1136        use crate::index_engine::run_fsindex;
1137
1138        let temp = tempdir().expect("create tempdir");
1139        let src = temp.path().join("src");
1140        fs::create_dir_all(&src).expect("create src");
1141        fs::write(src.join("item.txt"), b"Item content")
1142            .expect("write item.txt");
1143
1144        let custom_journal = temp.path().join("custom_index.cscjournal");
1145        let custom_desc = temp.path().join("custom_index.cscdesc");
1146
1147        let mut args = default_fsindex_args(vec![src.clone()], None);
1148        args.journal_path = Some(custom_journal.clone());
1149        args.journal_only = true;
1150
1151        let res = run_fsindex(args.clone())
1152            .await
1153            .expect("run fsindex with explicit journal_path");
1154        match res {
1155            ToolResult::Immediate { exit_code, .. } => assert_eq!(exit_code, 0),
1156            _ => panic!("Expected immediate tool result"),
1157        }
1158
1159        assert!(custom_journal.exists(), "Custom journal must exist");
1160        assert!(custom_desc.exists(), "Custom desc must exist");
1161
1162        // Running again without --resume must error
1163        let err = match run_fsindex(args).await {
1164            Err(e) => e,
1165            Ok(_) => panic!("Expected error when journal already exists"),
1166        };
1167        let err_msg = err.to_string();
1168        assert!(
1169            err_msg.contains("already exists"),
1170            "Must reject overwriting existing journal file: {err_msg}"
1171        );
1172    }
1173
1174    #[crate::ctb_test("tokio")]
1175    async fn test_fsindex_flush_deleted_files_from_index() {
1176        use crate::index_engine::run_fsindex;
1177        use crate::journal::read_journal_snapshot;
1178        use turso::{Builder, Value};
1179
1180        let temp = tempdir().expect("create tempdir");
1181        let src = temp.path().join("files");
1182        fs::create_dir_all(&src).expect("create src");
1183        fs::write(src.join("a.txt"), b"File A").expect("write a.txt");
1184        fs::write(src.join("b.txt"), b"File B").expect("write b.txt");
1185        fs::write(src.join("c.txt"), b"File C").expect("write c.txt");
1186
1187        let journal_path = temp.path().join("files.cscjournal");
1188        let db_path = temp.path().join("files.cscindex.sqlite");
1189
1190        // 1. Initial index
1191        let mut args_init =
1192            default_fsindex_args(vec![src.clone()], Some(db_path.clone()));
1193        args_init.journal_path = Some(journal_path.clone());
1194        args_init.source_name = Some("test_src".to_string());
1195        run_fsindex(args_init).await.expect("initial fsindex");
1196
1197        // Verify all 3 files exist in the database
1198        {
1199            let db_str = db_path.to_string_lossy().to_string();
1200            let db = Builder::new_local(&db_str)
1201                .experimental_index_method(true)
1202                .build()
1203                .await
1204                .expect("open db");
1205            let conn = db.connect().expect("connect db");
1206            let mut count_stmt = conn
1207                .prepare("SELECT COUNT(*) FROM entries")
1208                .await
1209                .expect("prepare count");
1210            let mut rows = count_stmt.query(()).await.expect("query count");
1211            let total: i64 = match rows
1212                .next()
1213                .await
1214                .expect("row")
1215                .expect("some row")
1216                .get_value(0)
1217            {
1218                Ok(Value::Integer(n)) => n,
1219                _ => panic!("Expected integer count"),
1220            };
1221            // 3 regular files + 1 root directory entry
1222            assert_eq!(total, 4);
1223        }
1224
1225        // 2. Delete b.txt from disk
1226        fs::remove_file(src.join("b.txt")).expect("remove b.txt");
1227
1228        let snap_before =
1229            read_journal_snapshot(&journal_path).expect("read snap");
1230        assert!(
1231            snap_before.is_committed(b"b.txt"),
1232            "Journal must contain b.txt before flush"
1233        );
1234
1235        {
1236            use ctb_formats_dcdata::dc::{
1237                DC_BEGIN_CHECKSUMMED_SECTION, DC_END_CHECKSUMMED_SECTION,
1238                DC_OPERATION_COMPLETED, DC_SECTION_DIGEST,
1239                DC_SEQUENCE_IDENTIFIER,
1240            };
1241            use ctb_formats_dcstring::{DcMixedEncode, DcMstring};
1242            use std::io::Write;
1243
1244            let mut fragment = DcMstring::new();
1245            fragment.push_char(DC_BEGIN_CHECKSUMMED_SECTION);
1246            fragment.push_char(DC_SEQUENCE_IDENTIFIER);
1247            snap_before
1248                .last_batch_id
1249                .saturating_add(1)
1250                .encode_dc_mixed(&mut fragment)
1251                .expect("sequence");
1252            fragment.push_char(DC_END_CHECKSUMMED_SECTION);
1253            fragment.push_char(DC_SECTION_DIGEST);
1254            fragment
1255                .push_checksum(ctb_utilities::format_id::DC_SHA256, &[0xFF; 32])
1256                .expect("digest");
1257            fragment.push_char(DC_OPERATION_COMPLETED);
1258            fs::OpenOptions::new()
1259                .append(true)
1260                .open(&journal_path)
1261                .expect("append journal")
1262                .write_all(fragment.payload_bytes())
1263                .expect("write invalid-digest batch");
1264        }
1265        let journal_before_flush =
1266            fs::read(&journal_path).expect("journal bytes");
1267        let mut strict_flush = default_fsindex_args(
1268            vec![journal_path.clone()],
1269            Some(db_path.clone()),
1270        );
1271        strict_flush.flush_deleted = true;
1272        strict_flush.source_name = Some("test_src".to_string());
1273        assert!(
1274            run_fsindex(strict_flush).await.is_err(),
1275            "Strict flush must reject interior digest mismatch"
1276        );
1277
1278        // 3. Run fsindex again with the journal path and --flush-deleted
1279        let mut args_flush = default_fsindex_args(
1280            vec![journal_path.clone()],
1281            Some(db_path.clone()),
1282        );
1283        args_flush.flush_deleted = true;
1284        args_flush.allow_journal_errors = true;
1285        args_flush.source_name = Some("test_src".to_string());
1286        let res_flush =
1287            run_fsindex(args_flush).await.expect("run fsindex flush");
1288        if let ToolResult::Immediate { stdout, .. } = res_flush {
1289            let out_str = String::from_utf8_lossy(&stdout);
1290            assert!(
1291                out_str.contains("Entries flushed:  1"),
1292                "Output must report 1 flushed entry: {out_str}"
1293            );
1294        } else {
1295            panic!("Expected immediate tool result");
1296        }
1297
1298        // 4. Verify b.txt is gone from database, while a.txt and c.txt remain
1299        let db_str = db_path.to_string_lossy().to_string();
1300        let db = Builder::new_local(&db_str)
1301            .experimental_index_method(true)
1302            .build()
1303            .await
1304            .expect("open db");
1305        let conn = db.connect().expect("connect db");
1306
1307        let mut check_b = conn
1308            .prepare("SELECT COUNT(*) FROM entries WHERE filename = 'b.txt'")
1309            .await
1310            .expect("prepare check_b");
1311        let mut b_rows = check_b.query(()).await.expect("query b");
1312        let b_count: i64 = match b_rows
1313            .next()
1314            .await
1315            .expect("row")
1316            .expect("some row")
1317            .get_value(0)
1318        {
1319            Ok(Value::Integer(n)) => n,
1320            _ => panic!("Expected integer count"),
1321        };
1322        assert_eq!(b_count, 0, "b.txt must be flushed from SQLite index");
1323
1324        let mut check_a = conn
1325            .prepare("SELECT COUNT(*) FROM entries WHERE filename = 'a.txt'")
1326            .await
1327            .expect("prepare check_a");
1328        let mut a_rows = check_a.query(()).await.expect("query a");
1329        let a_count: i64 = match a_rows
1330            .next()
1331            .await
1332            .expect("row")
1333            .expect("some row")
1334            .get_value(0)
1335        {
1336            Ok(Value::Integer(n)) => n,
1337            _ => panic!("Expected integer count"),
1338        };
1339        assert_eq!(a_count, 1, "a.txt must remain in SQLite index");
1340
1341        // 5. Verify the journal file was completely untouched
1342        assert_eq!(
1343            fs::read(&journal_path).expect("journal after flush"),
1344            journal_before_flush
1345        );
1346        let snap_after = crate::journal::read_journal_snapshot_with_policy(
1347            &journal_path,
1348            &ctb_formats_dcstring::DcProjectionPolicy::forgiving(),
1349        )
1350        .expect("read snap after");
1351        assert!(
1352            snap_after.is_committed(b"b.txt"),
1353            "Journal file must be untouched and still contain b.txt"
1354        );
1355    }
1356
1357    #[crate::ctb_test("tokio")]
1358    async fn test_fsindex_appended_indices_deduplicated_by_path() {
1359        use crate::index_engine::run_fsindex;
1360        use turso::{Builder, Value};
1361
1362        let temp = tempdir().expect("create tempdir");
1363        let src1 = temp.path().join("src1");
1364        let src2 = temp.path().join("src2");
1365        fs::create_dir_all(&src1).expect("create src1");
1366        fs::create_dir_all(&src2).expect("create src2");
1367
1368        // Version 1 of shared file
1369        fs::write(src1.join("shared.txt"), b"version 1").expect("write v1");
1370        // Version 2 of shared file (longer content)
1371        fs::write(src2.join("shared.txt"), b"version 2 longer content")
1372            .expect("write v2");
1373
1374        let db_path = temp.path().join("dedup.cscindex.sqlite");
1375
1376        // Index source 1
1377        let mut args1 =
1378            default_fsindex_args(vec![src1.clone()], Some(db_path.clone()));
1379        args1.source_name = Some("source_1".to_string());
1380        run_fsindex(args1).await.expect("index src1");
1381
1382        // Index source 2 into same database (append)
1383        let mut args2 =
1384            default_fsindex_args(vec![src2.clone()], Some(db_path.clone()));
1385        args2.source_name = Some("source_2".to_string());
1386        run_fsindex(args2).await.expect("index src2");
1387
1388        // Verify deduplication: exactly 1 entry for shared.txt with updated size
1389        let db_str = db_path.to_string_lossy().to_string();
1390        let db = Builder::new_local(&db_str)
1391            .experimental_index_method(true)
1392            .build()
1393            .await
1394            .expect("open db");
1395        let conn = db.connect().expect("connect db");
1396
1397        let mut stmt = conn
1398            .prepare("SELECT COUNT(*), size, s.name FROM entries e JOIN sources s ON e.source_id = s.id WHERE e.path = 'shared.txt'")
1399            .await
1400            .expect("prepare stmt");
1401        let mut rows = stmt.query(()).await.expect("query");
1402        let row = rows.next().await.expect("row").expect("some row");
1403
1404        let count: i64 = match row.get_value(0) {
1405            Ok(Value::Integer(n)) => n,
1406            _ => panic!("Expected count integer"),
1407        };
1408        let size: i64 = match row.get_value(1) {
1409            Ok(Value::Integer(s)) => s,
1410            _ => panic!("Expected size integer"),
1411        };
1412        let src_name: String = match row.get_value(2) {
1413            Ok(Value::Text(s)) => s,
1414            _ => panic!("Expected source name text"),
1415        };
1416
1417        assert_eq!(
1418            count, 1,
1419            "Appended index must deduplicate entries with the same path"
1420        );
1421        assert_eq!(
1422            size, 24,
1423            "Entry must be updated with the latest appended data"
1424        );
1425        assert_eq!(
1426            src_name, "source_2",
1427            "Source tag must be updated to the latest source"
1428        );
1429    }
1430
1431    #[crate::ctb_test("tokio")]
1432    async fn test_fsindex_and_fsearch_fulltext_and_context() {
1433        use crate::index_engine::run_fsindex;
1434        use crate::search_engine::run_fsearch;
1435
1436        let temp = tempdir().expect("create tempdir");
1437        let src = temp.path().join("docs");
1438        fs::create_dir_all(&src).expect("create src");
1439
1440        fs::write(
1441            src.join("sample.txt"),
1442            b"Line 1 introductory text\nLine 2 contains unique_phrase_xyz for search\nLine 3 conclusion text\n",
1443        )
1444        .expect("write sample.txt");
1445
1446        fs::write(
1447            src.join("other.txt"),
1448            b"Line 1 standard words\nLine 2 another normal sentence\n",
1449        )
1450        .expect("write other.txt");
1451
1452        let db_path = temp.path().join("fulltext.cscindex.sqlite");
1453
1454        // Index with fulltext enabled
1455        let mut idx_args =
1456            default_fsindex_args(vec![src.clone()], Some(db_path.clone()));
1457        idx_args.fulltext = true;
1458        idx_args.fulltext_max = "50k".to_string();
1459        run_fsindex(idx_args)
1460            .await
1461            .expect("run fsindex with fulltext");
1462
1463        // 1. Keyword search on text content (-kt / --keyword-text)
1464        let mut search_kt = default_fsearch_args(db_path.clone());
1465        search_kt.keyword_text = Some("unique_phrase_xyz".to_string());
1466        let res_kt = run_fsearch(search_kt).await.expect("search -kt");
1467        if let ToolResult::Immediate { stdout, .. } = res_kt {
1468            let s = String::from_utf8_lossy(&stdout);
1469            assert!(
1470                s.contains("sample.txt"),
1471                "Must find sample.txt by content: {s}"
1472            );
1473            assert!(!s.contains("other.txt"), "Must not find other.txt");
1474        } else {
1475            panic!("Expected immediate result");
1476        }
1477
1478        // 2. Search with context (-C 1)
1479        let mut search_ctx = default_fsearch_args(db_path.clone());
1480        search_ctx.keyword_text = Some("unique_phrase_xyz".to_string());
1481        search_ctx.context = Some(1);
1482        let res_ctx =
1483            run_fsearch(search_ctx).await.expect("search with context");
1484        if let ToolResult::Immediate { stdout, .. } = res_ctx {
1485            let s = String::from_utf8_lossy(&stdout);
1486            assert!(s.contains("sample.txt"));
1487            assert!(
1488                s.contains("1- Line 1 introductory text"),
1489                "Must show line 1 context: {s}"
1490            );
1491            assert!(
1492                s.contains("2: Line 2 contains unique_phrase_xyz for search"),
1493                "Must show matching line 2: {s}"
1494            );
1495            assert!(
1496                s.contains("3- Line 3 conclusion text"),
1497                "Must show line 3 context: {s}"
1498            );
1499        } else {
1500            panic!("Expected immediate result");
1501        }
1502
1503        // 3. Auto-resolved keyword search with multiple terms
1504        let mut search_multi = default_fsearch_args(db_path.clone());
1505        search_multi.query =
1506            vec!["unique_phrase_xyz".to_string(), "conclusion".to_string()];
1507        let res_multi = run_fsearch(search_multi)
1508            .await
1509            .expect("search multiple positional terms");
1510        if let ToolResult::Immediate { stdout, .. } = res_multi {
1511            let s = String::from_utf8_lossy(&stdout);
1512            assert!(
1513                s.contains("sample.txt"),
1514                "Multiple terms must match sample.txt: {s}"
1515            );
1516        } else {
1517            panic!("Expected immediate result");
1518        }
1519
1520        // 4. Auto-resolved glob search with wildcard '*'
1521        let mut search_glob = default_fsearch_args(db_path.clone());
1522        search_glob.query = vec!["*.txt".to_string()];
1523        let res_glob =
1524            run_fsearch(search_glob).await.expect("search glob *.txt");
1525        if let ToolResult::Immediate { stdout, .. } = res_glob {
1526            let s = String::from_utf8_lossy(&stdout);
1527            assert!(s.contains("sample.txt"));
1528            assert!(s.contains("other.txt"));
1529        } else {
1530            panic!("Expected immediate result");
1531        }
1532
1533        // 5. Orthogonal flag: -kn (keyword on filename only)
1534        let mut search_kn = default_fsearch_args(db_path.clone());
1535        search_kn.keyword_name = Some("unique_phrase_xyz".to_string());
1536        let res_kn = run_fsearch(search_kn).await.expect("search -kn");
1537        if let ToolResult::Immediate { stdout, .. } = res_kn {
1538            let s = String::from_utf8_lossy(&stdout);
1539            assert!(
1540                !s.contains("sample.txt"),
1541                "-kn must not match text content in sample.txt: {s}"
1542            );
1543        } else {
1544            panic!("Expected immediate result");
1545        }
1546
1547        // 6. Multi-argument keyword search (-k with multiple parameters vs single argument with space)
1548        let mut search_k_multi = default_fsearch_args(db_path.clone());
1549        search_k_multi.keyword = vec!["sample".to_string(), "txt".to_string()];
1550        let res_k_multi = run_fsearch(search_k_multi)
1551            .await
1552            .expect("search -k multiple terms");
1553        let s_multi = if let ToolResult::Immediate { stdout, .. } = res_k_multi
1554        {
1555            String::from_utf8_lossy(&stdout).to_string()
1556        } else {
1557            panic!("Expected immediate result");
1558        };
1559
1560        let mut search_k_joined = default_fsearch_args(db_path.clone());
1561        search_k_joined.keyword = vec!["sample txt".to_string()];
1562        let res_k_joined = run_fsearch(search_k_joined)
1563            .await
1564            .expect("search -k single term with space");
1565        let s_joined =
1566            if let ToolResult::Immediate { stdout, .. } = res_k_joined {
1567                String::from_utf8_lossy(&stdout).to_string()
1568            } else {
1569                panic!("Expected immediate result");
1570            };
1571
1572        assert_eq!(
1573            s_multi, s_joined,
1574            "-k 'a' 'b' must produce identical results to -k 'a b'"
1575        );
1576        assert!(s_multi.contains("sample.txt"));
1577
1578        // 7. Rejection of conflicting explicit option and positional query
1579        let mut search_conflict = default_fsearch_args(db_path.clone());
1580        search_conflict.keyword = vec!["sample".to_string()];
1581        search_conflict.query =
1582            vec!["unexpected_trailing_positional".to_string()];
1583        let err_conflict = run_fsearch(search_conflict)
1584            .await
1585            .err()
1586            .expect("must fail on mixed explicit option and query");
1587        assert!(err_conflict.to_string().contains("Cannot specify both explicit search filter flags and positional query terms"));
1588    }
1589
1590    #[crate::ctb_test("tokio")]
1591    async fn test_fsindex_without_fulltext_schema() {
1592        use crate::index_engine::run_fsindex;
1593        use crate::search_engine::run_fsearch;
1594        use turso::{Builder, Value};
1595
1596        let temp = tempdir().expect("create tempdir");
1597        let src = temp.path().join("files");
1598        fs::create_dir_all(&src).expect("create src");
1599        fs::write(src.join("test.txt"), b"Normal content").expect("write file");
1600
1601        let db_path = temp.path().join("nofulltext.cscindex.sqlite");
1602
1603        // Index with fulltext disabled (default)
1604        let idx_args =
1605            default_fsindex_args(vec![src.clone()], Some(db_path.clone()));
1606        run_fsindex(idx_args)
1607            .await
1608            .expect("run fsindex without fulltext");
1609
1610        // Check SQLite schema: full_text column must NOT exist
1611        let db_str = db_path.to_string_lossy().to_string();
1612        let db = Builder::new_local(&db_str)
1613            .experimental_index_method(true)
1614            .build()
1615            .await
1616            .expect("open db");
1617        let conn = db.connect().expect("connect db");
1618        let mut stmt = conn
1619            .prepare("PRAGMA table_info(entries)")
1620            .await
1621            .expect("pragma table_info");
1622        let mut rows = stmt.query(()).await.expect("query");
1623        let mut has_full_text_col = false;
1624        while let Some(row) = rows.next().await.expect("row") {
1625            if let Ok(Value::Text(col)) = row.get_value(1) {
1626                if col == "full_text" {
1627                    has_full_text_col = true;
1628                }
1629            }
1630        }
1631        assert!(
1632            !has_full_text_col,
1633            "entries table must NOT contain full_text column when fulltext is disabled"
1634        );
1635
1636        // Searching with -kt or -C on non-fulltext database must error
1637        let mut search_kt = default_fsearch_args(db_path.clone());
1638        search_kt.keyword_text = Some("Normal".to_string());
1639        let err = run_fsearch(search_kt)
1640            .await
1641            .err()
1642            .expect("must fail -kt on non-fulltext db");
1643        assert!(err.to_string().contains("not indexed with --fulltext"));
1644
1645        let mut search_ctx = default_fsearch_args(db_path.clone());
1646        search_ctx.query = vec!["Normal".to_string()];
1647        search_ctx.context = Some(2);
1648        let err_ctx = run_fsearch(search_ctx)
1649            .await
1650            .err()
1651            .expect("must fail context on non-fulltext db");
1652        assert!(err_ctx.to_string().contains("not indexed with --fulltext"));
1653    }
1654}