Skip to main content

code_kb_core/
sync.rs

1use rusqlite::Connection;
2use sha2::Digest;
3use std::path::{Path, PathBuf};
4use std::process::Command;
5use thiserror::Error;
6use tracing::{info, warn};
7
8use crate::queries;
9use crate::workspace::Workspace;
10
11#[derive(Debug, Error)]
12pub enum SyncError {
13    #[error(
14        "julie-extract not found. Put it on PATH or set JULIE_EXTRACT_BIN. Download: https://github.com/anortham/julie-extractors/releases"
15    )]
16    BinaryNotFound,
17    #[error("Extractor failed with status {0}: {1}")]
18    ExtractionFailed(i32, String),
19    #[error("IO error during synchronization: {0}")]
20    Io(#[from] std::io::Error),
21    #[error("Database error during synchronization: {0}")]
22    Db(#[from] rusqlite::Error),
23    #[error("Database error: {0}")]
24    DbInit(#[from] crate::db::DbError),
25    #[error("workspace traversal failed: {0}")]
26    Walk(#[from] ignore::Error),
27}
28
29pub const PINNED_JULIE_VERSION: &str = "3.1.1";
30
31/// Extraction level code-kb asks for on a new artifact: symbol core plus structural facts,
32/// without the identifier, literal, and source-region tables code-kb never reads.
33pub const EXTRACTION_LEVEL: &str = "facts";
34
35static CACHED_JULIE_BIN: std::sync::OnceLock<Option<(PathBuf, String)>> =
36    std::sync::OnceLock::new();
37
38/// Discovers the `julie-extract` binary and caches the result.
39///
40/// The first candidate whose version matches the pin wins. When none matches, the first
41/// candidate found is used and a warning is logged.
42pub fn find_julie_extract_binary() -> Option<PathBuf> {
43    installed_extractor().map(|(bin, _)| bin)
44}
45
46/// Version reported by the `julie-extract` binary in use, or the pin when none was found.
47pub fn installed_extractor_version() -> String {
48    installed_extractor()
49        .map(|(_, version)| version)
50        .unwrap_or_else(|| PINNED_JULIE_VERSION.to_string())
51}
52
53fn installed_extractor() -> Option<(PathBuf, String)> {
54    CACHED_JULIE_BIN
55        .get_or_init(|| {
56            let candidates: Vec<(PathBuf, String)> = julie_extract_candidates()
57                .into_iter()
58                .filter_map(|bin| extractor_version(&bin).map(|version| (bin, version)))
59                .collect();
60            let pinned = candidates
61                .iter()
62                .find(|(_, version)| version == PINNED_JULIE_VERSION)
63                .cloned();
64            if pinned.is_some() {
65                return pinned;
66            }
67            let first = candidates.into_iter().next()?;
68            tracing::warn!(
69                found = %first.1,
70                pinned = %PINNED_JULIE_VERSION,
71                binary = %first.0.display(),
72                "julie-extract version differs from pinned version; AST facts may drift"
73            );
74            Some(first)
75        })
76        .clone()
77}
78
79fn extractor_version(bin: &Path) -> Option<String> {
80    let output = Command::new(bin).arg("--version").output().ok()?;
81    let text = String::from_utf8_lossy(&output.stdout);
82    text.split_whitespace().last().map(str::to_string)
83}
84
85fn julie_extract_candidates() -> Vec<PathBuf> {
86    let exe_name = if cfg!(windows) {
87        "julie-extract.exe"
88    } else {
89        "julie-extract"
90    };
91    let mut candidates = Vec::new();
92
93    if let Ok(path_str) = std::env::var("JULIE_EXTRACT_BIN") {
94        candidates.push(PathBuf::from(path_str));
95    }
96
97    if let Some(parent) = std::env::current_exe()
98        .ok()
99        .and_then(|p| p.parent().map(|d| d.to_path_buf()))
100    {
101        candidates.push(parent.join(exe_name));
102        candidates.push(parent.join(".tools").join(exe_name));
103    }
104
105    if let Ok(cwd) = std::env::current_dir() {
106        let mut probe = cwd;
107        loop {
108            candidates.push(probe.join(".tools").join(exe_name));
109            match probe.parent() {
110                Some(parent) if parent != probe => probe = parent.to_path_buf(),
111                _ => break,
112            }
113        }
114    }
115
116    if let Ok(p) = which::which("julie-extract") {
117        candidates.push(p);
118    }
119
120    candidates
121        .into_iter()
122        .filter(|p| p.is_file())
123        .map(|p| crate::workspace::normalize_path(&p))
124        .collect()
125}
126
127/// Run julie-extract command with arguments.
128pub fn execute_julie_extract(args: &[&str]) -> Result<String, SyncError> {
129    let bin = find_julie_extract_binary().ok_or(SyncError::BinaryNotFound)?;
130
131    let mut attempts = 0;
132    loop {
133        let output = Command::new(&bin)
134            .args(args)
135            .output()
136            .map_err(SyncError::Io)?;
137
138        if output.status.success() {
139            return Ok(String::from_utf8_lossy(&output.stdout).to_string());
140        }
141
142        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
143        // Retry on database lock / busy collisions with backoff
144        if (stderr.contains("database is locked")
145            || stderr.contains("busy")
146            || stderr.contains("SQLITE_BUSY"))
147            && attempts < 5
148        {
149            attempts += 1;
150            std::thread::sleep(std::time::Duration::from_millis(50 * (1 << attempts)));
151            continue;
152        }
153
154        let code = output.status.code().unwrap_or(-1);
155        return Err(SyncError::ExtractionFailed(code, stderr));
156    }
157}
158
159/// Tier 1 & Incremental Update: updates a single file in the database.
160pub fn update_file(workspace: &Workspace, db_path: &Path, rel_path: &str) -> Result<(), SyncError> {
161    let root_str = workspace.canonical_root.to_string_lossy();
162    let db_str = db_path.to_string_lossy();
163
164    execute_julie_extract(&[
165        "update", "--root", &root_str, "--db", &db_str, "--file", rel_path,
166    ])?;
167
168    Ok(())
169}
170
171/// Delete a file's extraction records from the database.
172pub fn delete_file(workspace: &Workspace, db_path: &Path, rel_path: &str) -> Result<(), SyncError> {
173    let root_str = workspace.canonical_root.to_string_lossy();
174    let db_str = db_path.to_string_lossy();
175
176    execute_julie_extract(&[
177        "delete", "--root", &root_str, "--db", &db_str, "--file", rel_path,
178    ])?;
179
180    Ok(())
181}
182
183/// Initial or full scan to build/refresh the database.
184///
185/// An artifact the extractor cannot read (empty, torn, or older schema) is removed and
186/// rebuilt from scratch.
187pub fn scan_workspace(workspace: &Workspace, db_path: &Path, force: bool) -> Result<(), SyncError> {
188    let root_str = workspace.canonical_root.to_string_lossy();
189    let db_str = db_path.to_string_lossy();
190    let own_pid = std::process::id().to_string();
191
192    ensure_index_dir(db_path)?;
193
194    let scan_args = |new_artifact: bool| {
195        let mut args = vec!["scan", "--root", &*root_str, "--db", &*db_str];
196        if new_artifact {
197            args.extend(["--level", EXTRACTION_LEVEL]);
198        }
199        if cfg!(unix) {
200            args.extend(["--parent-pid", &*own_pid]);
201        }
202        if force {
203            args.push("--force");
204        }
205        args
206    };
207
208    match execute_julie_extract(&scan_args(!db_path.exists())) {
209        Ok(_) => {}
210        Err(SyncError::ExtractionFailed(_, stderr))
211            if stderr.contains("schema_incompatible") && db_path.exists() =>
212        {
213            warn!("Extractor cannot read the existing artifact; rebuilding from scratch");
214            remove_artifact_files(db_path)?;
215            execute_julie_extract(&scan_args(true))?;
216        }
217        Err(e) => return Err(e),
218    }
219
220    // Ensure FTS5 index is built and triggers are established
221    let _ = crate::db::ensure_fts_index_path(db_path);
222
223    Ok(())
224}
225
226/// Rebuilds the index when it was written by a `julie-extract` other than the one in use or
227/// at another extraction level. Returns `true` when a rebuild ran. The old artifact is removed first because the
228/// extractor refuses to write into an artifact with an older schema.
229pub fn ensure_index_matches_extractor(
230    workspace: &Workspace,
231    db_path: &Path,
232    extractor_version: &str,
233) -> Result<bool, SyncError> {
234    if !db_path.exists() {
235        return Ok(false);
236    }
237    let metadata = |key: &str| -> Option<String> {
238        let conn = crate::db::open_read_only(db_path).ok()?;
239        conn.query_row(
240            "SELECT value FROM artifact_metadata WHERE key = ?1",
241            [key],
242            |r| r.get(0),
243        )
244        .ok()
245    };
246    let Some(recorded) = metadata("binary_version") else {
247        return Ok(false);
248    };
249    let level = metadata("index_level").unwrap_or_else(|| "full".to_string());
250    if recorded == extractor_version
251        && level == EXTRACTION_LEVEL
252        && !has_file_written_by_another_extractor(db_path, extractor_version)
253    {
254        return Ok(false);
255    }
256    info!(
257        recorded = %recorded,
258        installed = %extractor_version,
259        level = %level,
260        wanted_level = %EXTRACTION_LEVEL,
261        "Index holds rows from a different julie-extract version or level; rebuilding"
262    );
263    remove_artifact_files(db_path)?;
264    scan_workspace(workspace, db_path, true)?;
265    Ok(true)
266}
267
268/// A `julie-extract update` run by a newer binary stamps its version into `artifact_metadata`
269/// but leaves every unchanged file's rows as the older binary wrote them, so the guard also
270/// checks the revision that last wrote each file.
271fn has_file_written_by_another_extractor(db_path: &Path, extractor_version: &str) -> bool {
272    let Ok(conn) = crate::db::open_read_only(db_path) else {
273        return false;
274    };
275    conn.query_row(
276        "SELECT 1 FROM files f
277         JOIN extraction_revisions r ON r.revision_id = f.last_revision_id
278         WHERE r.binary_version != ?1
279         LIMIT 1",
280        [extractor_version],
281        |_| Ok(true),
282    )
283    .unwrap_or(false)
284}
285
286fn remove_artifact_files(db_path: &Path) -> Result<(), SyncError> {
287    for suffix in ["", "-wal", "-shm"] {
288        let sidecar = PathBuf::from(format!("{}{suffix}", db_path.display()));
289        match std::fs::remove_file(&sidecar) {
290            Ok(()) => {}
291            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
292            Err(e) => return Err(e.into()),
293        }
294    }
295    Ok(())
296}
297
298/// Check if disk content matches the stored hash in the database.
299pub fn compute_content_hash_matches(disk_bytes: &[u8], stored_hash: &str) -> bool {
300    if stored_hash.starts_with("blake3:") {
301        let b3 = format!("blake3:{}", blake3::hash(disk_bytes).to_hex());
302        b3 == stored_hash
303    } else {
304        let b3 = blake3::hash(disk_bytes).to_hex().to_string();
305        if b3 == stored_hash {
306            return true;
307        }
308        let mut hasher = sha2::Sha256::new();
309        sha2::Digest::update(&mut hasher, disk_bytes);
310        let sha = hex::encode(sha2::Digest::finalize(hasher));
311        sha == stored_hash || format!("sha256:{sha}") == stored_hash
312    }
313}
314
315/// Tier 2: Just-In-Time Staleness Guard
316/// Checks if a file on disk has been modified since it was indexed in SQLite.
317/// If dirty or missing from index, re-extracts the file synchronously (< 5ms).
318pub fn ensure_fresh_file(
319    workspace: &Workspace,
320    db_path: &Path,
321    conn: &Connection,
322    rel_path: &str,
323) -> Result<bool, SyncError> {
324    let abs_path = workspace.canonical_root.join(rel_path);
325    let meta = match std::fs::metadata(&abs_path) {
326        Ok(meta) => meta,
327        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
328            let existing_file = queries::get_file(conn, rel_path).map_err(|e| match e {
329                queries::QueryError::Sqlite(err) => SyncError::Db(err),
330                _ => SyncError::Db(rusqlite::Error::QueryReturnedNoRows),
331            })?;
332            if existing_file.is_some() {
333                delete_file(workspace, db_path, rel_path)?;
334                return Ok(true);
335            }
336            return Ok(false);
337        }
338        Err(error) => return Err(SyncError::Io(error)),
339    };
340
341    if meta.is_dir() {
342        return Ok(false);
343    }
344
345    let disk_bytes = meta.len() as i64;
346
347    // Look up file in SQLite files table
348    let existing_file = queries::get_file(conn, rel_path).map_err(|e| match e {
349        queries::QueryError::Sqlite(err) => SyncError::Db(err),
350        _ => SyncError::Db(rusqlite::Error::QueryReturnedNoRows),
351    })?;
352
353    let is_dirty = match existing_file {
354        None => true, // Not yet in index
355        Some(f) => {
356            // Fast check: byte count difference
357            if f.content_bytes != disk_bytes {
358                true
359            } else {
360                let disk_content = std::fs::read(&abs_path)?;
361                !compute_content_hash_matches(&disk_content, &f.content_hash)
362            }
363        }
364    };
365
366    if is_dirty {
367        let stored_root: Option<String> = conn
368            .query_row(
369                "SELECT value FROM artifact_metadata WHERE key = 'root_path'",
370                [],
371                |r| r.get(0),
372            )
373            .ok();
374        if let Some(r) = stored_root
375            && !crate::workspace::paths_equal(Path::new(&r), &workspace.canonical_root)
376        {
377            crate::db::retarget_artifact_root(db_path, &workspace.canonical_root)?;
378        }
379
380        update_file(workspace, db_path, rel_path)?;
381        return Ok(true);
382    }
383
384    Ok(false)
385}
386
387/// Cold-Start Reconciliation Report
388#[derive(Debug, Default)]
389pub struct ReconcileReport {
390    pub added: Vec<String>,
391    pub modified: Vec<String>,
392    pub deleted: Vec<String>,
393}
394
395fn extract_error_path(err: &ignore::Error) -> Option<&Path> {
396    match err {
397        ignore::Error::WithPath { path, .. } => Some(path.as_path()),
398        ignore::Error::WithDepth { err, .. } => extract_error_path(err),
399        ignore::Error::WithLineNumber { err, .. } => extract_error_path(err),
400        ignore::Error::Loop { ancestor, .. } => Some(ancestor.as_path()),
401        _ => None,
402    }
403}
404
405/// Cold-start background sweep: checks filesystem against SQLite `files` records.
406/// Streams disk checks and uses an in-memory SQLite index to eliminate repository-wide heap HashMaps.
407/// Creates a missing index. A git worktree copies its parent repository's index and
408/// reconciles it against the worktree files, which is much faster than a full scan;
409/// anything else runs a full scan.
410pub fn create_index(workspace: &Workspace, db_path: &Path) -> Result<(), SyncError> {
411    if let Some(parent_db) = parent_repository_db(&workspace.canonical_root)
412        && copy_parent_index(workspace, db_path, &parent_db)
413    {
414        return Ok(());
415    }
416    scan_workspace(workspace, db_path, false)
417}
418
419/// Creates the index directory. A `.code-kb` directory also gets a `.gitignore` that
420/// hides it from git, so no project `.gitignore` edit is ever needed. Any other
421/// directory is left alone: a `*` ignore file there would hide the user's own files
422/// from the extractor and from git.
423fn ensure_index_dir(db_path: &Path) -> std::io::Result<()> {
424    let Some(dir) = db_path.parent() else {
425        return Ok(());
426    };
427    std::fs::create_dir_all(dir)?;
428    if dir.file_name().is_none_or(|name| name != ".code-kb") {
429        return Ok(());
430    }
431    let gitignore = dir.join(".gitignore");
432    if !gitignore.exists() {
433        std::fs::write(gitignore, "*\n")?;
434    }
435    Ok(())
436}
437
438fn parent_repository_db(root: &Path) -> Option<PathBuf> {
439    let git_marker = root.join(".git");
440    if !git_marker.is_file() {
441        return None;
442    }
443    let git_content = std::fs::read_to_string(&git_marker).ok()?;
444    let gitdir = git_content
445        .lines()
446        .find_map(|l| l.strip_prefix("gitdir:"))?
447        .trim();
448    let gitdir = Path::new(gitdir);
449    let mut probe = if gitdir.is_absolute() {
450        gitdir.to_path_buf()
451    } else {
452        root.join(gitdir)
453    };
454    while let Some(parent) = probe.parent() {
455        if parent == probe {
456            break;
457        }
458        if parent.join(".git").exists() {
459            let db = parent.join(".code-kb").join("artifact.db");
460            return db.exists().then_some(db);
461        }
462        probe = parent.to_path_buf();
463    }
464    None
465}
466
467fn copy_parent_index(workspace: &Workspace, db_path: &Path, parent_db: &Path) -> bool {
468    let flushed = crate::db::open_read_write(parent_db)
469        .map(|conn| crate::db::checkpoint_truncate(&conn).is_ok())
470        .unwrap_or(false);
471    if !flushed {
472        return false;
473    }
474    if ensure_index_dir(db_path).is_err() || std::fs::copy(parent_db, db_path).is_err() {
475        return false;
476    }
477    info!(from = %parent_db.display(), to = %db_path.display(), "Worktree fast-path: copied parent database, reconciling");
478    let reconciled = crate::db::retarget_artifact_root(db_path, &workspace.canonical_root)
479        .and_then(|_| crate::db::ensure_fts_index_path(db_path))
480        .is_ok()
481        && crate::db::open_read_only(db_path)
482            .ok()
483            .and_then(|conn| reconcile_offline_edits(workspace, db_path, &conn).ok())
484            .is_some();
485    if !reconciled {
486        warn!(
487            "Failed to retarget worktree database root; removing copied db and falling back to full scan"
488        );
489        let _ = std::fs::remove_file(db_path);
490    }
491    reconciled
492}
493
494pub fn reconcile_offline_edits(
495    workspace: &Workspace,
496    db_path: &Path,
497    conn: &Connection,
498) -> Result<ReconcileReport, SyncError> {
499    // Ensure artifact_metadata root_path matches workspace canonical root
500    // (self-heals worktrees where artifact.db was copied from a parent repository)
501    let stored_root: Option<String> = conn
502        .query_row(
503            "SELECT value FROM artifact_metadata WHERE key = 'root_path'",
504            [],
505            |r| r.get(0),
506        )
507        .ok();
508    if let Some(r) = stored_root
509        && !crate::workspace::paths_equal(Path::new(&r), &workspace.canonical_root)
510    {
511        crate::db::retarget_artifact_root(db_path, &workspace.canonical_root)?;
512    }
513
514    let mut report = ReconcileReport::default();
515
516    // In-memory table to track paths seen on disk without allocating repository-wide HashMaps in heap
517    let temp_conn = Connection::open_in_memory().map_err(SyncError::Db)?;
518    temp_conn
519        .execute(
520            "CREATE TABLE _seen (path TEXT COLLATE NOCASE PRIMARY KEY)",
521            [],
522        )
523        .map_err(SyncError::Db)?;
524
525    let mut insert_seen_stmt = temp_conn
526        .prepare("INSERT OR IGNORE INTO _seen (path) VALUES (?1)")
527        .map_err(SyncError::Db)?;
528
529    let mut check_file_stmt = conn
530        .prepare("SELECT content_bytes, content_hash FROM files WHERE path = ?1")
531        .map_err(SyncError::Db)?;
532
533    let mut walker = ignore::WalkBuilder::new(&workspace.canonical_root);
534    walker
535        .standard_filters(true)
536        .hidden(false)
537        .add_custom_ignore_filename(".julieignore")
538        .add_custom_ignore_filename(".code-kb-ignore")
539        .add_custom_ignore_filename(".codekbignore")
540        .filter_entry(|entry| {
541            let name = entry.file_name().to_string_lossy();
542            !crate::workspace::is_hard_excluded(&name)
543        });
544    let walker = walker.build();
545
546    temp_conn
547        .execute("BEGIN TRANSACTION", [])
548        .map_err(SyncError::Db)?;
549
550    let mut unreadable_prefixes: Vec<String> = Vec::new();
551
552    for result in walker {
553        let entry = match result {
554            Ok(e) => e,
555            Err(e) => {
556                warn!("Reconciliation walker encountered error: {e}");
557                if let Some(path) = extract_error_path(&e) {
558                    let norm_path = dunce::simplified(path);
559                    if let Some(rel) =
560                        crate::workspace::strip_prefix_lossy(norm_path, &workspace.canonical_root)
561                    {
562                        unreadable_prefixes.push(crate::workspace::to_forward_slash(rel));
563                    }
564                }
565                continue;
566            }
567        };
568
569        if entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
570            let path = entry.path();
571            let norm_path = dunce::simplified(path);
572            if let Some(rel) =
573                crate::workspace::strip_prefix_lossy(norm_path, &workspace.canonical_root)
574            {
575                let rel_str = crate::workspace::to_forward_slash(rel);
576                if crate::workspace::is_hard_excluded(&rel_str) {
577                    continue;
578                }
579                let bytes = match entry.metadata() {
580                    Ok(m) => m.len() as i64,
581                    Err(e) => {
582                        warn!("Failed to read metadata for '{}': {e}", path.display());
583                        let _ = insert_seen_stmt.execute([&rel_str]);
584                        continue;
585                    }
586                };
587
588                insert_seen_stmt
589                    .execute([&rel_str])
590                    .map_err(SyncError::Db)?;
591
592                let mut rows = check_file_stmt.query([&rel_str]).map_err(SyncError::Db)?;
593
594                if let Some(row) = rows.next().map_err(SyncError::Db)? {
595                    let indexed_bytes: i64 = row.get(0).map_err(SyncError::Db)?;
596                    let stored_hash: String = row.get(1).map_err(SyncError::Db)?;
597
598                    let is_modified = if indexed_bytes != bytes {
599                        true
600                    } else {
601                        match std::fs::read(path) {
602                            Ok(content) => !compute_content_hash_matches(&content, &stored_hash),
603                            Err(e) => {
604                                warn!(
605                                    "Failed to read '{}' for hash verification: {e}",
606                                    path.display()
607                                );
608                                false
609                            }
610                        }
611                    };
612
613                    if is_modified {
614                        report.modified.push(rel_str);
615                    }
616                } else {
617                    report.added.push(rel_str);
618                }
619            }
620        }
621    }
622
623    temp_conn.execute("COMMIT", []).map_err(SyncError::Db)?;
624
625    let mut files_stmt = conn
626        .prepare("SELECT path FROM files")
627        .map_err(SyncError::Db)?;
628
629    let mut exists_seen_stmt = temp_conn
630        .prepare("SELECT 1 FROM _seen WHERE path = ?1")
631        .map_err(SyncError::Db)?;
632
633    let mut file_rows = files_stmt.query([]).map_err(SyncError::Db)?;
634    while let Some(row) = file_rows.next().map_err(SyncError::Db)? {
635        let indexed_path: String = row.get(0).map_err(SyncError::Db)?;
636
637        // If the indexed file belongs to an unreadable directory, preserve it
638        let in_unreadable_prefix = unreadable_prefixes.iter().any(|prefix| {
639            indexed_path == *prefix || indexed_path.starts_with(&format!("{prefix}/"))
640        });
641        if in_unreadable_prefix {
642            continue;
643        }
644
645        let mut seen_rows = exists_seen_stmt
646            .query([&indexed_path])
647            .map_err(SyncError::Db)?;
648        if seen_rows.next().map_err(SyncError::Db)?.is_none() {
649            report.deleted.push(indexed_path);
650        }
651    }
652
653    drop(file_rows);
654    drop(files_stmt);
655    drop(check_file_stmt);
656    drop(exists_seen_stmt);
657    drop(insert_seen_stmt);
658    drop(temp_conn);
659
660    let total_changes = report.added.len() + report.modified.len() + report.deleted.len();
661    if total_changes > 0 {
662        info!(
663            "Cold start reconciliation detected {} changes (+{}, ~{}, -{})",
664            total_changes,
665            report.added.len(),
666            report.modified.len(),
667            report.deleted.len()
668        );
669
670        if total_changes > 50 {
671            // Trigger bulk scan if large changes
672            scan_workspace(workspace, db_path, false)?;
673        } else {
674            // Incremental single-file updates
675            for added in &report.added {
676                if let Err(e) = update_file(workspace, db_path, added) {
677                    warn!("Failed to index added file '{}': {e}", added);
678                }
679            }
680            for modified in &report.modified {
681                if let Err(e) = update_file(workspace, db_path, modified) {
682                    warn!("Failed to index modified file '{}': {e}", modified);
683                }
684            }
685            for deleted in &report.deleted {
686                if let Err(e) = delete_file(workspace, db_path, deleted) {
687                    warn!("Failed to remove deleted file '{}': {e}", deleted);
688                }
689            }
690        }
691    }
692
693    Ok(report)
694}
695
696#[cfg(test)]
697mod tests {
698    #[test]
699    fn pinned_version_matches_the_pins_file() {
700        let pins = include_str!("../../../scripts/julie-pins.json");
701        assert!(pins.contains(&format!("\"version\": \"{}\"", super::PINNED_JULIE_VERSION)));
702    }
703
704    use super::*;
705
706    #[test]
707    fn test_find_julie_extract_binary() {
708        let path = find_julie_extract_binary()
709            .expect("julie-extract binary must be present for tests (see scripts/julie-pins.json)");
710        assert!(path.exists(), "Discovered path must exist: {:?}", path);
711    }
712
713    #[test]
714    fn ensure_index_dir_writes_self_ignoring_gitignore() {
715        let temp = crate::safe_tempdir();
716        let db_path = temp.path().join(".code-kb").join("artifact.db");
717        ensure_index_dir(&db_path).unwrap();
718        let gitignore = db_path.parent().unwrap().join(".gitignore");
719        assert_eq!(std::fs::read_to_string(&gitignore).unwrap(), "*\n");
720        std::fs::write(&gitignore, "custom\n").unwrap();
721        ensure_index_dir(&db_path).unwrap();
722        assert_eq!(std::fs::read_to_string(&gitignore).unwrap(), "custom\n");
723    }
724
725    #[test]
726    fn ensure_index_dir_leaves_non_code_kb_directories_alone() {
727        let temp = crate::safe_tempdir();
728        let db_path = temp.path().join("test.db");
729        ensure_index_dir(&db_path).unwrap();
730        assert!(!temp.path().join(".gitignore").exists());
731    }
732
733    #[test]
734    fn test_reconcile_offline_edits_drive_case_mismatch() {
735        let temp = crate::safe_tempdir();
736        let db_path = temp.path().join("test.db");
737        let conn = rusqlite::Connection::open(&db_path).unwrap();
738        conn.execute_batch(
739            "CREATE TABLE files (
740                file_id TEXT PRIMARY KEY,
741                path TEXT NOT NULL,
742                language TEXT,
743                content_hash TEXT,
744                content_bytes INTEGER,
745                line_count INTEGER,
746                indexed_at TEXT
747            );
748            CREATE TABLE symbols (
749                symbol_id TEXT PRIMARY KEY,
750                file_id TEXT,
751                path TEXT NOT NULL
752            );",
753        )
754        .unwrap();
755
756        // Create a real file on disk
757        let src_dir = temp.path().join("src");
758        std::fs::create_dir_all(&src_dir).unwrap();
759        let file_path = src_dir.join("main.rs");
760        let content = "fn main() {}\n";
761        std::fs::write(&file_path, content).unwrap();
762
763        let hash = sha2::Sha256::digest(content.as_bytes());
764        let hash_hex = hex::encode(hash);
765
766        conn.execute(
767            "INSERT INTO files VALUES ('f1', 'src/main.rs', 'rust', ?1, ?2, 1, '2026-09-14T00:00:00Z')",
768            rusqlite::params![hash_hex, content.len() as i64],
769        )
770        .unwrap();
771
772        #[allow(unused_mut)]
773        let mut ws = Workspace::new(temp.path().to_path_buf());
774        #[cfg(windows)]
775        {
776            let root_str = ws.canonical_root.to_string_lossy().to_string();
777            if let Some(first_char) = root_str.chars().next() {
778                let flipped = if first_char.is_ascii_uppercase() {
779                    first_char.to_ascii_lowercase()
780                } else {
781                    first_char.to_ascii_uppercase()
782                };
783                let altered_root = format!("{}{}", flipped, &root_str[1..]);
784                ws.canonical_root = PathBuf::from(altered_root);
785            }
786        }
787
788        let report = reconcile_offline_edits(&ws, &db_path, &conn).unwrap();
789        assert!(
790            report.deleted.is_empty(),
791            "Files should not be marked deleted due to drive casing difference: {:?}",
792            report.deleted
793        );
794    }
795}