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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//! HuggingFace Hub API Client
//!
//! Implements HF-QUERY-002 (Hub Search) and HF-QUERY-003 (Asset Metadata)
//!
//! Provides live queries to HuggingFace Hub API:
//! - Model search with filters
//! - Dataset search with filters
//! - Space search with filters
//! - Asset metadata retrieval
//!
//! ## Observability (HF-OBS-001, HF-OBS-002)
//!
//! All Hub operations are instrumented with tracing spans:
//! - `hf.search.models` - Model search operations
//! - `hf.search.datasets` - Dataset search operations
//! - `hf.search.spaces` - Space search operations
//! - `hf.get.model` - Model metadata retrieval
//! - `hf.get.dataset` - Dataset metadata retrieval
//! - `hf.get.space` - Space metadata retrieval

// Allow dead_code for now - these types are tested and will be used
// once live Hub API integration is implemented (HUB-API milestone)
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, Instant};
use tracing::{debug, info, instrument, warn};

// ============================================================================
// HF-QUERY-002: Hub Asset Types
// ============================================================================

/// Type of Hub asset
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HubAssetType {
    Model,
    Dataset,
    Space,
}

impl std::fmt::Display for HubAssetType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Model => write!(f, "model"),
            Self::Dataset => write!(f, "dataset"),
            Self::Space => write!(f, "space"),
        }
    }
}

/// Hub asset metadata (model, dataset, or space)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HubAsset {
    /// Asset ID (e.g., "meta-llama/Llama-2-7b-hf")
    pub id: String,
    /// Asset type
    pub asset_type: HubAssetType,
    /// Author/organization
    pub author: String,
    /// Downloads count
    pub downloads: u64,
    /// Likes count
    pub likes: u64,
    /// Tags
    pub tags: Vec<String>,
    /// Pipeline tag (task) - for models
    pub pipeline_tag: Option<String>,
    /// Library (transformers, diffusers, etc.) - for models
    pub library: Option<String>,
    /// License
    pub license: Option<String>,
    /// Last modified timestamp
    pub last_modified: String,
    /// Model card/README content (optional, fetched separately)
    pub card_content: Option<String>,
}

impl HubAsset {
    pub fn new(id: impl Into<String>, asset_type: HubAssetType) -> Self {
        let id_str = id.into();
        let author = id_str.split('/').next().unwrap_or("unknown").to_string();
        Self {
            id: id_str,
            asset_type,
            author,
            downloads: 0,
            likes: 0,
            tags: Vec::new(),
            pipeline_tag: None,
            library: None,
            license: None,
            last_modified: String::new(),
            card_content: None,
        }
    }

    pub fn with_downloads(mut self, downloads: u64) -> Self {
        self.downloads = downloads;
        self
    }

    pub fn with_likes(mut self, likes: u64) -> Self {
        self.likes = likes;
        self
    }

    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }

    pub fn with_pipeline_tag(mut self, tag: impl Into<String>) -> Self {
        self.pipeline_tag = Some(tag.into());
        self
    }

    pub fn with_library(mut self, library: impl Into<String>) -> Self {
        self.library = Some(library.into());
        self
    }

    pub fn with_license(mut self, license: impl Into<String>) -> Self {
        self.license = Some(license.into());
        self
    }
}

// ============================================================================
// HF-QUERY-002: Search Filters
// ============================================================================

/// Search filters for Hub queries
#[derive(Debug, Clone, Default)]
pub struct SearchFilters {
    /// Filter by task (pipeline_tag)
    pub task: Option<String>,
    /// Filter by library
    pub library: Option<String>,
    /// Filter by author/organization
    pub author: Option<String>,
    /// Filter by license
    pub license: Option<String>,
    /// Minimum downloads threshold
    pub min_downloads: Option<u64>,
    /// Minimum likes threshold
    pub min_likes: Option<u64>,
    /// Search query text
    pub query: Option<String>,
    /// Maximum results to return
    pub limit: usize,
    /// Sort field
    pub sort: Option<String>,
    /// Sort direction (asc/desc)
    pub sort_direction: Option<String>,
}

impl SearchFilters {
    pub fn new() -> Self {
        Self { limit: 20, ..Default::default() }
    }

    pub fn with_task(mut self, task: impl Into<String>) -> Self {
        self.task = Some(task.into());
        self
    }

    pub fn with_library(mut self, library: impl Into<String>) -> Self {
        self.library = Some(library.into());
        self
    }

    pub fn with_author(mut self, author: impl Into<String>) -> Self {
        self.author = Some(author.into());
        self
    }

    pub fn with_license(mut self, license: impl Into<String>) -> Self {
        self.license = Some(license.into());
        self
    }

    pub fn with_min_downloads(mut self, min: u64) -> Self {
        self.min_downloads = Some(min);
        self
    }

    pub fn with_min_likes(mut self, min: u64) -> Self {
        self.min_likes = Some(min);
        self
    }

    pub fn with_query(mut self, query: impl Into<String>) -> Self {
        self.query = Some(query.into());
        self
    }

    pub fn with_limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }

    pub fn with_sort(mut self, field: impl Into<String>, direction: impl Into<String>) -> Self {
        self.sort = Some(field.into());
        self.sort_direction = Some(direction.into());
        self
    }
}

// ============================================================================
// HF-QUERY-002/003: Response Cache
// ============================================================================

/// Cache entry with TTL
#[derive(Debug, Clone)]
struct CacheEntry<T> {
    data: T,
    created: Instant,
    ttl: Duration,
}

impl<T> CacheEntry<T> {
    fn new(data: T, ttl: Duration) -> Self {
        Self { data, created: Instant::now(), ttl }
    }

    fn is_expired(&self) -> bool {
        self.created.elapsed() > self.ttl
    }
}

/// Response cache for Hub queries
#[derive(Debug, Default)]
pub struct ResponseCache {
    search_cache: HashMap<String, CacheEntry<Vec<HubAsset>>>,
    asset_cache: HashMap<String, CacheEntry<HubAsset>>,
    ttl: Duration,
}

impl ResponseCache {
    pub fn new(ttl: Duration) -> Self {
        Self { search_cache: HashMap::new(), asset_cache: HashMap::new(), ttl }
    }

    /// Default cache with 15 minute TTL
    pub fn default_ttl() -> Self {
        Self::new(Duration::from_secs(15 * 60))
    }

    /// Cache a search result
    pub fn cache_search(&mut self, key: &str, results: Vec<HubAsset>) {
        self.search_cache.insert(key.to_string(), CacheEntry::new(results, self.ttl));
    }

    /// Get cached search result
    pub fn get_search(&self, key: &str) -> Option<&Vec<HubAsset>> {
        self.search_cache.get(key).and_then(|entry| {
            if entry.is_expired() {
                None
            } else {
                Some(&entry.data)
            }
        })
    }

    /// Cache an asset
    pub fn cache_asset(&mut self, id: &str, asset: HubAsset) {
        self.asset_cache.insert(id.to_string(), CacheEntry::new(asset, self.ttl));
    }

    /// Get cached asset
    pub fn get_asset(&self, id: &str) -> Option<&HubAsset> {
        self.asset_cache.get(id).and_then(
            |entry| {
                if entry.is_expired() {
                    None
                } else {
                    Some(&entry.data)
                }
            },
        )
    }

    /// Clear expired entries
    pub fn clear_expired(&mut self) {
        self.search_cache.retain(|_, entry| !entry.is_expired());
        self.asset_cache.retain(|_, entry| !entry.is_expired());
    }

    /// Clear all cache
    pub fn clear(&mut self) {
        self.search_cache.clear();
        self.asset_cache.clear();
    }

    /// Get cache statistics
    pub fn stats(&self) -> CacheStats {
        CacheStats {
            search_entries: self.search_cache.len(),
            asset_entries: self.asset_cache.len(),
            ttl_secs: self.ttl.as_secs(),
        }
    }
}

/// Cache statistics
#[derive(Debug, Clone, Serialize)]
pub struct CacheStats {
    pub search_entries: usize,
    pub asset_entries: usize,
    pub ttl_secs: u64,
}

// ============================================================================
// HF-QUERY-002/003: Hub Client
// ============================================================================

/// HuggingFace Hub API client
#[derive(Debug)]
pub struct HubClient {
    base_url: String,
    cache: ResponseCache,
    offline_mode: bool,
}

impl HubClient {
    /// Create new client with default settings
    pub fn new() -> Self {
        Self {
            base_url: "https://huggingface.co/api".to_string(),
            cache: ResponseCache::default_ttl(),
            offline_mode: false,
        }
    }

    /// Create client with custom base URL (for testing)
    pub fn with_base_url(base_url: impl Into<String>) -> Self {
        Self { base_url: base_url.into(), cache: ResponseCache::default_ttl(), offline_mode: false }
    }

    /// Enable offline mode (only return cached data)
    pub fn offline(mut self) -> Self {
        self.offline_mode = true;
        self
    }

    /// Get cache statistics
    pub fn cache_stats(&self) -> CacheStats {
        self.cache.stats()
    }

    /// Clear cache
    pub fn clear_cache(&mut self) {
        self.cache.clear();
    }

    // ========================================================================
    // HF-QUERY-002: Search Methods (HF-OBS-001: Instrumented with tracing)
    // ========================================================================

    /// Search models on HuggingFace Hub
    #[instrument(name = "hf.search.models", skip(self), fields(
        task = filters.task.as_deref(),
        limit = filters.limit,
        cache_hit = tracing::field::Empty,
        result_count = tracing::field::Empty
    ))]
    pub fn search_models(&mut self, filters: &SearchFilters) -> Result<Vec<HubAsset>, HubError> {
        let cache_key = format!("models:{:?}", filters);

        // Check cache first
        if let Some(cached) = self.cache.get_search(&cache_key) {
            debug!(cache_hit = true, "Model search cache hit");
            tracing::Span::current().record("cache_hit", true);
            tracing::Span::current().record("result_count", cached.len());
            return Ok(cached.clone());
        }

        if self.offline_mode {
            warn!("Model search attempted in offline mode");
            return Err(HubError::OfflineMode);
        }

        // In a real implementation, this would make an HTTP request
        // For now, return mock data for testing
        let results = self.mock_model_search(filters);
        self.cache.cache_search(&cache_key, results.clone());
        info!(result_count = results.len(), "Model search completed");
        tracing::Span::current().record("cache_hit", false);
        tracing::Span::current().record("result_count", results.len());
        Ok(results)
    }

    /// Search datasets on HuggingFace Hub
    #[instrument(name = "hf.search.datasets", skip(self), fields(
        limit = filters.limit,
        cache_hit = tracing::field::Empty,
        result_count = tracing::field::Empty
    ))]
    pub fn search_datasets(&mut self, filters: &SearchFilters) -> Result<Vec<HubAsset>, HubError> {
        let cache_key = format!("datasets:{:?}", filters);

        if let Some(cached) = self.cache.get_search(&cache_key) {
            debug!(cache_hit = true, "Dataset search cache hit");
            tracing::Span::current().record("cache_hit", true);
            tracing::Span::current().record("result_count", cached.len());
            return Ok(cached.clone());
        }

        if self.offline_mode {
            warn!("Dataset search attempted in offline mode");
            return Err(HubError::OfflineMode);
        }

        let results = self.mock_dataset_search(filters);
        self.cache.cache_search(&cache_key, results.clone());
        info!(result_count = results.len(), "Dataset search completed");
        tracing::Span::current().record("cache_hit", false);
        tracing::Span::current().record("result_count", results.len());
        Ok(results)
    }

    /// Search spaces on HuggingFace Hub
    #[instrument(name = "hf.search.spaces", skip(self), fields(
        limit = filters.limit,
        cache_hit = tracing::field::Empty,
        result_count = tracing::field::Empty
    ))]
    pub fn search_spaces(&mut self, filters: &SearchFilters) -> Result<Vec<HubAsset>, HubError> {
        let cache_key = format!("spaces:{:?}", filters);

        if let Some(cached) = self.cache.get_search(&cache_key) {
            debug!(cache_hit = true, "Space search cache hit");
            tracing::Span::current().record("cache_hit", true);
            tracing::Span::current().record("result_count", cached.len());
            return Ok(cached.clone());
        }

        if self.offline_mode {
            warn!("Space search attempted in offline mode");
            return Err(HubError::OfflineMode);
        }

        let results = self.mock_space_search(filters);
        self.cache.cache_search(&cache_key, results.clone());
        info!(result_count = results.len(), "Space search completed");
        tracing::Span::current().record("cache_hit", false);
        tracing::Span::current().record("result_count", results.len());
        Ok(results)
    }

    // ========================================================================
    // HF-QUERY-003: Asset Metadata Methods (HF-OBS-002: Instrumented with tracing)
    // ========================================================================

    /// Get model metadata
    #[instrument(name = "hf.get.model", skip(self), fields(
        asset_id = id,
        cache_hit = tracing::field::Empty
    ))]
    pub fn get_model(&mut self, id: &str) -> Result<HubAsset, HubError> {
        let cache_key = format!("model:{}", id);

        if let Some(cached) = self.cache.get_asset(&cache_key) {
            debug!(cache_hit = true, "Model metadata cache hit");
            tracing::Span::current().record("cache_hit", true);
            return Ok(cached.clone());
        }

        if self.offline_mode {
            warn!(asset_id = id, "Model get attempted in offline mode");
            return Err(HubError::OfflineMode);
        }

        let asset = self.mock_get_model(id)?;
        self.cache.cache_asset(&cache_key, asset.clone());
        info!(asset_id = id, "Model metadata retrieved");
        tracing::Span::current().record("cache_hit", false);
        Ok(asset)
    }

    /// Get dataset metadata
    #[instrument(name = "hf.get.dataset", skip(self), fields(
        asset_id = id,
        cache_hit = tracing::field::Empty
    ))]
    pub fn get_dataset(&mut self, id: &str) -> Result<HubAsset, HubError> {
        let cache_key = format!("dataset:{}", id);

        if let Some(cached) = self.cache.get_asset(&cache_key) {
            debug!(cache_hit = true, "Dataset metadata cache hit");
            tracing::Span::current().record("cache_hit", true);
            return Ok(cached.clone());
        }

        if self.offline_mode {
            warn!(asset_id = id, "Dataset get attempted in offline mode");
            return Err(HubError::OfflineMode);
        }

        let asset = self.mock_get_dataset(id)?;
        self.cache.cache_asset(&cache_key, asset.clone());
        info!(asset_id = id, "Dataset metadata retrieved");
        tracing::Span::current().record("cache_hit", false);
        Ok(asset)
    }

    /// Get space metadata
    #[instrument(name = "hf.get.space", skip(self), fields(
        asset_id = id,
        cache_hit = tracing::field::Empty
    ))]
    pub fn get_space(&mut self, id: &str) -> Result<HubAsset, HubError> {
        let cache_key = format!("space:{}", id);

        if let Some(cached) = self.cache.get_asset(&cache_key) {
            debug!(cache_hit = true, "Space metadata cache hit");
            tracing::Span::current().record("cache_hit", true);
            return Ok(cached.clone());
        }

        if self.offline_mode {
            warn!(asset_id = id, "Space get attempted in offline mode");
            return Err(HubError::OfflineMode);
        }

        let asset = self.mock_get_space(id)?;
        self.cache.cache_asset(&cache_key, asset.clone());
        info!(asset_id = id, "Space metadata retrieved");
        tracing::Span::current().record("cache_hit", false);
        Ok(asset)
    }

    // ========================================================================
    // Mock implementations (replace with real API calls)
    // ========================================================================

    fn mock_model_search(&self, filters: &SearchFilters) -> Vec<HubAsset> {
        let mut results = vec![
            HubAsset::new("meta-llama/Llama-2-7b-hf", HubAssetType::Model)
                .with_downloads(5_000_000)
                .with_likes(10_000)
                .with_pipeline_tag("text-generation")
                .with_library("transformers")
                .with_license("llama2"),
            HubAsset::new("openai/whisper-large-v3", HubAssetType::Model)
                .with_downloads(2_000_000)
                .with_likes(5_000)
                .with_pipeline_tag("automatic-speech-recognition")
                .with_library("transformers")
                .with_license("apache-2.0"),
            HubAsset::new("stabilityai/stable-diffusion-xl-base-1.0", HubAssetType::Model)
                .with_downloads(3_000_000)
                .with_likes(8_000)
                .with_pipeline_tag("text-to-image")
                .with_library("diffusers")
                .with_license("openrail++"),
            HubAsset::new("sentence-transformers/all-MiniLM-L6-v2", HubAssetType::Model)
                .with_downloads(10_000_000)
                .with_likes(2_000)
                .with_pipeline_tag("sentence-similarity")
                .with_library("sentence-transformers")
                .with_license("apache-2.0"),
            HubAsset::new("bert-base-uncased", HubAssetType::Model)
                .with_downloads(50_000_000)
                .with_likes(15_000)
                .with_pipeline_tag("fill-mask")
                .with_library("transformers")
                .with_license("apache-2.0"),
        ];

        // Apply filters
        if let Some(ref task) = filters.task {
            results.retain(|m| m.pipeline_tag.as_ref().is_some_and(|t| t == task));
        }
        if let Some(ref library) = filters.library {
            results.retain(|m| m.library.as_ref().is_some_and(|l| l == library));
        }
        if let Some(min) = filters.min_downloads {
            results.retain(|m| m.downloads >= min);
        }
        if let Some(min) = filters.min_likes {
            results.retain(|m| m.likes >= min);
        }

        results.truncate(filters.limit);
        results
    }

    fn mock_dataset_search(&self, filters: &SearchFilters) -> Vec<HubAsset> {
        let mut results = vec![
            HubAsset::new("squad", HubAssetType::Dataset)
                .with_downloads(5_000_000)
                .with_likes(1_000)
                .with_tags(vec!["question-answering".into(), "english".into()]),
            HubAsset::new("imdb", HubAssetType::Dataset)
                .with_downloads(3_000_000)
                .with_likes(500)
                .with_tags(vec!["text-classification".into(), "sentiment".into()]),
            HubAsset::new("wikipedia", HubAssetType::Dataset)
                .with_downloads(10_000_000)
                .with_likes(2_000)
                .with_tags(vec!["text".into(), "multilingual".into()]),
        ];

        if let Some(min) = filters.min_downloads {
            results.retain(|d| d.downloads >= min);
        }

        results.truncate(filters.limit);
        results
    }

    fn mock_space_search(&self, filters: &SearchFilters) -> Vec<HubAsset> {
        let mut results = vec![
            HubAsset::new("gradio/chatbot", HubAssetType::Space)
                .with_downloads(100_000)
                .with_likes(500)
                .with_tags(vec!["gradio".into(), "chat".into()]),
            HubAsset::new("stabilityai/stable-diffusion", HubAssetType::Space)
                .with_downloads(500_000)
                .with_likes(2_000)
                .with_tags(vec!["gradio".into(), "image-generation".into()]),
        ];

        if let Some(min) = filters.min_downloads {
            results.retain(|s| s.downloads >= min);
        }

        results.truncate(filters.limit);
        results
    }

    fn mock_get_model(&self, id: &str) -> Result<HubAsset, HubError> {
        // Return mock data for known models
        match id {
            "meta-llama/Llama-2-7b-hf" => Ok(HubAsset::new(id, HubAssetType::Model)
                .with_downloads(5_000_000)
                .with_likes(10_000)
                .with_pipeline_tag("text-generation")
                .with_library("transformers")
                .with_license("llama2")),
            "bert-base-uncased" => Ok(HubAsset::new(id, HubAssetType::Model)
                .with_downloads(50_000_000)
                .with_likes(15_000)
                .with_pipeline_tag("fill-mask")
                .with_library("transformers")
                .with_license("apache-2.0")),
            _ => Err(HubError::NotFound(id.to_string())),
        }
    }

    fn mock_get_dataset(&self, id: &str) -> Result<HubAsset, HubError> {
        match id {
            "squad" => Ok(HubAsset::new(id, HubAssetType::Dataset)
                .with_downloads(5_000_000)
                .with_likes(1_000)
                .with_tags(vec!["question-answering".into()])),
            _ => Err(HubError::NotFound(id.to_string())),
        }
    }

    fn mock_get_space(&self, id: &str) -> Result<HubAsset, HubError> {
        match id {
            "gradio/chatbot" => Ok(HubAsset::new(id, HubAssetType::Space)
                .with_downloads(100_000)
                .with_likes(500)
                .with_tags(vec!["gradio".into(), "chat".into()])),
            _ => Err(HubError::NotFound(id.to_string())),
        }
    }
}

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

// ============================================================================
// Error Types
// ============================================================================

/// Hub API error
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HubError {
    /// Asset not found
    NotFound(String),
    /// Rate limited
    RateLimited { retry_after: Option<u64> },
    /// Network error
    NetworkError(String),
    /// Offline mode - no cached data available
    OfflineMode,
    /// Invalid response from API
    InvalidResponse(String),
}

impl std::fmt::Display for HubError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotFound(id) => write!(f, "Asset not found: {}", id),
            Self::RateLimited { retry_after } => {
                if let Some(secs) = retry_after {
                    write!(f, "Rate limited, retry after {} seconds", secs)
                } else {
                    write!(f, "Rate limited")
                }
            }
            Self::NetworkError(msg) => write!(f, "Network error: {}", msg),
            Self::OfflineMode => write!(f, "Offline mode: no cached data available"),
            Self::InvalidResponse(msg) => write!(f, "Invalid response: {}", msg),
        }
    }
}

impl std::error::Error for HubError {}

// ============================================================================
// Tests - Extreme TDD
// ============================================================================

#[cfg(test)]
#[allow(non_snake_case)]
#[path = "hub_client_tests.rs"]
mod tests;