argentor-gateway 1.2.0

Axum-based HTTP gateway, REST API, and WebSocket server for Argentor
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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! REST API endpoints for the skill marketplace.
//!
//! Provides HTTP endpoints for searching, browsing, installing, and uninstalling
//! skills from the [`MarketplaceManager`]. All endpoints are mounted under
//! `/api/v1/marketplace/` and return JSON responses.
//!
//! # Endpoints
//!
//! | Method   | Path                                | Description              |
//! |----------|-------------------------------------|--------------------------|
//! | `GET`    | `/api/v1/marketplace/search`        | Search catalog           |
//! | `GET`    | `/api/v1/marketplace/featured`      | List featured skills     |
//! | `GET`    | `/api/v1/marketplace/categories`    | List categories          |
//! | `GET`    | `/api/v1/marketplace/skills/:name`  | Get skill details        |
//! | `GET`    | `/api/v1/marketplace/popular`       | Top by downloads         |
//! | `GET`    | `/api/v1/marketplace/recent`        | Recently updated         |
//! | `POST`   | `/api/v1/marketplace/install/:name` | Install a skill          |
//! | `DELETE` | `/api/v1/marketplace/install/:name` | Uninstall a skill        |
//! | `GET`    | `/api/v1/marketplace/installed`     | List installed skills    |
//! | `GET`    | `/api/v1/marketplace/stats`         | Catalog statistics       |

use argentor_skills::{MarketplaceEntry, MarketplaceManager, MarketplaceSearch, SortBy};
use axum::{
    extract::{Json, Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
    routing::{delete, get, post},
    Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{info, warn};

// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------

/// Shared state for the marketplace API endpoints.
pub struct MarketplaceApiState {
    /// The marketplace manager, behind a read-write lock for concurrent access.
    pub manager: RwLock<MarketplaceManager>,
}

// ---------------------------------------------------------------------------
// Query / response types
// ---------------------------------------------------------------------------

/// Query parameters for the search endpoint.
#[derive(Debug, Deserialize)]
pub struct SearchQuery {
    /// Free-text search query.
    pub q: Option<String>,
    /// Filter by category.
    pub category: Option<String>,
    /// Sort order: "relevance", "downloads", "rating", "recent", "name".
    pub sort: Option<String>,
    /// Maximum number of results (default: 50).
    pub limit: Option<usize>,
    /// Number of results to skip (default: 0).
    pub offset: Option<usize>,
}

/// Query parameters for the popular endpoint.
#[derive(Debug, Deserialize)]
pub struct PopularQuery {
    /// Maximum number of results (default: 10).
    pub limit: Option<usize>,
}

/// Query parameters for the recent endpoint.
#[derive(Debug, Deserialize)]
pub struct RecentQuery {
    /// Maximum number of results (default: 10).
    pub limit: Option<usize>,
}

/// JSON-serializable view of a marketplace entry (avoids borrow issues).
#[derive(Debug, Serialize, Deserialize)]
pub struct MarketplaceEntryResponse {
    /// Unique skill name.
    pub name: String,
    /// Semantic version string.
    pub version: String,
    /// Human-readable description.
    pub description: String,
    /// Author name or organization.
    pub author: String,
    /// SPDX license identifier.
    pub license: Option<String>,
    /// Total download count.
    pub downloads: u64,
    /// Average rating (0.0 -- 5.0).
    pub rating: f32,
    /// Number of individual ratings.
    pub ratings_count: u32,
    /// High-level categories.
    pub categories: Vec<String>,
    /// Whether this entry is editorially featured.
    pub featured: bool,
    /// RFC 3339 timestamp of initial publication.
    pub published_at: String,
    /// RFC 3339 timestamp of most recent update.
    pub updated_at: String,
    /// WASM binary size in bytes.
    pub size_bytes: u64,
    /// URL to download the WASM binary.
    pub download_url: Option<String>,
    /// Homepage or documentation URL.
    pub homepage: Option<String>,
    /// Free-form keywords for discoverability.
    pub keywords: Vec<String>,
    /// Tags from the skill manifest.
    pub tags: Vec<String>,
}

impl From<&MarketplaceEntry> for MarketplaceEntryResponse {
    fn from(e: &MarketplaceEntry) -> Self {
        Self {
            name: e.manifest.name.clone(),
            version: e.manifest.version.clone(),
            description: e.manifest.description.clone(),
            author: e.manifest.author.clone(),
            license: e.manifest.license.clone(),
            downloads: e.downloads,
            rating: e.rating,
            ratings_count: e.ratings_count,
            categories: e.categories.clone(),
            featured: e.featured,
            published_at: e.published_at.clone(),
            updated_at: e.updated_at.clone(),
            size_bytes: e.size_bytes,
            download_url: e.download_url.clone(),
            homepage: e.homepage.clone(),
            keywords: e.keywords.clone(),
            tags: e.manifest.tags.clone(),
        }
    }
}

/// Response for the installed skills list.
#[derive(Debug, Serialize, Deserialize)]
pub struct InstalledSkillResponse {
    /// Skill name.
    pub name: String,
    /// Installed version string.
    pub version: String,
    /// RFC 3339 timestamp when the skill was installed.
    pub installed_at: String,
    /// Whether this skill passed the vetting pipeline.
    pub vetted: bool,
}

/// Response for the install endpoint.
#[derive(Debug, Serialize, Deserialize)]
pub struct InstallResponse {
    /// Whether the installation succeeded.
    pub success: bool,
    /// Name of the skill.
    pub name: String,
    /// Human-readable status message.
    pub message: String,
}

/// Response for the uninstall endpoint.
#[derive(Debug, Serialize, Deserialize)]
pub struct UninstallResponse {
    /// Whether the uninstall succeeded.
    pub success: bool,
    /// Name of the skill.
    pub name: String,
    /// Human-readable status message.
    pub message: String,
}

/// Catalog statistics response.
#[derive(Debug, Serialize, Deserialize)]
pub struct CatalogStats {
    /// Total number of skills in the catalog.
    pub total_skills: usize,
    /// Number of unique categories.
    pub total_categories: usize,
    /// Number of locally installed skills.
    pub total_installed: usize,
    /// Number of featured skills.
    pub featured_count: usize,
    /// List of all category names.
    pub categories: Vec<String>,
}

/// Unified error type for marketplace API handlers.
#[derive(Debug)]
pub enum MarketplaceApiError {
    /// The requested resource was not found.
    NotFound(String),
    /// The request was malformed.
    BadRequest(String),
    /// An internal server error occurred.
    Internal(String),
}

impl std::fmt::Display for MarketplaceApiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotFound(msg) => write!(f, "Not found: {msg}"),
            Self::BadRequest(msg) => write!(f, "Bad request: {msg}"),
            Self::Internal(msg) => write!(f, "Internal error: {msg}"),
        }
    }
}

impl IntoResponse for MarketplaceApiError {
    fn into_response(self) -> axum::response::Response {
        let (status, message) = match &self {
            Self::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()),
            Self::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
            Self::Internal(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
        };
        let body = serde_json::json!({ "error": message });
        (status, Json(body)).into_response()
    }
}

// ---------------------------------------------------------------------------
// Router
// ---------------------------------------------------------------------------

/// Build the marketplace API sub-router.
///
/// All routes are nested under `/api/v1/marketplace/` and return JSON responses.
pub fn marketplace_router(state: Arc<MarketplaceApiState>) -> Router {
    Router::new()
        .route("/api/v1/marketplace/search", get(search_catalog))
        .route("/api/v1/marketplace/featured", get(list_featured))
        .route("/api/v1/marketplace/categories", get(list_categories))
        .route("/api/v1/marketplace/skills/{name}", get(get_skill_details))
        .route("/api/v1/marketplace/popular", get(list_popular))
        .route("/api/v1/marketplace/recent", get(list_recent))
        .route("/api/v1/marketplace/install/{name}", post(install_skill))
        .route(
            "/api/v1/marketplace/install/{name}",
            delete(uninstall_skill),
        )
        .route("/api/v1/marketplace/installed", get(list_installed))
        .route("/api/v1/marketplace/stats", get(get_stats))
        .with_state(state)
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn parse_sort(s: &str) -> SortBy {
    match s.to_lowercase().as_str() {
        "downloads" => SortBy::Downloads,
        "rating" => SortBy::Rating,
        "recent" => SortBy::Recent,
        "name" => SortBy::Name,
        _ => SortBy::Relevance,
    }
}

// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------

/// `GET /api/v1/marketplace/search?q=&category=&sort=&limit=&offset=`
async fn search_catalog(
    State(state): State<Arc<MarketplaceApiState>>,
    Query(params): Query<SearchQuery>,
) -> Result<Json<Vec<MarketplaceEntryResponse>>, MarketplaceApiError> {
    let mgr = state.manager.read().await;
    let search = MarketplaceSearch {
        query: params.q,
        category: params.category,
        author: None,
        min_rating: None,
        tags: Vec::new(),
        sort_by: params
            .sort
            .as_deref()
            .map(parse_sort)
            .unwrap_or(SortBy::Relevance),
        limit: params.limit.unwrap_or(50),
        offset: params.offset.unwrap_or(0),
    };

    let results = mgr.catalog().search(&search);
    let response: Vec<MarketplaceEntryResponse> = results
        .iter()
        .map(|e| MarketplaceEntryResponse::from(*e))
        .collect();
    Ok(Json(response))
}

/// `GET /api/v1/marketplace/featured`
async fn list_featured(
    State(state): State<Arc<MarketplaceApiState>>,
) -> Result<Json<Vec<MarketplaceEntryResponse>>, MarketplaceApiError> {
    let mgr = state.manager.read().await;
    let featured = mgr.catalog().list_featured();
    let response: Vec<MarketplaceEntryResponse> = featured
        .iter()
        .map(|e| MarketplaceEntryResponse::from(*e))
        .collect();
    Ok(Json(response))
}

/// `GET /api/v1/marketplace/categories`
async fn list_categories(
    State(state): State<Arc<MarketplaceApiState>>,
) -> Result<Json<Vec<String>>, MarketplaceApiError> {
    let mgr = state.manager.read().await;
    Ok(Json(mgr.catalog().categories()))
}

/// `GET /api/v1/marketplace/skills/:name`
async fn get_skill_details(
    State(state): State<Arc<MarketplaceApiState>>,
    Path(name): Path<String>,
) -> Result<Json<MarketplaceEntryResponse>, MarketplaceApiError> {
    let mgr = state.manager.read().await;
    let entry = mgr.catalog().get(&name).ok_or_else(|| {
        MarketplaceApiError::NotFound(format!("Skill '{name}' not found in catalog"))
    })?;
    Ok(Json(MarketplaceEntryResponse::from(entry)))
}

/// `GET /api/v1/marketplace/popular?limit=`
async fn list_popular(
    State(state): State<Arc<MarketplaceApiState>>,
    Query(params): Query<PopularQuery>,
) -> Result<Json<Vec<MarketplaceEntryResponse>>, MarketplaceApiError> {
    let mgr = state.manager.read().await;
    let limit = params.limit.unwrap_or(10);
    let popular = mgr.catalog().list_popular(limit);
    let response: Vec<MarketplaceEntryResponse> = popular
        .iter()
        .map(|e| MarketplaceEntryResponse::from(*e))
        .collect();
    Ok(Json(response))
}

/// `GET /api/v1/marketplace/recent?limit=`
async fn list_recent(
    State(state): State<Arc<MarketplaceApiState>>,
    Query(params): Query<RecentQuery>,
) -> Result<Json<Vec<MarketplaceEntryResponse>>, MarketplaceApiError> {
    let mgr = state.manager.read().await;
    let limit = params.limit.unwrap_or(10);
    let recent = mgr.catalog().list_recent(limit);
    let response: Vec<MarketplaceEntryResponse> = recent
        .iter()
        .map(|e| MarketplaceEntryResponse::from(*e))
        .collect();
    Ok(Json(response))
}

/// `POST /api/v1/marketplace/install/:name`
///
/// Looks up the skill in the catalog, creates a minimal manifest from catalog data,
/// and runs the install pipeline (vetting + installation) with placeholder WASM bytes.
async fn install_skill(
    State(state): State<Arc<MarketplaceApiState>>,
    Path(name): Path<String>,
) -> Result<Json<InstallResponse>, MarketplaceApiError> {
    let mut mgr = state.manager.write().await;

    // Verify the skill exists in catalog
    let entry = mgr.catalog().get(&name).ok_or_else(|| {
        MarketplaceApiError::NotFound(format!("Skill '{name}' not found in catalog"))
    })?;

    // Check if already installed
    if mgr.is_installed(&name) {
        return Ok(Json(InstallResponse {
            success: false,
            name: name.clone(),
            message: format!("Skill '{name}' is already installed"),
        }));
    }

    let manifest = entry.manifest.clone();

    // Install with placeholder bytes (in real deployment these would be fetched)
    let placeholder_wasm = b"(module)";
    match mgr.install_from_bytes(manifest, placeholder_wasm) {
        Ok(result) => {
            info!(skill = %name, "Skill installed via marketplace API");
            Ok(Json(InstallResponse {
                success: result.passed,
                name: name.clone(),
                message: if result.passed {
                    format!("Skill '{name}' installed successfully")
                } else {
                    format!(
                        "Skill '{name}' installation failed vetting: {}",
                        result
                            .checks
                            .iter()
                            .filter(|c| !c.passed)
                            .map(|c| c.message.clone())
                            .collect::<Vec<_>>()
                            .join(", ")
                    )
                },
            }))
        }
        Err(e) => {
            warn!(skill = %name, error = %e, "Skill installation failed");
            Err(MarketplaceApiError::Internal(format!(
                "Failed to install skill '{name}': {e}"
            )))
        }
    }
}

/// `DELETE /api/v1/marketplace/install/:name`
async fn uninstall_skill(
    State(state): State<Arc<MarketplaceApiState>>,
    Path(name): Path<String>,
) -> Result<Json<UninstallResponse>, MarketplaceApiError> {
    let mut mgr = state.manager.write().await;

    if !mgr.is_installed(&name) {
        return Err(MarketplaceApiError::NotFound(format!(
            "Skill '{name}' is not installed"
        )));
    }

    match mgr.uninstall(&name) {
        Ok(removed) => {
            info!(skill = %name, removed, "Skill uninstalled via marketplace API");
            Ok(Json(UninstallResponse {
                success: removed,
                name: name.clone(),
                message: if removed {
                    format!("Skill '{name}' uninstalled successfully")
                } else {
                    format!("Skill '{name}' was not found in the index")
                },
            }))
        }
        Err(e) => {
            warn!(skill = %name, error = %e, "Skill uninstall failed");
            Err(MarketplaceApiError::Internal(format!(
                "Failed to uninstall skill '{name}': {e}"
            )))
        }
    }
}

/// `GET /api/v1/marketplace/installed`
async fn list_installed(
    State(state): State<Arc<MarketplaceApiState>>,
) -> Result<Json<Vec<InstalledSkillResponse>>, MarketplaceApiError> {
    let mgr = state.manager.read().await;
    let installed: Vec<InstalledSkillResponse> = mgr
        .installed()
        .list()
        .iter()
        .map(|entry| InstalledSkillResponse {
            name: entry.manifest.name.clone(),
            version: entry.manifest.version.clone(),
            installed_at: entry.installed_at.clone(),
            vetted: entry.vetted,
        })
        .collect();
    Ok(Json(installed))
}

/// `GET /api/v1/marketplace/stats`
async fn get_stats(
    State(state): State<Arc<MarketplaceApiState>>,
) -> Result<Json<CatalogStats>, MarketplaceApiError> {
    let mgr = state.manager.read().await;
    let catalog = mgr.catalog();
    let categories = catalog.categories();
    let featured_count = catalog.list_featured().len();
    let total = catalog.count();
    let installed = mgr.installed().list().len();

    Ok(Json(CatalogStats {
        total_skills: total,
        total_categories: categories.len(),
        total_installed: installed,
        featured_count,
        categories,
    }))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use argentor_skills::{builtin_catalog_entries, MarketplaceManager};
    use axum::body::Body;
    use axum::http::Request;
    use tower::ServiceExt;

    /// Create a test state with the built-in catalog entries loaded.
    fn test_state() -> Arc<MarketplaceApiState> {
        let dir = std::env::temp_dir().join("argentor_marketplace_api_test");
        let _ = std::fs::create_dir_all(&dir);
        let catalog_path = dir.join("catalog.json");
        let mut mgr = MarketplaceManager::new(dir, catalog_path);
        let entries = builtin_catalog_entries();
        mgr.update_catalog(entries);
        Arc::new(MarketplaceApiState {
            manager: RwLock::new(mgr),
        })
    }

    fn app(state: Arc<MarketplaceApiState>) -> Router {
        marketplace_router(state)
    }

    // -- Test: search returns results --

    #[tokio::test]
    async fn test_search_returns_results() {
        let state = test_state();
        let router = app(state);

        let resp = router
            .oneshot(
                Request::builder()
                    .uri("/api/v1/marketplace/search?q=calculator")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let results: Vec<MarketplaceEntryResponse> = serde_json::from_slice(&body).unwrap();
        assert!(!results.is_empty());
        assert!(results.iter().any(|r| r.name.contains("calculator")));
    }

    // -- Test: search with no query returns all --

    #[tokio::test]
    async fn test_search_no_query_returns_all() {
        let state = test_state();
        let router = app(state);

        let resp = router
            .oneshot(
                Request::builder()
                    .uri("/api/v1/marketplace/search")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let results: Vec<MarketplaceEntryResponse> = serde_json::from_slice(&body).unwrap();
        assert!(results.len() > 1);
    }

    // -- Test: category listing --

    #[tokio::test]
    async fn test_category_listing() {
        let state = test_state();
        let router = app(state);

        let resp = router
            .oneshot(
                Request::builder()
                    .uri("/api/v1/marketplace/categories")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let categories: Vec<String> = serde_json::from_slice(&body).unwrap();
        assert!(!categories.is_empty());
    }

    // -- Test: featured listing --

    #[tokio::test]
    async fn test_featured_listing() {
        let state = test_state();
        let router = app(state);

        let resp = router
            .oneshot(
                Request::builder()
                    .uri("/api/v1/marketplace/featured")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let featured: Vec<MarketplaceEntryResponse> = serde_json::from_slice(&body).unwrap();
        // All returned entries should be featured
        for entry in &featured {
            assert!(entry.featured);
        }
    }

    // -- Test: skill details found --

    #[tokio::test]
    async fn test_skill_details_found() {
        let state = test_state();
        let router = app(state);

        let resp = router
            .oneshot(
                Request::builder()
                    .uri("/api/v1/marketplace/skills/calculator")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let detail: MarketplaceEntryResponse = serde_json::from_slice(&body).unwrap();
        assert_eq!(detail.name, "calculator");
    }

    // -- Test: skill details not found --

    #[tokio::test]
    async fn test_skill_details_not_found() {
        let state = test_state();
        let router = app(state);

        let resp = router
            .oneshot(
                Request::builder()
                    .uri("/api/v1/marketplace/skills/nonexistent_skill_xyz")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    // -- Test: popular listing --

    #[tokio::test]
    async fn test_popular_listing() {
        let state = test_state();
        let router = app(state);

        let resp = router
            .oneshot(
                Request::builder()
                    .uri("/api/v1/marketplace/popular?limit=5")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let popular: Vec<MarketplaceEntryResponse> = serde_json::from_slice(&body).unwrap();
        assert!(popular.len() <= 5);
        // Verify sorted by downloads descending
        for w in popular.windows(2) {
            assert!(w[0].downloads >= w[1].downloads);
        }
    }

    // -- Test: recent listing --

    #[tokio::test]
    async fn test_recent_listing() {
        let state = test_state();
        let router = app(state);

        let resp = router
            .oneshot(
                Request::builder()
                    .uri("/api/v1/marketplace/recent?limit=5")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let recent: Vec<MarketplaceEntryResponse> = serde_json::from_slice(&body).unwrap();
        assert!(recent.len() <= 5);
    }

    // -- Test: installed listing (initially empty) --

    #[tokio::test]
    async fn test_installed_listing_empty() {
        let state = test_state();
        let router = app(state);

        let resp = router
            .oneshot(
                Request::builder()
                    .uri("/api/v1/marketplace/installed")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let installed: Vec<InstalledSkillResponse> = serde_json::from_slice(&body).unwrap();
        assert!(installed.is_empty());
    }

    // -- Test: stats endpoint --

    #[tokio::test]
    async fn test_stats_endpoint() {
        let state = test_state();
        let router = app(state);

        let resp = router
            .oneshot(
                Request::builder()
                    .uri("/api/v1/marketplace/stats")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let stats: CatalogStats = serde_json::from_slice(&body).unwrap();
        assert!(stats.total_skills > 0);
        assert!(stats.total_categories > 0);
        assert_eq!(stats.total_installed, 0);
    }

    // -- Test: uninstall nonexistent returns 404 --

    #[tokio::test]
    async fn test_uninstall_nonexistent() {
        let state = test_state();
        let router = app(state);

        let resp = router
            .oneshot(
                Request::builder()
                    .method("DELETE")
                    .uri("/api/v1/marketplace/install/nonexistent_skill")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    // -- Test: install nonexistent skill returns 404 --

    #[tokio::test]
    async fn test_install_nonexistent_skill() {
        let state = test_state();
        let router = app(state);

        let resp = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/api/v1/marketplace/install/nonexistent_skill_xyz")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    // -- Test: search with category filter --

    #[tokio::test]
    async fn test_search_with_category_filter() {
        let state = test_state();
        let router = app(state);

        let resp = router
            .oneshot(
                Request::builder()
                    .uri("/api/v1/marketplace/search?category=data")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let results: Vec<MarketplaceEntryResponse> = serde_json::from_slice(&body).unwrap();
        // All returned results should have the "data" category
        for r in &results {
            assert!(
                r.categories.iter().any(|c| c.to_lowercase() == "data"),
                "Entry '{}' does not have 'data' category: {:?}",
                r.name,
                r.categories
            );
        }
    }
}