aprender-orchestrate 0.31.2

Sovereign AI orchestration: autonomous agents, ML serving, code analysis, and transpilation pipelines
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
470
471
472
473
//! RAG Index Persistence - Section 9.7 of oracle-mode-spec.md
//!
//! Persistent storage for the RAG index at `~/.cache/batuta/rag/`.
//! Uses JSON format with BLAKE3 checksums for integrity validation.
//!
//! # Toyota Production System Principles
//!
//! - **Jidoka**: Graceful degradation on corruption (rebuild instead of crash)
//! - **Poka-Yoke**: Version compatibility prevents format mismatches
//! - **Heijunka**: Incremental updates via fingerprint-based invalidation
//! - **Muda**: JSON for debugging, future P2 uses bincode

use super::fingerprint::{blake3_hash, DocumentFingerprint};
use super::types::{Bm25Config, RrfConfig};
use super::IndexedDocument;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};

/// Index format version (semver major.minor.patch)
///
/// 1.1.0: Added chunk_contents, stemming, stop words, TF-IDF dense search
pub const INDEX_VERSION: &str = "1.1.0";

/// Cache directory relative to user cache
const CACHE_SUBDIR: &str = "batuta/rag";

/// Manifest filename
const MANIFEST_FILE: &str = "manifest.json";

/// Index filename
const INDEX_FILE: &str = "index.json";

/// Documents filename
const DOCUMENTS_FILE: &str = "documents.json";

/// Fingerprints-only filename (lightweight, for `is_index_current` checks)
const FINGERPRINTS_FILE: &str = "fingerprints.json";

/// Persisted RAG index manifest
///
/// Contains metadata and checksums for integrity validation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RagManifest {
    /// Index format version (semver)
    pub version: String,
    /// BLAKE3 checksum of index.json
    pub index_checksum: [u8; 32],
    /// BLAKE3 checksum of documents.json
    pub docs_checksum: [u8; 32],
    /// Indexed corpus sources
    pub sources: Vec<CorpusSource>,
    /// Unix timestamp when indexed (milliseconds)
    pub indexed_at: u64,
    /// Batuta version that created this index
    pub batuta_version: String,
}

/// Source corpus information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CorpusSource {
    /// Corpus identifier (e.g., "trueno", "hf-ground-truth-corpus")
    pub id: String,
    /// Git commit hash at index time (if available)
    pub commit: Option<String>,
    /// Number of documents indexed from this source
    pub doc_count: usize,
    /// Number of chunks indexed from this source
    pub chunk_count: usize,
}

/// Serializable inverted index state
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PersistedIndex {
    /// Inverted index: term -> (doc_id -> term_frequency)
    pub inverted_index: HashMap<String, HashMap<String, usize>>,
    /// Document lengths for BM25
    pub doc_lengths: HashMap<String, usize>,
    /// BM25 configuration
    pub bm25_config: Bm25Config,
    /// RRF configuration
    pub rrf_config: RrfConfig,
    /// Average document length
    pub avg_doc_length: f64,
}

/// Serializable document metadata
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PersistedDocuments {
    /// Documents by ID
    pub documents: HashMap<String, IndexedDocument>,
    /// Fingerprints for change detection
    pub fingerprints: HashMap<String, DocumentFingerprint>,
    /// Total chunks indexed
    pub total_chunks: usize,
    /// Chunk content snippets (first 200 chars) for result display
    #[serde(default)]
    pub chunk_contents: HashMap<String, String>,
}

/// Persistence errors
#[derive(Debug, thiserror::Error)]
pub enum PersistenceError {
    /// I/O error
    #[error("I/O error: {0}")]
    Io(#[from] io::Error),

    /// JSON serialization error
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),

    /// Checksum mismatch (Jidoka halt)
    #[error("Checksum mismatch for {file}: expected {expected:x?}, got {actual:x?}")]
    ChecksumMismatch { file: String, expected: [u8; 32], actual: [u8; 32] },

    /// Version mismatch
    #[error("Version mismatch: index version {index_version}, expected {expected_version}")]
    VersionMismatch { index_version: String, expected_version: String },

    /// Cache directory not found
    #[error("Cache directory not found")]
    CacheDirNotFound,

    /// Manifest not found (no cached index)
    #[error("No cached index found")]
    NoCachedIndex,
}

/// RAG index persistence manager
///
/// Handles saving and loading the RAG index to/from disk.
#[derive(Debug)]
pub struct RagPersistence {
    /// Cache path
    cache_path: PathBuf,
}

impl RagPersistence {
    /// Create persistence manager with default cache path
    ///
    /// Default path: `~/.cache/batuta/rag/`
    pub fn new() -> Self {
        Self { cache_path: Self::default_cache_path() }
    }

    /// Create persistence manager with custom cache path
    pub fn with_path(path: PathBuf) -> Self {
        Self { cache_path: path }
    }

    /// Get default cache path
    ///
    /// Uses `dirs::cache_dir()` for platform-specific cache location.
    fn default_cache_path() -> PathBuf {
        #[cfg(feature = "native")]
        {
            dirs::cache_dir().unwrap_or_else(|| PathBuf::from(".cache")).join(CACHE_SUBDIR)
        }
        #[cfg(not(feature = "native"))]
        {
            PathBuf::from(".cache").join(CACHE_SUBDIR)
        }
    }

    /// Get the cache path
    pub fn cache_path(&self) -> &Path {
        &self.cache_path
    }

    /// Save index to disk using two-phase commit
    ///
    /// Writes three files with crash safety:
    /// - **Prepare phase**: Write all `.tmp` files (crash here = old cache intact)
    /// - **Commit phase**: Rename all 3, manifest LAST (crash before manifest
    ///   rename = old manifest still valid or checksum mismatch triggers rebuild)
    ///
    /// Files written:
    /// - `manifest.json`: Version and checksums
    /// - `index.json`: Inverted index data
    /// - `documents.json`: Document metadata
    pub fn save(
        &self,
        index: &PersistedIndex,
        docs: &PersistedDocuments,
        sources: Vec<CorpusSource>,
    ) -> Result<(), PersistenceError> {
        // Ensure cache directory exists
        fs::create_dir_all(&self.cache_path)?;

        // Clean up any orphaned .tmp files from a previous crashed save
        self.cleanup_tmp_files();

        // Serialize index and documents
        let index_json = serde_json::to_string_pretty(index)?;
        let docs_json = serde_json::to_string_pretty(docs)?;

        // Serialize fingerprints separately for fast is_index_current checks
        let fingerprints_json = serde_json::to_string_pretty(&docs.fingerprints)?;

        // Compute checksums
        let index_checksum = blake3_hash(index_json.as_bytes());
        let docs_checksum = blake3_hash(docs_json.as_bytes());

        // Create manifest
        let manifest = RagManifest {
            version: INDEX_VERSION.to_string(),
            index_checksum,
            docs_checksum,
            sources,
            indexed_at: current_timestamp_ms(),
            batuta_version: env!("CARGO_PKG_VERSION").to_string(),
        };
        let manifest_json = serde_json::to_string_pretty(&manifest)?;

        // Phase 1: Prepare — write all .tmp files (crash here = old cache intact)
        self.prepare_write(INDEX_FILE, index_json.as_bytes())?;
        self.prepare_write(DOCUMENTS_FILE, docs_json.as_bytes())?;
        self.prepare_write(FINGERPRINTS_FILE, fingerprints_json.as_bytes())?;
        self.prepare_write(MANIFEST_FILE, manifest_json.as_bytes())?;

        // Phase 2: Commit — rename all, manifest LAST
        // Crash before manifest rename = old manifest checksums won't match new
        // data files, which triggers graceful rebuild on next load().
        self.commit_rename(INDEX_FILE)?;
        self.commit_rename(DOCUMENTS_FILE)?;
        self.commit_rename(FINGERPRINTS_FILE)?;
        self.commit_rename(MANIFEST_FILE)?;

        Ok(())
    }

    /// Load index from disk
    ///
    /// Returns `None` if no cached index exists or if the cache is corrupted
    /// (IO error, checksum mismatch, invalid JSON). Corruption triggers a
    /// warning to stderr so the caller can rebuild gracefully.
    ///
    /// Returns `Err` only for `VersionMismatch` (incompatible format requires
    /// a code update, not just a re-index).
    pub fn load(
        &self,
    ) -> Result<Option<(PersistedIndex, PersistedDocuments, RagManifest)>, PersistenceError> {
        let manifest_path = self.cache_path.join(MANIFEST_FILE);

        // Check if manifest exists
        if !manifest_path.exists() {
            return Ok(None);
        }

        // Load manifest — graceful on IO/JSON errors
        let manifest_json = match fs::read_to_string(&manifest_path) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("Warning: failed to read RAG manifest, will rebuild: {e}");
                return Ok(None);
            }
        };
        let manifest: RagManifest = match serde_json::from_str(&manifest_json) {
            Ok(m) => m,
            Err(e) => {
                eprintln!("Warning: corrupt RAG manifest JSON, will rebuild: {e}");
                return Ok(None);
            }
        };

        // Validate version (Poka-Yoke) — hard error, needs code update
        self.validate_version(&manifest)?;

        // Load and validate index — graceful on IO/JSON/checksum errors
        let index_json = match fs::read_to_string(self.cache_path.join(INDEX_FILE)) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("Warning: failed to read RAG index file, will rebuild: {e}");
                return Ok(None);
            }
        };
        if let Err(e) = self.validate_checksum(&index_json, manifest.index_checksum, "index.json") {
            eprintln!("Warning: {e}, will rebuild");
            return Ok(None);
        }
        let index: PersistedIndex = match serde_json::from_str(&index_json) {
            Ok(i) => i,
            Err(e) => {
                eprintln!("Warning: corrupt RAG index JSON, will rebuild: {e}");
                return Ok(None);
            }
        };

        // Load and validate documents — graceful on IO/JSON/checksum errors
        let docs_json = match fs::read_to_string(self.cache_path.join(DOCUMENTS_FILE)) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("Warning: failed to read RAG documents file, will rebuild: {e}");
                return Ok(None);
            }
        };
        if let Err(e) = self.validate_checksum(&docs_json, manifest.docs_checksum, "documents.json")
        {
            eprintln!("Warning: {e}, will rebuild");
            return Ok(None);
        }
        let docs: PersistedDocuments = match serde_json::from_str(&docs_json) {
            Ok(d) => d,
            Err(e) => {
                eprintln!("Warning: corrupt RAG documents JSON, will rebuild: {e}");
                return Ok(None);
            }
        };

        Ok(Some((index, docs, manifest)))
    }

    /// Load only fingerprints for fast `is_index_current` checks.
    ///
    /// Reads ~KB fingerprints.json instead of ~600MB (index.json + documents.json).
    /// Falls back to full `load()` if fingerprints.json doesn't exist (pre-upgrade cache).
    pub fn load_fingerprints_only(
        &self,
    ) -> Result<Option<HashMap<String, DocumentFingerprint>>, PersistenceError> {
        let fp_path = self.cache_path.join(FINGERPRINTS_FILE);

        if fp_path.exists() {
            let fp_json = match fs::read_to_string(&fp_path) {
                Ok(s) => s,
                Err(_) => return self.load_fingerprints_fallback(),
            };
            match serde_json::from_str(&fp_json) {
                Ok(fps) => return Ok(Some(fps)),
                Err(_) => return self.load_fingerprints_fallback(),
            }
        }

        // Fallback: fingerprints.json doesn't exist (pre-upgrade cache)
        self.load_fingerprints_fallback()
    }

    /// Fallback: extract fingerprints from full documents.json load
    fn load_fingerprints_fallback(
        &self,
    ) -> Result<Option<HashMap<String, DocumentFingerprint>>, PersistenceError> {
        self.load().map(|opt| opt.map(|(_, docs, _)| docs.fingerprints))
    }

    /// Save only fingerprints.json for fast `is_index_current` checks.
    ///
    /// Used by the SQLite indexing path to persist fingerprints without
    /// writing the full 600MB JSON index/documents files.
    pub fn save_fingerprints_only(
        &self,
        fingerprints: &HashMap<String, DocumentFingerprint>,
    ) -> Result<(), PersistenceError> {
        fs::create_dir_all(&self.cache_path)?;
        let fingerprints_json = serde_json::to_string_pretty(fingerprints)?;
        self.prepare_write(FINGERPRINTS_FILE, fingerprints_json.as_bytes())?;
        self.commit_rename(FINGERPRINTS_FILE)?;
        Ok(())
    }

    /// Clear cached index
    pub fn clear(&self) -> Result<(), PersistenceError> {
        if self.cache_path.exists() {
            // Remove individual files
            let _ = fs::remove_file(self.cache_path.join(MANIFEST_FILE));
            let _ = fs::remove_file(self.cache_path.join(INDEX_FILE));
            let _ = fs::remove_file(self.cache_path.join(DOCUMENTS_FILE));
            let _ = fs::remove_file(self.cache_path.join(FINGERPRINTS_FILE));

            // Try to remove directory if empty
            let _ = fs::remove_dir(&self.cache_path);
        }
        Ok(())
    }

    /// Get index statistics without full load
    pub fn stats(&self) -> Result<Option<RagManifest>, PersistenceError> {
        let manifest_path = self.cache_path.join(MANIFEST_FILE);

        if !manifest_path.exists() {
            return Ok(None);
        }

        let manifest_json = fs::read_to_string(&manifest_path)?;
        let manifest: RagManifest = serde_json::from_str(&manifest_json)?;

        Ok(Some(manifest))
    }

    /// Phase 1: Write data to a `.tmp` file (prepare)
    fn prepare_write(&self, filename: &str, data: &[u8]) -> Result<(), io::Error> {
        let tmp_path = self.cache_path.join(format!("{}.tmp", filename));

        let mut file = fs::File::create(&tmp_path)?;
        file.write_all(data)?;
        file.sync_all()?;

        Ok(())
    }

    /// Phase 2: Rename `.tmp` file to final path (commit)
    fn commit_rename(&self, filename: &str) -> Result<(), io::Error> {
        let tmp_path = self.cache_path.join(format!("{}.tmp", filename));
        let final_path = self.cache_path.join(filename);

        fs::rename(&tmp_path, &final_path)?;

        Ok(())
    }

    /// Remove orphaned `.tmp` files from a previous crashed save
    fn cleanup_tmp_files(&self) {
        for filename in &[MANIFEST_FILE, INDEX_FILE, DOCUMENTS_FILE] {
            let tmp_path = self.cache_path.join(format!("{}.tmp", filename));
            let _ = fs::remove_file(tmp_path);
        }
    }

    /// Validate version compatibility (Poka-Yoke)
    fn validate_version(&self, manifest: &RagManifest) -> Result<(), PersistenceError> {
        // Parse versions
        let index_parts: Vec<&str> = manifest.version.split('.').collect();
        let expected_parts: Vec<&str> = INDEX_VERSION.split('.').collect();

        // Major version must match for compatibility
        if index_parts.first() != expected_parts.first() {
            return Err(PersistenceError::VersionMismatch {
                index_version: manifest.version.clone(),
                expected_version: INDEX_VERSION.to_string(),
            });
        }

        Ok(())
    }

    /// Validate checksum (Jidoka)
    fn validate_checksum(
        &self,
        data: &str,
        expected: [u8; 32],
        filename: &str,
    ) -> Result<(), PersistenceError> {
        let actual = blake3_hash(data.as_bytes());

        if actual != expected {
            return Err(PersistenceError::ChecksumMismatch {
                file: filename.to_string(),
                expected,
                actual,
            });
        }

        Ok(())
    }
}

impl Default for RagPersistence {
    fn default() -> Self {
        Self::new()
    }
}

/// Get current timestamp in milliseconds
fn current_timestamp_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

#[cfg(test)]
#[path = "persistence_tests.rs"]
mod tests;