turbovault-core 1.3.2

Core data models and types for TurboVault Server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! Cross-platform persistent cache for vault configuration and state
//!
//! This module provides a cache mechanism to persist vault registrations and
//! the active vault across server restarts. This solves the "amnesia" problem
//! where Claude Desktop starts a new process for each conversation, losing
//! all runtime vault state.
//!
//! PROJECT-AWARE CACHING:
//! Each project has its own vault registry, identified by:
//! 1. Project marker detection: .git/, .obsidian/, Cargo.toml, package.json
//! 2. Working directory: the directory where the server was started
//! 3. SHA256 hash of the working directory path for safe file naming
//!
//! Cache structure:
//! ~/.cache/turbovault/projects/{project_hash}/vaults.yaml
//! ~/.cache/turbovault/projects/{project_hash}/metadata.json
//!
//! Cache location:
//! - Linux/macOS: ~/.cache/turbovault/ or $XDG_CACHE_HOME/turbovault/
//! - Windows: %LOCALAPPDATA%\turbovault\cache\
//! - Fallback: ~/.turbovault/cache/ (all platforms)

use crate::config::VaultConfig;
use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
use tokio::fs;

/// Cache metadata: which vault is active and when cache was last updated
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheMetadata {
    /// Currently active vault name
    pub active_vault: String,
    /// Unix timestamp of last cache update
    pub last_updated: u64,
    /// Cache format version for future compatibility
    pub version: u32,
    /// Project identifier (working directory hash)
    pub project_id: String,
    /// Working directory path (for reference)
    pub working_dir: String,
}

/// Persistent cache for vault state - PROJECT-AWARE
pub struct VaultCache {
    cache_dir: PathBuf,
    project_cache_dir: PathBuf,
    vaults_file: PathBuf,
    metadata_file: PathBuf,
    project_id: String,
    working_dir: PathBuf,
}

impl VaultCache {
    /// Initialize cache in the appropriate platform-specific directory
    /// Auto-detects project using markers (.git, .obsidian, Cargo.toml, package.json)
    pub async fn init() -> Result<Self> {
        let cache_dir = Self::get_cache_dir()?;
        let working_dir = std::env::current_dir().map_err(Error::io)?;
        let project_id = Self::get_project_id(&working_dir)?;
        let project_cache_dir = cache_dir.join("projects").join(&project_id);

        // Create project cache directory if it doesn't exist
        if !project_cache_dir.exists() {
            fs::create_dir_all(&project_cache_dir)
                .await
                .map_err(Error::io)?;
        }

        Ok(Self {
            cache_dir,
            project_cache_dir: project_cache_dir.clone(),
            vaults_file: project_cache_dir.join("vaults.yaml"),
            metadata_file: project_cache_dir.join("metadata.json"),
            project_id,
            working_dir,
        })
    }

    /// Initialize cache with a specific project (useful for testing)
    pub async fn init_with_project(project_root: &Path) -> Result<Self> {
        let cache_dir = Self::get_cache_dir()?;
        let project_id = Self::get_project_id(project_root)?;
        let project_cache_dir = cache_dir.join("projects").join(&project_id);

        // Create project cache directory if it doesn't exist
        if !project_cache_dir.exists() {
            fs::create_dir_all(&project_cache_dir)
                .await
                .map_err(Error::io)?;
        }

        Ok(Self {
            cache_dir,
            project_cache_dir: project_cache_dir.clone(),
            vaults_file: project_cache_dir.join("vaults.yaml"),
            metadata_file: project_cache_dir.join("metadata.json"),
            project_id,
            working_dir: project_root.to_path_buf(),
        })
    }

    /// Detect project by looking for markers in parent directories
    /// Returns a hash of the project root directory path
    fn get_project_id(start_path: &Path) -> Result<String> {
        // Look for project markers going up the directory tree
        let markers = vec![
            ".git",
            ".obsidian",
            "Cargo.toml",
            "package.json",
            ".project",
        ];

        let mut current = start_path.to_path_buf();
        loop {
            for marker in &markers {
                let marker_path = current.join(marker);
                if marker_path.exists() {
                    // Found a project marker - use this directory as project root
                    let canonical = current.canonicalize().unwrap_or_else(|_| current.clone());
                    let project_id = Self::hash_path(&canonical);
                    log::debug!(
                        "Detected project root: {} (hash: {})",
                        canonical.display(),
                        project_id
                    );
                    return Ok(project_id);
                }
            }

            // Move up one directory
            if !current.pop() {
                // Reached filesystem root without finding markers
                // Use the original start path as project identifier
                let canonical = start_path
                    .canonicalize()
                    .unwrap_or_else(|_| start_path.to_path_buf());
                let project_id = Self::hash_path(&canonical);
                log::debug!(
                    "No project marker found, using start path: {} (hash: {})",
                    canonical.display(),
                    project_id
                );
                return Ok(project_id);
            }
        }
    }

    /// Hash a path to create a safe filename
    fn hash_path(path: &Path) -> String {
        let path_str = path.to_string_lossy();
        let mut hasher = Sha256::new();
        hasher.update(path_str.as_bytes());
        let result = hasher.finalize();
        format!("{:x}", result)[..16].to_string() // Use first 16 chars of hash
    }

    /// Get the platform-specific cache directory
    fn get_cache_dir() -> Result<PathBuf> {
        if let Ok(cache_home) = std::env::var("XDG_CACHE_HOME") {
            // Linux with XDG_CACHE_HOME set
            return Ok(PathBuf::from(cache_home).join("turbovault"));
        }

        // Use platform-specific defaults
        #[cfg(target_os = "windows")]
        {
            if let Ok(local_app_data) = std::env::var("LOCALAPPDATA") {
                return Ok(PathBuf::from(local_app_data)
                    .join("turbovault")
                    .join("cache"));
            }
        }

        #[cfg(not(target_os = "windows"))]
        {
            if let Ok(home) = std::env::var("HOME") {
                return Ok(PathBuf::from(home).join(".cache").join("turbovault"));
            }
        }

        // Fallback to ~/.turbovault/cache/ for all platforms
        if let Ok(home) = std::env::var("HOME") {
            return Ok(PathBuf::from(home).join(".turbovault").join("cache"));
        }

        Err(Error::config_error(
            "Cannot determine cache directory: HOME not set and no platform-specific override found".to_string()
        ))
    }

    /// Save vault configurations and metadata
    pub async fn save_vaults(&self, vaults: &[VaultConfig], active_vault: &str) -> Result<()> {
        // Save vaults as YAML
        let vaults_yaml = serde_yaml::to_string(vaults)
            .map_err(|e| Error::config_error(format!("Failed to serialize vaults: {}", e)))?;

        fs::write(&self.vaults_file, vaults_yaml)
            .await
            .map_err(Error::io)?;

        // Save metadata as JSON
        let metadata = CacheMetadata {
            active_vault: active_vault.to_string(),
            last_updated: Self::current_timestamp(),
            version: 1,
            project_id: self.project_id.clone(),
            working_dir: self.working_dir.to_string_lossy().to_string(),
        };

        let metadata_json = serde_json::to_string_pretty(&metadata)
            .map_err(|e| Error::config_error(format!("Failed to serialize metadata: {}", e)))?;

        fs::write(&self.metadata_file, metadata_json)
            .await
            .map_err(Error::io)?;

        log::debug!(
            "Saved {} vaults to project cache {} (active: {})",
            vaults.len(),
            self.project_id,
            active_vault
        );

        Ok(())
    }

    /// Load vault configurations from cache
    pub async fn load_vaults(&self) -> Result<Vec<VaultConfig>> {
        if !self.vaults_file.exists() {
            return Ok(Vec::new()); // No cache yet
        }

        let content = fs::read_to_string(&self.vaults_file)
            .await
            .map_err(Error::io)?;

        let vaults = serde_yaml::from_str(&content)
            .map_err(|e| Error::config_error(format!("Invalid vaults cache format: {}", e)))?;

        log::debug!("Loaded vaults from project cache {}", self.project_id);

        Ok(vaults)
    }

    /// Load metadata (active vault, etc.)
    pub async fn load_metadata(&self) -> Result<CacheMetadata> {
        if !self.metadata_file.exists() {
            return Ok(CacheMetadata {
                active_vault: String::new(),
                last_updated: 0,
                version: 1,
                project_id: self.project_id.clone(),
                working_dir: self.working_dir.to_string_lossy().to_string(),
            });
        }

        let content = fs::read_to_string(&self.metadata_file)
            .await
            .map_err(Error::io)?;

        let metadata = serde_json::from_str(&content)
            .map_err(|e| Error::config_error(format!("Invalid metadata cache format: {}", e)))?;

        Ok(metadata)
    }

    /// Clear all cached data for this project
    pub async fn clear(&self) -> Result<()> {
        if self.vaults_file.exists() {
            fs::remove_file(&self.vaults_file)
                .await
                .map_err(Error::io)?;
        }

        if self.metadata_file.exists() {
            fs::remove_file(&self.metadata_file)
                .await
                .map_err(Error::io)?;
        }

        log::info!("Cache cleared for project {}", self.project_id);
        Ok(())
    }

    /// Get cache directory for diagnostics
    pub fn cache_dir(&self) -> &Path {
        &self.cache_dir
    }

    /// Get project cache directory for diagnostics
    pub fn project_cache_dir(&self) -> &Path {
        &self.project_cache_dir
    }

    /// Get project identifier for diagnostics
    pub fn project_id(&self) -> &str {
        &self.project_id
    }

    /// Get working directory for diagnostics
    pub fn working_dir(&self) -> &Path {
        &self.working_dir
    }

    fn current_timestamp() -> u64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::VaultConfig;
    use tempfile::TempDir;

    // ── Helpers ──────────────────────────────────────────────────────────────

    /// Build a VaultCache whose project-cache directory lives entirely inside
    /// a temporary directory, keeping tests isolated from each other and from
    /// the real user cache.
    ///
    /// We point `XDG_CACHE_HOME` at the temp dir so `get_cache_dir()` uses it.
    ///
    /// SAFETY: modifying environment variables is unsafe in Rust 2024+ because
    /// it is not thread-safe; however these tests are run with `#[tokio::test]`
    /// which provides single-threaded isolation for each test function.
    async fn make_cache(temp: &TempDir) -> VaultCache {
        // Override the cache root so nothing leaks into ~/.cache
        // SAFETY: single-threaded test context; no other threads read XDG_CACHE_HOME.
        unsafe { std::env::set_var("XDG_CACHE_HOME", temp.path()) };
        VaultCache::init_with_project(temp.path()).await.unwrap()
    }

    fn make_vault_config(name: &str, path: &std::path::Path) -> VaultConfig {
        VaultConfig {
            name: name.to_string(),
            path: path.to_path_buf(),
            is_default: false,
            watch_for_changes: None,
            max_file_size: None,
            allowed_extensions: None,
            excluded_paths: None,
            enable_caching: None,
            cache_ttl: None,
            template_dirs: None,
            allowed_operations: None,
        }
    }

    // ── Tests ─────────────────────────────────────────────────────────────────

    #[test]
    fn test_hash_path_deterministic() {
        let path = Path::new("/home/user/projects/vault");
        let h1 = VaultCache::hash_path(path);
        let h2 = VaultCache::hash_path(path);
        assert_eq!(h1, h2, "same path must always produce the same hash");
        // The implementation truncates to 16 hex chars
        assert_eq!(h1.len(), 16);
    }

    #[test]
    fn test_hash_path_different_paths() {
        let h1 = VaultCache::hash_path(Path::new("/home/user/vault-a"));
        let h2 = VaultCache::hash_path(Path::new("/home/user/vault-b"));
        assert_ne!(h1, h2, "different paths must produce different hashes");
    }

    #[tokio::test]
    async fn test_init_creates_cache_directory() {
        let temp = TempDir::new().unwrap();
        // SAFETY: single-threaded test context; no other threads read XDG_CACHE_HOME.
        unsafe { std::env::set_var("XDG_CACHE_HOME", temp.path()) };

        let cache = VaultCache::init_with_project(temp.path()).await.unwrap();

        // The project cache directory should now exist on disk
        assert!(
            cache.project_cache_dir().exists(),
            "project cache dir should be created by init_with_project"
        );
        assert!(cache.project_cache_dir().is_dir());
    }

    #[tokio::test]
    async fn test_save_and_load_roundtrip() {
        let temp = TempDir::new().unwrap();
        let cache = make_cache(&temp).await;

        let configs = vec![
            make_vault_config("personal", &temp.path().join("personal")),
            make_vault_config("work", &temp.path().join("work")),
        ];

        cache.save_vaults(&configs, "personal").await.unwrap();

        let loaded = cache.load_vaults().await.unwrap();
        assert_eq!(loaded.len(), 2);

        let names: Vec<&str> = loaded.iter().map(|v| v.name.as_str()).collect();
        assert!(names.contains(&"personal"));
        assert!(names.contains(&"work"));

        let meta = cache.load_metadata().await.unwrap();
        assert_eq!(meta.active_vault, "personal");
    }

    #[tokio::test]
    async fn test_clear_removes_data() {
        let temp = TempDir::new().unwrap();
        let cache = make_cache(&temp).await;

        let configs = vec![make_vault_config("v1", &temp.path().join("v1"))];
        cache.save_vaults(&configs, "v1").await.unwrap();

        // Confirm data is there before clearing
        assert_eq!(cache.load_vaults().await.unwrap().len(), 1);

        cache.clear().await.unwrap();

        // After clearing, load_vaults should return an empty vec (no file = no data)
        let after = cache.load_vaults().await.unwrap();
        assert!(after.is_empty(), "cleared cache should return no vaults");
    }

    #[tokio::test]
    async fn test_load_nonexistent_returns_empty() {
        let temp = TempDir::new().unwrap();
        let cache = make_cache(&temp).await;

        // Never called save_vaults — vaults.yaml does not exist yet
        let vaults = cache.load_vaults().await.unwrap();
        assert!(
            vaults.is_empty(),
            "missing cache file should produce empty vec, not an error"
        );
    }

    #[tokio::test]
    async fn test_corrupted_cache_graceful() {
        let temp = TempDir::new().unwrap();
        let cache = make_cache(&temp).await;

        // Write invalid YAML directly to the vaults file
        let vaults_path = cache.project_cache_dir().join("vaults.yaml");
        tokio::fs::write(&vaults_path, b"{ not: [valid: yaml---\x00\xff")
            .await
            .unwrap();

        // load_vaults must not panic; it may return Err or Ok(empty)
        let result = cache.load_vaults().await;
        // Either outcome is acceptable — panic is not
        match result {
            Ok(vaults) => {
                // Tolerate implementations that silently discard corrupt caches
                let _ = vaults;
            }
            Err(_) => {
                // Tolerate implementations that surface the parse error
            }
        }
    }
}