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