batuta 0.7.3

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
//! Property-based tests for crates_io module.

use super::helpers::{make_full_response, make_response};
use crate::stack::crates_io::cache::PersistentCache;
use crate::stack::crates_io::types::{CacheEntry, PersistentCacheEntry};
use crate::stack::crates_io::MockCratesIoClient;
use proptest::prelude::*;
use std::time::Duration;

// ============================================================================
// CRATES-007: CratesIoClient sync method tests
// ============================================================================

#[cfg(feature = "native")]
#[test]
fn test_crates_007_client_clear_cache() {
    use crate::stack::crates_io::client::CratesIoClient;
    let mut client = CratesIoClient::new();

    // Add something to cache manually (via internal testing)
    let response = make_response("test", "1.0.0");

    client.cache.insert("test".to_string(), CacheEntry::new(response, Duration::from_secs(3600)));

    assert!(!client.cache.is_empty());
    client.clear_cache();
    assert!(client.cache.is_empty());
}

#[cfg(feature = "native")]
#[test]
fn test_crates_007_client_clear_expired() {
    use crate::stack::crates_io::client::CratesIoClient;
    let mut client = CratesIoClient::new();

    // Add an expired entry
    let response = make_response("expired", "1.0.0");

    client
        .cache
        .insert("expired".to_string(), CacheEntry::new(response.clone(), Duration::from_secs(0)));

    // Add a valid entry
    client.cache.insert("valid".to_string(), CacheEntry::new(response, Duration::from_secs(3600)));

    assert_eq!(client.cache.len(), 2);
    client.clear_expired();
    assert_eq!(client.cache.len(), 1);
    assert!(client.cache.contains_key("valid"));
}

#[cfg(feature = "native")]
#[test]
fn test_crates_007_client_with_cache_ttl() {
    use crate::stack::crates_io::client::CratesIoClient;
    let client = CratesIoClient::new().with_cache_ttl(Duration::from_secs(60));
    assert_eq!(client.cache_ttl, Duration::from_secs(60));
}

#[cfg(feature = "native")]
#[test]
fn test_crates_007_client_with_persistent_cache() {
    use crate::stack::crates_io::client::CratesIoClient;
    let client = CratesIoClient::new().with_persistent_cache();
    assert!(client.persistent_cache.is_some());
}

#[cfg(feature = "native")]
#[test]
fn test_crates_007_client_offline_mode() {
    use crate::stack::crates_io::client::CratesIoClient;
    let mut client = CratesIoClient::new();
    assert!(!client.is_offline());

    client.set_offline(true);
    assert!(client.is_offline());

    client.set_offline(false);
    assert!(!client.is_offline());
}

#[cfg(feature = "native")]
#[test]
fn test_crates_007_client_default() {
    use crate::stack::crates_io::client::CratesIoClient;
    let client = CratesIoClient::default();
    assert!(!client.is_offline());
    assert!(client.cache.is_empty());
}

// ============================================================================
// CRATES-008: PersistentCache file operations
// ============================================================================

#[test]
fn test_crates_008_persistent_cache_path() {
    let path = PersistentCache::cache_path();
    assert!(path.to_string_lossy().contains("batuta"));
    assert!(path.to_string_lossy().contains("crates_io_cache.json"));
}

#[test]
fn test_crates_008_persistent_cache_load_nonexistent() {
    // Loading from nonexistent path should return empty cache
    let cache = PersistentCache::load();
    // Just verify it doesn't panic - cache may or may not have entries
    // depending on previous test runs
    let _ = cache.entries.len();
}

#[test]
fn test_crates_008_persistent_cache_save_load_roundtrip() {
    let temp_dir = std::env::temp_dir().join("batuta_crates_io_test");
    let _ = std::fs::remove_dir_all(&temp_dir);
    std::fs::create_dir_all(&temp_dir).unwrap();

    let cache_path = temp_dir.join("test_cache.json");

    let mut cache = PersistentCache::default();
    let mut roundtrip_response = make_full_response("test-crate", "1.0.0", Some("Test"), 100);
    roundtrip_response.krate.updated_at = "2025-01-01".to_string();
    roundtrip_response.versions[0].created_at = "2025-01-01".to_string();
    cache.insert("test-crate".to_string(), roundtrip_response, Duration::from_secs(3600));

    // Save to custom path
    let data = serde_json::to_string_pretty(&cache).unwrap();
    std::fs::write(&cache_path, data).unwrap();

    // Load and verify
    let loaded_data = std::fs::read_to_string(&cache_path).unwrap();
    let loaded: PersistentCache = serde_json::from_str(&loaded_data).unwrap();
    assert!(loaded.get("test-crate").is_some());
    assert_eq!(loaded.get("test-crate").unwrap().krate.name, "test-crate");

    let _ = std::fs::remove_dir_all(&temp_dir);
}

proptest! {
    /// PROPERTY: CacheEntry with positive TTL starts non-expired
    #[test]
    fn prop_cache_entry_starts_valid(ttl_secs in 1u64..1000) {
        let entry = CacheEntry::new("test", Duration::from_secs(ttl_secs));
        prop_assert!(!entry.is_expired());
    }

    /// PROPERTY: MockCratesIoClient returns consistent versions
    #[test]
    fn prop_mock_client_version_consistency(
        major in 0u64..100,
        minor in 0u64..100,
        patch in 0u64..100
    ) {
        let version_str = format!("{}.{}.{}", major, minor, patch);
        let mut mock = MockCratesIoClient::new();
        mock.add_crate("test", &version_str);

        let latest = mock.get_latest_version("test").unwrap();
        prop_assert_eq!(latest.major, major);
        prop_assert_eq!(latest.minor, minor);
        prop_assert_eq!(latest.patch, patch);
    }

    /// PROPERTY: Added crate is always found
    #[test]
    fn prop_added_crate_always_found(
        name in "[a-z][a-z0-9_-]{0,20}",
        version in "[0-9]+\\.[0-9]+\\.[0-9]+"
    ) {
        let mut mock = MockCratesIoClient::new();
        mock.add_crate(&name, &version);

        let result = mock.get_crate(&name);
        prop_assert!(result.is_ok());
        prop_assert_eq!(result.unwrap().krate.name, name);
    }

    /// PROPERTY: Not-found crate always errors
    #[test]
    fn prop_not_found_always_errors(
        name in "[a-z][a-z0-9_-]{0,20}"
    ) {
        let mut mock = MockCratesIoClient::new();
        mock.add_not_found(&name);

        let result = mock.get_crate(&name);
        prop_assert!(result.is_err());
    }
}

// ============================================================================
// CRATES-009: Additional PersistentCache edge cases
// ============================================================================

#[test]
fn test_crates_009_persistent_cache_entry_debug() {
    let response = make_response("debug", "1.0.0");
    let entry = PersistentCacheEntry::new(response, Duration::from_secs(60));
    let debug = format!("{:?}", entry);
    assert!(debug.contains("PersistentCacheEntry"));
}

#[test]
fn test_crates_009_persistent_cache_debug() {
    let cache = PersistentCache::default();
    let debug = format!("{:?}", cache);
    assert!(debug.contains("PersistentCache"));
}

#[test]
fn test_crates_009_persistent_cache_clone_entry() {
    let mut response = make_full_response("clone", "1.0.0", Some("test"), 100);
    response.krate.updated_at = "2025-01-01".to_string();
    response.versions[0].downloads = 50;
    response.versions[0].created_at = "2025-01-01".to_string();
    let entry = PersistentCacheEntry::new(response, Duration::from_secs(60));
    let cloned = entry.clone();
    assert_eq!(cloned.response.krate.name, "clone");
    assert_eq!(cloned.expires_at, entry.expires_at);
}

#[test]
fn test_crates_009_persistent_cache_multiple_entries() {
    let mut cache = PersistentCache::default();

    for i in 0..10 {
        let mut response = make_response(&format!("crate-{}", i), &format!("0.{}.0", i));
        response.krate.downloads = i as u64 * 100;
        cache.insert(format!("crate-{}", i), response, Duration::from_secs(3600));
    }

    assert_eq!(cache.entries.len(), 10);
    for i in 0..10 {
        assert!(cache.get(&format!("crate-{}", i)).is_some());
    }
}

#[test]
fn test_crates_009_persistent_cache_overwrite() {
    let mut cache = PersistentCache::default();

    let response1 = make_response("overwrite", "1.0.0");
    cache.insert("overwrite".to_string(), response1, Duration::from_secs(3600));

    let response2 = make_response("overwrite", "2.0.0");
    cache.insert("overwrite".to_string(), response2, Duration::from_secs(3600));

    assert_eq!(cache.entries.len(), 1);
    assert_eq!(cache.get("overwrite").unwrap().krate.max_version, "2.0.0");
}

// ============================================================================
// CRATES-010: CratesIoClient debug and additional tests
// ============================================================================

#[cfg(feature = "native")]
#[test]
fn test_crates_010_client_debug() {
    use crate::stack::crates_io::client::CratesIoClient;
    let client = CratesIoClient::new();
    let debug = format!("{:?}", client);
    assert!(debug.contains("CratesIoClient"));
}

#[cfg(feature = "native")]
#[test]
fn test_crates_010_client_cache_insert_and_clear() {
    use crate::stack::crates_io::client::CratesIoClient;
    let mut client = CratesIoClient::new();

    for i in 0..5 {
        let response = make_response(&format!("test-{}", i), "1.0.0");
        client
            .cache
            .insert(format!("test-{}", i), CacheEntry::new(response, Duration::from_secs(3600)));
    }

    assert_eq!(client.cache.len(), 5);
    client.clear_cache();
    assert!(client.cache.is_empty());
}

#[cfg(feature = "native")]
#[test]
fn test_crates_010_client_mixed_ttl() {
    use crate::stack::crates_io::client::CratesIoClient;
    let mut client = CratesIoClient::new();

    // Add entries with different TTLs
    for i in 0..3 {
        let response = make_response(&format!("expired-{}", i), "1.0.0");
        // Expired
        client
            .cache
            .insert(format!("expired-{}", i), CacheEntry::new(response, Duration::from_secs(0)));
    }

    for i in 0..3 {
        let response = make_response(&format!("valid-{}", i), "1.0.0");
        // Valid
        client
            .cache
            .insert(format!("valid-{}", i), CacheEntry::new(response, Duration::from_secs(3600)));
    }

    assert_eq!(client.cache.len(), 6);
    client.clear_expired();
    assert_eq!(client.cache.len(), 3);
}

// ============================================================================
// CRATES-011: PersistentCache save/load I/O tests (coverage for cache.rs)
// ============================================================================

/// Test PersistentCache::save() succeeds and creates parent directories
#[test]
fn test_crates_011_persistent_cache_save_succeeds() {
    // save() on an empty cache should succeed (covers save codepath)
    let cache = PersistentCache::default();
    let result = cache.save();
    assert!(result.is_ok());

    // Verify the cache directory was created
    let cache_path = PersistentCache::cache_path();
    assert!(cache_path.parent().unwrap().exists());
}

/// Test PersistentCache::load() does not panic regardless of file state
#[test]
fn test_crates_011_persistent_cache_load_does_not_panic() {
    // load() should always return a valid PersistentCache, never panic
    let cache = PersistentCache::load();
    // Just verify we can access entries without panic
    let _ = cache.entries.len();
}

/// Test PersistentCache save/load roundtrip using serde directly
/// (avoids race conditions from shared global cache file)
#[test]
fn test_crates_011_persistent_cache_serde_roundtrip() {
    // Create cache with entries
    let mut cache = PersistentCache::default();
    for i in 0..3 {
        let response = make_response(&format!("roundtrip-{}", i), &format!("{}.0.0", i + 1));
        cache.insert(format!("roundtrip-{}", i), response, Duration::from_secs(3600));
    }

    // Serialize and deserialize (same as save/load but without file I/O race)
    let json = serde_json::to_string_pretty(&cache).unwrap();
    let loaded: PersistentCache = serde_json::from_str(&json).unwrap();

    // Verify all entries survived
    for i in 0..3 {
        let entry = loaded.get(&format!("roundtrip-{}", i));
        assert!(entry.is_some());
        assert_eq!(entry.unwrap().krate.max_version, format!("{}.0.0", i + 1));
    }
}

/// Test PersistentCache::load() returns default for corrupt JSON
/// (tested via serde deserialization failure behavior)
#[test]
fn test_crates_011_persistent_cache_corrupt_json_behavior() {
    // Verify that serde_json::from_str fails on corrupt JSON
    // (this is the same behavior that load() falls back from)
    let result: Result<PersistentCache, _> = serde_json::from_str("not valid json {{{");
    assert!(result.is_err());

    // load() handles this by returning default
    // Verify default is empty
    let default = PersistentCache::default();
    assert!(default.entries.is_empty());
}

/// Test PersistentCache::cache_path() returns path under home cache dir
#[test]
fn test_crates_011_cache_path_structure() {
    let path = PersistentCache::cache_path();
    let path_str = path.to_string_lossy();
    // Should always end with our known filename
    assert!(
        path_str.ends_with("batuta/crates_io_cache.json"),
        "cache path should end with batuta/crates_io_cache.json, got: {}",
        path_str
    );
}

/// Test PersistentCache::clear_expired() removes only expired entries from disk-backed cache
#[test]
fn test_crates_011_clear_expired_preserves_valid() {
    let mut cache = PersistentCache::default();

    // Insert a valid entry
    let valid = make_response("valid-clear", "1.0.0");
    cache.insert("valid-clear".to_string(), valid, Duration::from_secs(3600));

    // Insert an expired entry (TTL=0)
    let expired = make_response("expired-clear", "0.1.0");
    cache.insert("expired-clear".to_string(), expired, Duration::from_secs(0));

    assert_eq!(cache.entries.len(), 2);

    cache.clear_expired();

    // Valid entry should remain, expired should be gone
    assert_eq!(cache.entries.len(), 1);
    assert!(cache.get("valid-clear").is_some());
    assert!(cache.get("expired-clear").is_none());
}