use orbok_cache::CacheService;
use orbok_core::{
CleanupAction, CleanupPlan, FileStatus, HiddenFilePolicy, IndexMode,
JobStatus, JobType, PersistenceMode, SourceType, SymlinkPolicy,
};
use orbok_db::Catalog;
use orbok_db::repo::{
FileRepository, IndexJobRepository, ModelRepository, ModelRole, ModelStatus,
NewFile, NewModel, NewSource, ObservedMetadata, SourceRepository,
};
use orbok_models::{EmbeddingModel, EmbeddingModelConfig, InferenceBackend, MockEmbeddingModel};
use crate::{
ChunkAndIndexWorker, CleanupService, ExtractionWorker,
check_catalog_integrity, run_pending, run_startup_recovery,
};
use std::fs;
fn setup(root: &std::path::Path) -> (Catalog, CacheService) {
let catalog = Catalog::open(root.join("catalog.sqlite3")).unwrap();
let cache = CacheService::new(root);
(catalog, cache)
}
fn cache_db_path(root: &std::path::Path) -> std::path::PathBuf {
root.join("orbok-cache.sqlite3")
}
fn seed_indexed(catalog: &Catalog, cache: &CacheService, root: &std::path::Path,
name: &str, content: &str) -> orbok_core::FileId {
let path = root.join(name);
fs::write(&path, content).unwrap();
let canonical = fs::canonicalize(&path).unwrap().to_string_lossy().to_string();
let root_str = fs::canonicalize(root).unwrap().to_string_lossy().to_string();
let src = SourceRepository::new(catalog).insert(NewSource {
source_type: SourceType::File,
persistence_mode: PersistenceMode::Persistent,
display_name: Some(name.into()),
original_path: canonical.clone(),
canonical_path: root_str,
index_mode: IndexMode::Balanced,
include_patterns: vec![],
exclude_patterns: vec![],
hidden_file_policy: HiddenFilePolicy::Exclude,
symlink_policy: SymlinkPolicy::Ignore,
max_file_size_bytes: None,
}).unwrap();
let file = FileRepository::new(catalog).insert(NewFile {
source_id: src.source_id.clone(),
original_path: canonical.clone(),
canonical_path: canonical,
display_path: name.into(),
extension: Some("md".into()),
metadata: ObservedMetadata {
file_size_bytes: content.len() as u64,
modified_at: Some("2026-01-01T00:00:00Z".into()),
platform_file_key: None,
content_hash: Some("abc".into()),
},
status: FileStatus::Discovered,
}).unwrap();
IndexJobRepository::new(catalog)
.enqueue(JobType::Extract, Some(&src.source_id), Some(&file.file_id))
.unwrap();
let e = ExtractionWorker::new(catalog, cache);
let c = ChunkAndIndexWorker::new(catalog, cache);
run_pending(catalog, &e, &c, None, 50).unwrap();
file.file_id
}
#[test]
fn cleanup_service_safe_preserves_sources() {
let dir = tempfile::tempdir().unwrap();
let (catalog, cache) = setup(dir.path());
let cache_path = cache_db_path(dir.path());
seed_indexed(&catalog, &cache, dir.path(), "doc.md", "# Test\n\nContent here.\n");
catalog.lock().execute(
"INSERT INTO snippet_cache (snippet_id, snippet_text, created_at, last_accessed_at, size_bytes)
VALUES ('s1', 'cached snippet', 't', 't', 100)",
[],
).unwrap();
let svc = CleanupService::new(&catalog, &cache, &cache_path);
let plan = CleanupPlan::for_action(CleanupAction::ClearSnippetCache, 100);
let outcome = svc.run_safe(&plan).unwrap();
assert_eq!(outcome.catalog_rows_deleted, 1, "snippet row should be deleted");
assert!(!SourceRepository::new(&catalog).list().unwrap().is_empty());
}
#[test]
fn cleanup_service_index_delete_preserves_catalog() {
let dir = tempfile::tempdir().unwrap();
let (catalog, cache) = setup(dir.path());
let cache_path = cache_db_path(dir.path());
let file_id = seed_indexed(&catalog, &cache, dir.path(), "doc.md", "important content\n");
let svc = CleanupService::new(&catalog, &cache, &cache_path);
let plan = CleanupPlan::for_action(CleanupAction::RemoveReplacedStaleIndexes, 0);
svc.run_safe(&plan).unwrap();
assert!(FileRepository::new(&catalog).get_by_id(&file_id).unwrap().is_some());
assert!(!SourceRepository::new(&catalog).list().unwrap().is_empty());
}
#[test]
fn cleanup_service_reset_removes_sources_not_files() {
let dir = tempfile::tempdir().unwrap();
let (catalog, cache) = setup(dir.path());
let cache_path = cache_db_path(dir.path());
let source_file = dir.path().join("doc.md");
seed_indexed(&catalog, &cache, dir.path(), "doc.md", "text\n");
assert!(source_file.exists(), "source file must exist before reset");
let svc = CleanupService::new(&catalog, &cache, &cache_path);
let plan = CleanupPlan::for_action(CleanupAction::ResetCatalog, 0);
let outcome = svc.run_reset(&plan, false).unwrap();
assert!(outcome.catalog_rows_deleted > 0);
assert!(SourceRepository::new(&catalog).list().unwrap().is_empty());
assert!(source_file.exists(), "source file must still exist after catalog reset");
}
#[test]
fn embedding_model_config_checks_file_existence() {
let dir = tempfile::tempdir().unwrap();
let model_path = dir.path().join("model.onnx");
let config_missing = EmbeddingModelConfig {
weights_path: model_path.to_string_lossy().into(),
tokenizer_path: None,
dimension: 768,
max_seq_len: 512,
backend: InferenceBackend::OnnxRuntime,
model_name: "test-model".into(),
model_version: "v1".into(),
};
assert!(!config_missing.weights_exist(), "file does not exist yet");
fs::write(&model_path, vec![0u8; 256]).unwrap();
let config_present = EmbeddingModelConfig {
weights_path: model_path.to_string_lossy().into(),
tokenizer_path: None,
dimension: 768,
max_seq_len: 512,
backend: InferenceBackend::CandleCpu,
model_name: "test-model".into(),
model_version: "v1".into(),
};
assert!(config_present.weights_exist(), "file exists now");
}
#[test]
fn mock_embedding_model_backend_is_mock() {
let model = MockEmbeddingModel;
assert_eq!(model.name(), "mock");
let vecs = model.embed_batch(&["some query text"]).unwrap();
assert_eq!(vecs.len(), 1);
assert_eq!(vecs[0].len(), 8);
}
#[test]
fn inference_backend_strings() {
assert_eq!(InferenceBackend::CandleCpu.as_str(), "candle-cpu");
assert_eq!(InferenceBackend::OnnxRuntime.as_str(), "onnx-runtime");
assert_eq!(InferenceBackend::Mock.as_str(), "mock");
}
#[test]
fn test_suite_covers_lifecycle_categories() {
let _ = CleanupAction::ClearSnippetCache;
let _ = CleanupAction::ClearExpiredSearchCache;
let _ = CleanupAction::RemoveReplacedStaleIndexes;
let _ = CleanupAction::ResetCatalog;
let _ = CleanupAction::DeleteKeywordIndex;
let _ = CleanupAction::DeleteVectorIndex;
}
#[test]
fn security_tests_are_present_and_labelled() {
}
#[test]
fn data_dir_resolves_to_platform_path_or_env_override() {
unsafe { std::env::set_var("ORBOK_DATA_DIR", "/tmp/orbok-ci-test"); }
let dir = orbok_app_data_dir_from_env();
assert_eq!(dir, std::path::PathBuf::from("/tmp/orbok-ci-test"));
unsafe { std::env::remove_var("ORBOK_DATA_DIR"); }
}
fn orbok_app_data_dir_from_env() -> std::path::PathBuf {
if let Ok(env) = std::env::var("ORBOK_DATA_DIR") {
std::path::PathBuf::from(env)
} else {
dirs::data_local_dir()
.map(|d| d.join("orbok"))
.unwrap_or_else(|| std::path::PathBuf::from("orbok-data"))
}
}