1use rusqlite::Connection;
2use sha2::Digest;
3use std::path::{Path, PathBuf};
4use std::process::Command;
5use thiserror::Error;
6use tracing::{error, 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 #[error("extractor did not index the requested file: {0}")]
28 TargetNotIndexed(String),
29}
30
31pub const PINNED_JULIE_VERSION: &str = "3.7.2";
32
33pub const EXTRACTION_LEVEL: &str = "facts";
36
37static CACHED_JULIE_BIN: std::sync::OnceLock<Option<(PathBuf, String)>> =
38 std::sync::OnceLock::new();
39static HEADER_SCAN_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
40
41pub fn find_julie_extract_binary() -> Option<PathBuf> {
46 installed_extractor().map(|(bin, _)| bin)
47}
48
49pub fn installed_extractor_version() -> String {
51 installed_extractor()
52 .map(|(_, version)| version)
53 .unwrap_or_else(|| PINNED_JULIE_VERSION.to_string())
54}
55
56fn installed_extractor() -> Option<(PathBuf, String)> {
57 CACHED_JULIE_BIN
58 .get_or_init(|| {
59 let candidates: Vec<(PathBuf, String)> = julie_extract_candidates()
60 .into_iter()
61 .filter_map(|bin| extractor_version(&bin).map(|version| (bin, version)))
62 .collect();
63 let pinned = candidates
64 .iter()
65 .find(|(_, version)| version == PINNED_JULIE_VERSION)
66 .cloned();
67 if pinned.is_some() {
68 return pinned;
69 }
70 let first = candidates.into_iter().next()?;
71 tracing::warn!(
72 found = %first.1,
73 pinned = %PINNED_JULIE_VERSION,
74 binary = %first.0.display(),
75 "julie-extract version differs from pinned version; AST facts may drift"
76 );
77 Some(first)
78 })
79 .clone()
80}
81
82fn extractor_version(bin: &Path) -> Option<String> {
83 let output = Command::new(bin).arg("--version").output().ok()?;
84 let text = String::from_utf8_lossy(&output.stdout);
85 text.split_whitespace().last().map(str::to_string)
86}
87
88fn julie_extract_candidates() -> Vec<PathBuf> {
89 let exe_name = if cfg!(windows) {
90 "julie-extract.exe"
91 } else {
92 "julie-extract"
93 };
94 let mut candidates = Vec::new();
95
96 if let Ok(path_str) = std::env::var("JULIE_EXTRACT_BIN") {
97 candidates.push(PathBuf::from(path_str));
98 }
99
100 if let Some(exe_dir) = std::env::current_exe()
103 .ok()
104 .and_then(|p| p.parent().map(|d| d.to_path_buf()))
105 {
106 candidates.push(exe_dir.join(exe_name));
107 candidates.extend(
108 exe_dir
109 .ancestors()
110 .map(|dir| dir.join(".tools").join(exe_name)),
111 );
112 }
113
114 if let Ok(p) = which::which("julie-extract") {
115 candidates.push(p);
116 }
117
118 candidates
119 .into_iter()
120 .filter(|p| p.is_file())
121 .map(|p| crate::workspace::normalize_path(&p))
122 .collect()
123}
124
125pub fn execute_julie_extract(args: &[&str]) -> Result<String, SyncError> {
127 let bin = find_julie_extract_binary().ok_or(SyncError::BinaryNotFound)?;
128
129 let mut attempts = 0;
130 loop {
131 let output = Command::new(&bin)
132 .args(args)
133 .output()
134 .map_err(SyncError::Io)?;
135
136 if output.status.success() {
137 return Ok(String::from_utf8_lossy(&output.stdout).to_string());
138 }
139
140 let stderr = String::from_utf8_lossy(&output.stderr).to_string();
141 if (stderr.contains("database is locked")
143 || stderr.contains("busy")
144 || stderr.contains("SQLITE_BUSY"))
145 && attempts < 5
146 {
147 attempts += 1;
148 std::thread::sleep(std::time::Duration::from_millis(50 * (1 << attempts)));
149 continue;
150 }
151
152 let code = output.status.code().unwrap_or(-1);
153 return Err(SyncError::ExtractionFailed(code, stderr));
154 }
155}
156
157fn is_header_path(rel_path: &str) -> bool {
158 Path::new(rel_path)
159 .extension()
160 .is_some_and(|extension| extension.eq_ignore_ascii_case("h"))
161}
162
163pub fn update_file(workspace: &Workspace, db_path: &Path, rel_path: &str) -> Result<(), SyncError> {
165 if db_path.is_file() && is_header_path(rel_path) {
166 return scan_header_file(workspace, db_path, rel_path);
167 }
168
169 let root_str = workspace.canonical_root.to_string_lossy();
170 let db_str = db_path.to_string_lossy();
171
172 write_incrementally(
173 workspace,
174 db_path,
175 &[
176 "update", "--root", &root_str, "--db", &db_str, "--file", rel_path,
177 ],
178 )
179}
180
181fn write_incrementally(
185 workspace: &Workspace,
186 db_path: &Path,
187 args: &[&str],
188) -> Result<(), SyncError> {
189 match execute_julie_extract(args) {
190 Err(SyncError::ExtractionFailed(_, stderr)) if is_fingerprint_mismatch(&stderr) => {
191 warn!("Index was written by another julie-extract build; rescanning it");
192 scan_workspace(workspace, db_path, true)
193 }
194 result => result.map(drop),
195 }
196}
197
198fn is_fingerprint_mismatch(stderr: &str) -> bool {
199 stderr.contains("fingerprint_mismatch")
200}
201
202fn scan_header_file(
203 workspace: &Workspace,
204 db_path: &Path,
205 rel_path: &str,
206) -> Result<(), SyncError> {
207 let _scan_lock = HEADER_SCAN_LOCK
209 .lock()
210 .unwrap_or_else(|poisoned| poisoned.into_inner());
211 if header_hash_matches_disk(workspace, db_path, rel_path)? {
212 return Ok(());
213 }
214 scan_workspace(workspace, db_path, false)?;
216
217 if !header_hash_matches_disk(workspace, db_path, rel_path)? {
218 return Err(SyncError::TargetNotIndexed(rel_path.to_string()));
219 }
220
221 Ok(())
222}
223
224fn header_hash_matches_disk(
225 workspace: &Workspace,
226 db_path: &Path,
227 rel_path: &str,
228) -> Result<bool, SyncError> {
229 let stored_hash = {
230 let conn = crate::db::open_read_only(db_path)?;
231 queries::get_file(&conn, rel_path)
232 .map_err(|error| match error {
233 queries::QueryError::Sqlite(error) => SyncError::Db(error),
234 _ => SyncError::TargetNotIndexed(rel_path.to_string()),
235 })?
236 .map(|file| file.content_hash)
237 };
238 let Some(stored_hash) = stored_hash else {
239 return Ok(false);
240 };
241 let disk_bytes = match std::fs::read(workspace.canonical_root.join(rel_path)) {
242 Ok(bytes) => bytes,
243 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
244 Err(error) => return Err(error.into()),
245 };
246
247 Ok(compute_content_hash_matches(&disk_bytes, &stored_hash))
248}
249
250pub fn delete_file(workspace: &Workspace, db_path: &Path, rel_path: &str) -> Result<(), SyncError> {
252 let root_str = workspace.canonical_root.to_string_lossy();
253 let db_str = db_path.to_string_lossy();
254
255 write_incrementally(
256 workspace,
257 db_path,
258 &[
259 "delete", "--root", &root_str, "--db", &db_str, "--file", rel_path,
260 ],
261 )
262}
263
264pub fn scan_workspace(workspace: &Workspace, db_path: &Path, force: bool) -> Result<(), SyncError> {
269 let root_str = workspace.canonical_root.to_string_lossy();
270 let db_str = db_path.to_string_lossy();
271 let own_pid = std::process::id().to_string();
272
273 ensure_index_dir(db_path)?;
274
275 let scan_args = |new_artifact: bool| {
276 let mut args = vec!["scan", "--root", &*root_str, "--db", &*db_str];
277 if new_artifact {
278 args.extend(["--level", EXTRACTION_LEVEL]);
279 }
280 if cfg!(unix) {
281 args.extend(["--parent-pid", &*own_pid]);
282 }
283 if force {
284 args.push("--force");
285 }
286 args
287 };
288
289 match execute_julie_extract(&scan_args(!db_path.exists())) {
290 Ok(_) => {}
291 Err(SyncError::ExtractionFailed(_, stderr))
292 if stderr.contains("schema_incompatible") && db_path.exists() =>
293 {
294 warn!("Extractor cannot read the existing artifact; rebuilding from scratch");
295 remove_artifact_files(db_path)?;
296 execute_julie_extract(&scan_args(true))?;
297 }
298 Err(SyncError::ExtractionFailed(_, stderr))
299 if is_fingerprint_mismatch(&stderr) && !force && db_path.exists() =>
300 {
301 warn!("Index was written by another julie-extract build; rescanning it");
302 return scan_workspace(workspace, db_path, true);
303 }
304 Err(SyncError::ExtractionFailed(1, stderr))
305 if stderr.starts_with("partial") && db_path.exists() =>
306 {
307 warn!(
308 "Extractor skipped files it could not read; the next reconcile retries them:\n{stderr}"
309 );
310 }
311 Err(e) => return Err(e),
312 }
313
314 crate::db::ensure_fts_index_path(db_path).map_err(|e| {
315 error!(db = %db_path.display(), "FTS index preparation failed: {e}");
316 e
317 })?;
318
319 Ok(())
320}
321
322pub fn ensure_index_matches_extractor(
327 workspace: &Workspace,
328 db_path: &Path,
329 extractor_version: &str,
330) -> Result<bool, SyncError> {
331 if !db_path.exists() {
332 return Ok(false);
333 }
334 let metadata = |key: &str| -> Option<String> {
335 let conn = crate::db::open_read_only(db_path).ok()?;
336 conn.query_row(
337 "SELECT value FROM artifact_metadata WHERE key = ?1",
338 [key],
339 |r| r.get(0),
340 )
341 .ok()
342 };
343 let Some(recorded) = metadata("binary_version") else {
344 return Ok(false);
345 };
346 let level = metadata("index_level").unwrap_or_else(|| "full".to_string());
347 if recorded == extractor_version
348 && level == EXTRACTION_LEVEL
349 && !has_file_written_by_another_extractor(db_path, extractor_version)
350 {
351 return Ok(false);
352 }
353 if let Some(newer) = newest_writer_version(db_path, &recorded)
354 .filter(|newest| version_is_older(extractor_version, newest))
355 {
356 warn!(
357 written_by = %newer,
358 installed = %extractor_version,
359 "Index was written by a newer julie-extract than the one in use; keeping it"
360 );
361 return Ok(false);
362 }
363 info!(
364 recorded = %recorded,
365 installed = %extractor_version,
366 level = %level,
367 wanted_level = %EXTRACTION_LEVEL,
368 "Index holds rows from a different julie-extract version or level; rebuilding"
369 );
370 rebuild_index(workspace, db_path)?;
371 Ok(true)
372}
373
374fn rebuild_index(workspace: &Workspace, db_path: &Path) -> Result<(), SyncError> {
377 let rebuilt = PathBuf::from(format!("{}.rebuild", db_path.display()));
378 remove_artifact_files(&rebuilt)?;
379 let scanned = scan_workspace(workspace, &rebuilt, true).and_then(|()| {
380 let conn = crate::db::open_read_write(&rebuilt)?;
381 crate::db::checkpoint_truncate(&conn)?;
382 Ok(())
383 });
384 if let Err(e) = scanned {
385 let _ = remove_artifact_files(&rebuilt);
386 return Err(e);
387 }
388 remove_artifact_files(db_path)?;
389 for suffix in ["-wal", "-shm"] {
390 let _ = std::fs::remove_file(format!("{}{suffix}", rebuilt.display()));
391 }
392 std::fs::rename(&rebuilt, db_path)?;
393 Ok(())
394}
395
396fn newest_writer_version(db_path: &Path, recorded: &str) -> Option<String> {
398 let revisions: Vec<String> = crate::db::open_read_only(db_path)
399 .ok()
400 .and_then(|conn| {
401 let mut stmt = conn
402 .prepare("SELECT DISTINCT binary_version FROM extraction_revisions")
403 .ok()?;
404 let versions = stmt
405 .query_map([], |r| r.get(0))
406 .ok()?
407 .filter_map(Result::ok)
408 .collect();
409 Some(versions)
410 })
411 .unwrap_or_default();
412 std::iter::once(recorded.to_string())
413 .chain(revisions)
414 .filter(|version| parse_version(version).is_some())
415 .max_by_key(|version| parse_version(version))
416}
417
418fn parse_version(version: &str) -> Option<Vec<u64>> {
419 version.split('.').map(|part| part.parse().ok()).collect()
420}
421
422fn version_is_older(candidate: &str, than: &str) -> bool {
424 matches!((parse_version(candidate), parse_version(than)), (Some(a), Some(b)) if a < b)
425}
426
427fn has_file_written_by_another_extractor(db_path: &Path, extractor_version: &str) -> bool {
431 let Ok(conn) = crate::db::open_read_only(db_path) else {
432 return false;
433 };
434 conn.query_row(
435 "SELECT 1 FROM files f
436 JOIN extraction_revisions r ON r.revision_id = f.last_revision_id
437 WHERE r.binary_version != ?1
438 LIMIT 1",
439 [extractor_version],
440 |_| Ok(true),
441 )
442 .unwrap_or(false)
443}
444
445fn remove_artifact_files(db_path: &Path) -> Result<(), SyncError> {
446 for suffix in ["", "-wal", "-shm"] {
447 let sidecar = PathBuf::from(format!("{}{suffix}", db_path.display()));
448 match std::fs::remove_file(&sidecar) {
449 Ok(()) => {}
450 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
451 Err(e) => return Err(e.into()),
452 }
453 }
454 Ok(())
455}
456
457pub fn compute_content_hash_matches(disk_bytes: &[u8], stored_hash: &str) -> bool {
459 if stored_hash.starts_with("blake3:") {
460 let b3 = format!("blake3:{}", blake3::hash(disk_bytes).to_hex());
461 b3 == stored_hash
462 } else {
463 let b3 = blake3::hash(disk_bytes).to_hex().to_string();
464 if b3 == stored_hash {
465 return true;
466 }
467 let mut hasher = sha2::Sha256::new();
468 sha2::Digest::update(&mut hasher, disk_bytes);
469 let sha = hex::encode(sha2::Digest::finalize(hasher));
470 sha == stored_hash || format!("sha256:{sha}") == stored_hash
471 }
472}
473
474pub fn ensure_fresh_file(
478 workspace: &Workspace,
479 db_path: &Path,
480 conn: &Connection,
481 rel_path: &str,
482) -> Result<bool, SyncError> {
483 let abs_path = workspace.canonical_root.join(rel_path);
484 let meta = match std::fs::metadata(&abs_path) {
485 Ok(meta) => meta,
486 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
487 let existing_file = queries::get_file(conn, rel_path).map_err(|e| match e {
488 queries::QueryError::Sqlite(err) => SyncError::Db(err),
489 _ => SyncError::Db(rusqlite::Error::QueryReturnedNoRows),
490 })?;
491 if existing_file.is_some() {
492 delete_file(workspace, db_path, rel_path)?;
493 return Ok(true);
494 }
495 return Ok(false);
496 }
497 Err(error) => return Err(SyncError::Io(error)),
498 };
499
500 if meta.is_dir() {
501 return Ok(false);
502 }
503
504 let disk_bytes = meta.len() as i64;
505
506 let existing_file = queries::get_file(conn, rel_path).map_err(|e| match e {
508 queries::QueryError::Sqlite(err) => SyncError::Db(err),
509 _ => SyncError::Db(rusqlite::Error::QueryReturnedNoRows),
510 })?;
511
512 let is_dirty = match existing_file {
513 None => true, Some(f) => {
515 if f.content_bytes != disk_bytes {
517 true
518 } else {
519 let disk_content = std::fs::read(&abs_path)?;
520 !compute_content_hash_matches(&disk_content, &f.content_hash)
521 }
522 }
523 };
524
525 if is_dirty {
526 let stored_root: Option<String> = conn
527 .query_row(
528 "SELECT value FROM artifact_metadata WHERE key = 'root_path'",
529 [],
530 |r| r.get(0),
531 )
532 .ok();
533 if let Some(r) = stored_root
534 && !crate::workspace::paths_equal(Path::new(&r), &workspace.canonical_root)
535 {
536 crate::db::retarget_artifact_root(db_path, &workspace.canonical_root)?;
537 }
538
539 update_file(workspace, db_path, rel_path)?;
540 return Ok(true);
541 }
542
543 Ok(false)
544}
545
546#[derive(Debug, Default)]
548pub struct ReconcileReport {
549 pub added: Vec<String>,
550 pub modified: Vec<String>,
551 pub deleted: Vec<String>,
552}
553
554fn extract_error_path(err: &ignore::Error) -> Option<&Path> {
555 match err {
556 ignore::Error::WithPath { path, .. } => Some(path.as_path()),
557 ignore::Error::WithDepth { err, .. } => extract_error_path(err),
558 ignore::Error::WithLineNumber { err, .. } => extract_error_path(err),
559 ignore::Error::Loop { ancestor, .. } => Some(ancestor.as_path()),
560 _ => None,
561 }
562}
563
564pub fn create_index(workspace: &Workspace, db_path: &Path) -> Result<(), SyncError> {
570 if let Some(parent_db) = parent_repository_db(&workspace.canonical_root)
571 && copy_parent_index(workspace, db_path, &parent_db)
572 {
573 ensure_index_matches_extractor(workspace, db_path, &installed_extractor_version())?;
574 return Ok(());
575 }
576 scan_workspace(workspace, db_path, false)
577}
578
579fn ensure_index_dir(db_path: &Path) -> std::io::Result<()> {
584 let Some(dir) = db_path.parent() else {
585 return Ok(());
586 };
587 std::fs::create_dir_all(dir)?;
588 if dir.file_name().is_none_or(|name| name != ".code-kb") {
589 return Ok(());
590 }
591 let gitignore = dir.join(".gitignore");
592 if !gitignore.exists() {
593 std::fs::write(gitignore, "*\n")?;
594 }
595 Ok(())
596}
597
598fn parent_repository_db(root: &Path) -> Option<PathBuf> {
599 let git_marker = root.join(".git");
600 if !git_marker.is_file() {
601 return None;
602 }
603 let git_content = std::fs::read_to_string(&git_marker).ok()?;
604 let gitdir = git_content
605 .lines()
606 .find_map(|l| l.strip_prefix("gitdir:"))?
607 .trim();
608 let gitdir = Path::new(gitdir);
609 let mut probe = if gitdir.is_absolute() {
610 gitdir.to_path_buf()
611 } else {
612 root.join(gitdir)
613 };
614 while let Some(parent) = probe.parent() {
615 if parent == probe {
616 break;
617 }
618 if parent.join(".git").exists() {
619 let db = parent.join(".code-kb").join("artifact.db");
620 return db.exists().then_some(db);
621 }
622 probe = parent.to_path_buf();
623 }
624 None
625}
626
627fn copy_parent_index(workspace: &Workspace, db_path: &Path, parent_db: &Path) -> bool {
628 let flushed = crate::db::open_read_write(parent_db)
629 .map(|conn| crate::db::checkpoint_truncate(&conn).is_ok())
630 .unwrap_or(false);
631 if !flushed {
632 return false;
633 }
634 if ensure_index_dir(db_path).is_err() || std::fs::copy(parent_db, db_path).is_err() {
635 return false;
636 }
637 info!(from = %parent_db.display(), to = %db_path.display(), "Worktree fast-path: copied parent database, reconciling");
638 let reconciled = crate::db::retarget_artifact_root(db_path, &workspace.canonical_root)
639 .and_then(|_| crate::db::ensure_fts_index_path(db_path))
640 .is_ok()
641 && crate::db::open_read_only(db_path)
642 .ok()
643 .and_then(|conn| reconcile_offline_edits(workspace, db_path, &conn).ok())
644 .is_some();
645 if !reconciled {
646 warn!(
647 "Failed to retarget worktree database root; removing copied db and falling back to full scan"
648 );
649 let _ = std::fs::remove_file(db_path);
650 }
651 reconciled
652}
653
654pub fn reconcile_offline_edits(
655 workspace: &Workspace,
656 db_path: &Path,
657 conn: &Connection,
658) -> Result<ReconcileReport, SyncError> {
659 let stored_root: Option<String> = conn
662 .query_row(
663 "SELECT value FROM artifact_metadata WHERE key = 'root_path'",
664 [],
665 |r| r.get(0),
666 )
667 .ok();
668 if let Some(r) = stored_root
669 && !crate::workspace::paths_equal(Path::new(&r), &workspace.canonical_root)
670 {
671 crate::db::retarget_artifact_root(db_path, &workspace.canonical_root)?;
672 }
673
674 let mut report = ReconcileReport::default();
675
676 let temp_conn = Connection::open_in_memory().map_err(SyncError::Db)?;
678 temp_conn
679 .execute(
680 "CREATE TABLE _seen (path TEXT COLLATE NOCASE PRIMARY KEY)",
681 [],
682 )
683 .map_err(SyncError::Db)?;
684
685 let mut insert_seen_stmt = temp_conn
686 .prepare("INSERT OR IGNORE INTO _seen (path) VALUES (?1)")
687 .map_err(SyncError::Db)?;
688
689 let mut check_file_stmt = conn
690 .prepare("SELECT content_bytes, content_hash FROM files WHERE path = ?1")
691 .map_err(SyncError::Db)?;
692 let mut skipped_stmt = if crate::queries::has_table(conn, "skipped_files") {
693 Some(
694 conn.prepare(
695 "SELECT 1 FROM skipped_files WHERE path = ?1 AND content_bytes = ?2 AND mtime_ns = ?3",
696 )
697 .map_err(SyncError::Db)?,
698 )
699 } else {
700 None
701 };
702
703 let mut walker = ignore::WalkBuilder::new(&workspace.canonical_root);
704 walker
705 .standard_filters(true)
706 .hidden(false)
707 .add_custom_ignore_filename(".julieignore")
708 .add_custom_ignore_filename(".code-kb-ignore")
709 .add_custom_ignore_filename(".codekbignore")
710 .filter_entry(|entry| {
711 let name = entry.file_name().to_string_lossy();
712 !crate::workspace::is_hard_excluded(&name)
713 });
714 let walker = walker.build();
715
716 temp_conn
717 .execute("BEGIN TRANSACTION", [])
718 .map_err(SyncError::Db)?;
719
720 let mut unreadable_prefixes: Vec<String> = Vec::new();
721
722 for result in walker {
723 let entry = match result {
724 Ok(e) => e,
725 Err(e) => {
726 warn!("Reconciliation walker encountered error: {e}");
727 if let Some(path) = extract_error_path(&e) {
728 let norm_path = dunce::simplified(path);
729 if let Some(rel) =
730 crate::workspace::strip_prefix_lossy(norm_path, &workspace.canonical_root)
731 {
732 unreadable_prefixes.push(crate::workspace::to_forward_slash(rel));
733 }
734 }
735 continue;
736 }
737 };
738
739 if entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
740 let path = entry.path();
741 let norm_path = dunce::simplified(path);
742 if let Some(rel) =
743 crate::workspace::strip_prefix_lossy(norm_path, &workspace.canonical_root)
744 {
745 let rel_str = crate::workspace::to_forward_slash(rel);
746 if crate::workspace::is_hard_excluded(&rel_str) {
747 continue;
748 }
749 let meta = match entry.metadata() {
750 Ok(m) => m,
751 Err(e) => {
752 warn!("Failed to read metadata for '{}': {e}", path.display());
753 let _ = insert_seen_stmt.execute([&rel_str]);
754 continue;
755 }
756 };
757 let bytes = meta.len() as i64;
758
759 insert_seen_stmt
760 .execute([&rel_str])
761 .map_err(SyncError::Db)?;
762
763 let mut rows = check_file_stmt.query([&rel_str]).map_err(SyncError::Db)?;
764
765 if let Some(row) = rows.next().map_err(SyncError::Db)? {
766 let indexed_bytes: i64 = row.get(0).map_err(SyncError::Db)?;
767 let stored_hash: String = row.get(1).map_err(SyncError::Db)?;
768
769 let is_modified = if indexed_bytes != bytes {
770 true
771 } else {
772 match std::fs::read(path) {
773 Ok(content) => !compute_content_hash_matches(&content, &stored_hash),
774 Err(e) => {
775 warn!(
776 "Failed to read '{}' for hash verification: {e}",
777 path.display()
778 );
779 false
780 }
781 }
782 };
783
784 if is_modified {
785 report.modified.push(rel_str);
786 }
787 } else if !skipped_before(skipped_stmt.as_mut(), &rel_str, bytes, mtime_ns(&meta))?
788 {
789 report.added.push(rel_str);
790 }
791 }
792 }
793 }
794
795 temp_conn.execute("COMMIT", []).map_err(SyncError::Db)?;
796
797 let mut files_stmt = conn
798 .prepare("SELECT path FROM files")
799 .map_err(SyncError::Db)?;
800
801 let mut exists_seen_stmt = temp_conn
802 .prepare("SELECT 1 FROM _seen WHERE path = ?1")
803 .map_err(SyncError::Db)?;
804
805 let mut file_rows = files_stmt.query([]).map_err(SyncError::Db)?;
806 while let Some(row) = file_rows.next().map_err(SyncError::Db)? {
807 let indexed_path: String = row.get(0).map_err(SyncError::Db)?;
808
809 let in_unreadable_prefix = unreadable_prefixes.iter().any(|prefix| {
811 indexed_path == *prefix || indexed_path.starts_with(&format!("{prefix}/"))
812 });
813 if in_unreadable_prefix {
814 continue;
815 }
816
817 let mut seen_rows = exists_seen_stmt
818 .query([&indexed_path])
819 .map_err(SyncError::Db)?;
820 if seen_rows.next().map_err(SyncError::Db)?.is_none() {
821 report.deleted.push(indexed_path);
822 }
823 }
824
825 drop(file_rows);
826 drop(files_stmt);
827 drop(check_file_stmt);
828 drop(skipped_stmt);
829 drop(exists_seen_stmt);
830 drop(insert_seen_stmt);
831 drop(temp_conn);
832
833 let total_changes = report.added.len() + report.modified.len() + report.deleted.len();
834 if total_changes > 0 {
835 info!(
836 "Cold start reconciliation detected {} changes (+{}, ~{}, -{})",
837 total_changes,
838 report.added.len(),
839 report.modified.len(),
840 report.deleted.len()
841 );
842
843 let changed_paths = report.added.iter().chain(&report.modified);
844 let changed_headers = changed_paths.clone().any(|path| is_header_path(path));
845 if total_changes > 50 || changed_headers {
846 scan_workspace(workspace, db_path, false)?;
847 remember_skipped_files(workspace, db_path, conn, changed_paths)?;
848 } else {
849 let mut updated: Vec<&String> = Vec::new();
850 for added in &report.added {
851 match update_file(workspace, db_path, added) {
852 Ok(()) => updated.push(added),
853 Err(e) => warn!("Failed to index added file '{}': {e}", added),
854 }
855 }
856 for modified in &report.modified {
857 match update_file(workspace, db_path, modified) {
858 Ok(()) => updated.push(modified),
859 Err(e) => warn!("Failed to index modified file '{}': {e}", modified),
860 }
861 }
862 for deleted in &report.deleted {
863 if let Err(e) = delete_file(workspace, db_path, deleted) {
864 warn!("Failed to remove deleted file '{}': {e}", deleted);
865 }
866 }
867 remember_skipped_files(workspace, db_path, conn, updated.into_iter())?;
868 }
869 }
870
871 Ok(report)
872}
873
874const SKIPPED_FILES_DDL: &str = "CREATE TABLE IF NOT EXISTS skipped_files (
878 path TEXT PRIMARY KEY, content_bytes INTEGER NOT NULL, mtime_ns INTEGER NOT NULL)";
879
880fn mtime_ns(meta: &std::fs::Metadata) -> i64 {
881 meta.modified()
882 .ok()
883 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
884 .map_or(0, |d| d.as_nanos() as i64)
885}
886
887fn skipped_before(
888 stmt: Option<&mut rusqlite::Statement<'_>>,
889 path: &str,
890 bytes: i64,
891 mtime: i64,
892) -> Result<bool, SyncError> {
893 let Some(stmt) = stmt else {
894 return Ok(false);
895 };
896 stmt.exists(rusqlite::params![path, bytes, mtime])
897 .map_err(SyncError::Db)
898}
899
900fn remember_skipped_files<'a>(
901 workspace: &Workspace,
902 db_path: &Path,
903 conn: &Connection,
904 paths: impl Iterator<Item = &'a String>,
905) -> Result<(), SyncError> {
906 let mut indexed = conn
907 .prepare("SELECT 1 FROM files WHERE path = ?1")
908 .map_err(SyncError::Db)?;
909 let mut writer: Option<Connection> = None;
910 for path in paths {
911 if indexed.exists([path]).map_err(SyncError::Db)? {
912 continue;
913 }
914 let Ok(meta) = std::fs::metadata(workspace.canonical_root.join(path)) else {
915 continue;
916 };
917 if writer.is_none() {
918 let conn = crate::db::open_read_write(db_path)?;
919 conn.execute_batch(SKIPPED_FILES_DDL)
920 .map_err(SyncError::Db)?;
921 writer = Some(conn);
922 }
923 writer
924 .as_ref()
925 .expect("opened above")
926 .execute(
927 "INSERT OR REPLACE INTO skipped_files (path, content_bytes, mtime_ns) VALUES (?1, ?2, ?3)",
928 rusqlite::params![path, meta.len() as i64, mtime_ns(&meta)],
929 )
930 .map_err(SyncError::Db)?;
931 }
932 Ok(())
933}
934
935#[cfg(test)]
936mod tests {
937 #[test]
938 fn pinned_version_matches_the_pins_file() {
939 let pins = include_str!("../../../scripts/julie-pins.json");
940 assert!(pins.contains(&format!("\"version\": \"{}\"", super::PINNED_JULIE_VERSION)));
941 }
942
943 use super::*;
944
945 #[test]
946 fn test_find_julie_extract_binary() {
947 let path = find_julie_extract_binary()
948 .expect("julie-extract binary must be present for tests (see scripts/julie-pins.json)");
949 assert!(path.exists(), "Discovered path must exist: {:?}", path);
950 }
951
952 #[test]
953 fn ensure_index_dir_writes_self_ignoring_gitignore() {
954 let temp = crate::safe_tempdir();
955 let db_path = temp.path().join(".code-kb").join("artifact.db");
956 ensure_index_dir(&db_path).unwrap();
957 let gitignore = db_path.parent().unwrap().join(".gitignore");
958 assert_eq!(std::fs::read_to_string(&gitignore).unwrap(), "*\n");
959 std::fs::write(&gitignore, "custom\n").unwrap();
960 ensure_index_dir(&db_path).unwrap();
961 assert_eq!(std::fs::read_to_string(&gitignore).unwrap(), "custom\n");
962 }
963
964 #[test]
965 fn ensure_index_dir_leaves_non_code_kb_directories_alone() {
966 let temp = crate::safe_tempdir();
967 let db_path = temp.path().join("test.db");
968 ensure_index_dir(&db_path).unwrap();
969 assert!(!temp.path().join(".gitignore").exists());
970 }
971
972 #[test]
973 fn test_reconcile_offline_edits_drive_case_mismatch() {
974 let temp = crate::safe_tempdir();
975 let db_path = temp.path().join("test.db");
976 let conn = rusqlite::Connection::open(&db_path).unwrap();
977 conn.execute_batch(
978 "CREATE TABLE files (
979 file_id TEXT PRIMARY KEY,
980 path TEXT NOT NULL,
981 language TEXT,
982 content_hash TEXT,
983 content_bytes INTEGER,
984 line_count INTEGER,
985 indexed_at TEXT
986 );
987 CREATE TABLE symbols (
988 symbol_id TEXT PRIMARY KEY,
989 file_id TEXT,
990 path TEXT NOT NULL
991 );",
992 )
993 .unwrap();
994
995 let src_dir = temp.path().join("src");
997 std::fs::create_dir_all(&src_dir).unwrap();
998 let file_path = src_dir.join("main.rs");
999 let content = "fn main() {}\n";
1000 std::fs::write(&file_path, content).unwrap();
1001
1002 let hash = sha2::Sha256::digest(content.as_bytes());
1003 let hash_hex = hex::encode(hash);
1004
1005 conn.execute(
1006 "INSERT INTO files VALUES ('f1', 'src/main.rs', 'rust', ?1, ?2, 1, '2026-09-14T00:00:00Z')",
1007 rusqlite::params![hash_hex, content.len() as i64],
1008 )
1009 .unwrap();
1010
1011 #[allow(unused_mut)]
1012 let mut ws = Workspace::new(temp.path().to_path_buf());
1013 #[cfg(windows)]
1014 {
1015 let root_str = ws.canonical_root.to_string_lossy().to_string();
1016 if let Some(first_char) = root_str.chars().next() {
1017 let flipped = if first_char.is_ascii_uppercase() {
1018 first_char.to_ascii_lowercase()
1019 } else {
1020 first_char.to_ascii_uppercase()
1021 };
1022 let altered_root = format!("{}{}", flipped, &root_str[1..]);
1023 ws.canonical_root = PathBuf::from(altered_root);
1024 }
1025 }
1026
1027 let report = reconcile_offline_edits(&ws, &db_path, &conn).unwrap();
1028 assert!(
1029 report.deleted.is_empty(),
1030 "Files should not be marked deleted due to drive casing difference: {:?}",
1031 report.deleted
1032 );
1033 }
1034}