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