skillfile-sources 1.5.0

Source fetching and caching for skillfile: resolver, strategies, sync
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
//! agentskill.sh registry implementation.

use serde::Deserialize;

use crate::http::HttpClient;
use skillfile_core::error::SkillfileError;

use super::scrape::urlencoded;
use super::{Registry, RegistryId, SearchQuery, SearchResponse, SearchResult};

const AGENTSKILL_API: &str = "https://agentskill.sh/api/agent/search";

/// The agentskill.sh registry (110K+ skills, public, no auth).
pub struct AgentskillSh;

#[derive(Deserialize)]
struct ApiResponse {
    results: Vec<ApiResult>,
    total: Option<usize>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ApiResult {
    slug: Option<String>,
    name: Option<String>,
    owner: Option<String>,
    description: Option<String>,
    security_score: Option<u8>,
    github_stars: Option<u32>,
    github_owner: Option<String>,
    github_repo: Option<String>,
    github_path: Option<String>,
}

fn github_repo_from(owner: Option<&str>, repo: Option<&str>) -> Option<String> {
    match (owner, repo) {
        (Some(o), Some(r)) if !o.is_empty() && !r.is_empty() => Some(format!("{o}/{r}")),
        _ => None,
    }
}

fn map_api_result(r: ApiResult) -> Option<SearchResult> {
    let name = r.name?;
    let owner = r.owner.unwrap_or_default();
    let slug = r.slug.unwrap_or_else(|| format!("{owner}/{name}"));
    let source_repo = github_repo_from(r.github_owner.as_deref(), r.github_repo.as_deref());
    Some(SearchResult {
        url: format!("https://agentskill.sh/@{slug}"),
        source_repo,
        source_path: r.github_path,
        name,
        owner,
        description: r.description,
        security_score: r.security_score,
        stars: r.github_stars,
        registry: RegistryId::AgentskillSh,
    })
}

/// Extract the JSON body from the first `__NUXT_DATA__` `<script>` tag.
fn extract_nuxt_json(html: &str) -> Option<&str> {
    let marker = r#"id="__NUXT_DATA__""#;
    let tag_start = html.find(marker)?;
    let after = &html[tag_start..];
    let tag_end = after.find('>')?;
    let content = &html[tag_start + tag_end + 1..];
    let end = content.find("</script>")?;
    Some(content[..end].trim())
}

/// Resolve the `skillMd` value from a Nuxt hydration data array.
///
/// The `__NUXT_DATA__` array contains objects whose values are numeric
/// indices into the same array. Find any object with a `"skillMd"` key,
/// read its numeric value, and index back into the array to get the
/// raw markdown string.
fn extract_skill_md(data: &[serde_json::Value]) -> Option<String> {
    let ref_idx = data
        .iter()
        .find_map(|v| v.as_object()?.get("skillMd")?.as_u64())?;
    let idx = usize::try_from(ref_idx).ok()?;
    data.get(idx)?.as_str().map(String::from)
}

impl Registry for AgentskillSh {
    fn name(&self) -> &'static str {
        "agentskill.sh"
    }

    fn fetch_skill_content(&self, client: &dyn HttpClient, item: &SearchResult) -> Option<String> {
        let bytes = client.get_bytes(&item.url).ok()?;
        let html = String::from_utf8(bytes).ok()?;
        let json_str = extract_nuxt_json(&html)?;
        let data: Vec<serde_json::Value> = serde_json::from_str(json_str).ok()?;
        extract_skill_md(&data)
    }

    fn search(&self, q: &SearchQuery<'_>) -> Result<SearchResponse, SkillfileError> {
        let (client, query) = (q.client, q.query);
        let url = format!("{AGENTSKILL_API}?q={}&limit=100", urlencoded(query));

        let bytes = client
            .get_bytes(&url)
            .map_err(|e| SkillfileError::Network(format!("agentskill.sh search failed: {e}")))?;

        let body = String::from_utf8(bytes).map_err(|e| {
            SkillfileError::Network(format!("invalid UTF-8 in agentskill.sh response: {e}"))
        })?;

        let api: ApiResponse = serde_json::from_str(&body).map_err(|e| {
            SkillfileError::Network(format!("failed to parse agentskill.sh results: {e}"))
        })?;

        let items: Vec<SearchResult> = api.results.into_iter().filter_map(map_api_result).collect();

        Ok(SearchResponse {
            total: api.total.unwrap_or(items.len()),
            items,
        })
    }
}

// ---------------------------------------------------------------------------
// Detail API — fetch GitHub coordinates for a specific skill
// ---------------------------------------------------------------------------

/// GitHub coordinates resolved from the agentskill.sh detail API.
#[derive(Debug, Clone)]
pub struct AgentskillGithubMeta {
    /// GitHub `owner/repo` (e.g. `openclaw/skills`).
    pub source_repo: String,
    pub source_path: String,
}

const AGENTSKILL_SKILLS_API: &str = "https://agentskill.sh/api/skills";

#[derive(Deserialize)]
struct DetailResponse {
    data: Option<Vec<DetailResult>>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct DetailResult {
    slug: Option<String>,
    github_owner: Option<String>,
    github_repo: Option<String>,
    github_path: Option<String>,
}

/// Fetch GitHub coordinates for an agentskill.sh skill by querying the detail API.
///
/// The search API (`/api/agent/search`) only returns a registry slug, not the
/// actual GitHub coordinates. The detail API (`/api/skills`) returns
/// `githubOwner`, `githubRepo`, and `githubPath`.
///
/// Queries by `skill_name`, then matches on `slug` to find the right entry.
/// Returns `None` on network failure or if no matching entry is found.
pub fn fetch_agentskill_github_meta(
    client: &dyn HttpClient,
    slug: &str,
    skill_name: &str,
) -> Option<AgentskillGithubMeta> {
    let url = format!(
        "{AGENTSKILL_SKILLS_API}?q={}&limit=5",
        urlencoded(skill_name)
    );

    let bytes = client.get_bytes(&url).ok()?;
    let body = String::from_utf8(bytes).ok()?;
    let api: DetailResponse = serde_json::from_str(&body).ok()?;

    let items = api.data?;
    let slug_lower = slug.to_ascii_lowercase();

    for item in items {
        let item_slug = item.slug.as_deref().unwrap_or("");
        if item_slug.to_ascii_lowercase() == slug_lower {
            let owner = item.github_owner.filter(|s| !s.is_empty())?;
            let repo = item.github_repo.filter(|s| !s.is_empty())?;
            let path = item.github_path.filter(|s| !s.is_empty())?;
            return Some(AgentskillGithubMeta {
                source_repo: format!("{owner}/{repo}"),
                source_path: path,
            });
        }
    }

    None
}

/// Scrape GitHub coordinates from an agentskill.sh skill page.
///
/// Fallback for when [`fetch_agentskill_github_meta`] can't find the slug
/// in the detail API search results. The skill page embeds `githubOwner`,
/// `githubRepo`, and `githubPath` in its Nuxt hydration data.
pub fn scrape_github_meta_from_page(
    client: &dyn HttpClient,
    slug: &str,
) -> Option<AgentskillGithubMeta> {
    let url = format!("https://agentskill.sh/@{slug}");
    let bytes = client.get_bytes(&url).ok()?;
    let html = String::from_utf8(bytes).ok()?;
    let source_repo = extract_repo_from_html(&html)?;
    let source_path = extract_path_from_html(&html).unwrap_or_default();
    Some(AgentskillGithubMeta {
        source_repo,
        source_path,
    })
}

/// Parse the first `github.com/{owner}/{repo}` URL from Nuxt-rendered HTML.
fn extract_repo_from_html(html: &str) -> Option<String> {
    extract_repo_nuxt(html).or_else(|| extract_repo_plain(html))
}

/// Parse the `githubPath` from Nuxt-rendered HTML.
///
/// Looks for a Nuxt-escaped path ending in `SKILL.md`.
fn extract_path_from_html(html: &str) -> Option<String> {
    // Nuxt format: "skills\u002Fauthor\u002Fname\u002FSKILL.md"
    let marker = r"\u002FSKILL.md";
    if let Some(end) = html.find(marker) {
        let before = &html[..end];
        let quote = before.rfind('"')?;
        let raw = &html[quote + 1..end + marker.len()];
        return Some(raw.replace(r"\u002F", "/"));
    }
    None
}

fn extract_repo_nuxt(html: &str) -> Option<String> {
    let marker = r"github.com\u002F";
    let sep = r"\u002F";
    let pos = html.find(marker)?;
    let after = &html[pos + marker.len()..];
    let owner_end = after.find(sep)?;
    let owner = &after[..owner_end];
    let after_owner = &after[owner_end + sep.len()..];
    let repo_end = after_owner.find(['"', '\\'])?;
    let repo = &after_owner[..repo_end];
    if owner.is_empty() || repo.is_empty() {
        return None;
    }
    Some(format!("{owner}/{repo}"))
}

fn extract_repo_plain(html: &str) -> Option<String> {
    let marker = "github.com/";
    for (i, _) in html.match_indices(marker) {
        let after = &html[i + marker.len()..];
        let Some(owner_end) = after.find('/') else {
            continue;
        };
        let owner = &after[..owner_end];
        let after_owner = &after[owner_end + 1..];
        let Some(repo_end) =
            after_owner.find(|c: char| !c.is_alphanumeric() && c != '-' && c != '_' && c != '.')
        else {
            continue;
        };
        let repo = &after_owner[..repo_end];
        if !owner.is_empty() && !repo.is_empty() && owner != "avatars" {
            return Some(format!("{owner}/{repo}"));
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::registry::test_support::MockClient;
    use crate::registry::SearchOptions;

    fn mock_response() -> String {
        r#"{
            "results": [
                {
                    "slug": "alice/code-reviewer",
                    "name": "code-reviewer",
                    "owner": "alice",
                    "description": "Review code changes",
                    "securityScore": 92,
                    "githubStars": 150
                },
                {
                    "slug": "bob/pr-review",
                    "name": "pr-review",
                    "owner": "bob",
                    "description": "Automated PR reviews",
                    "securityScore": 65,
                    "githubStars": 30
                }
            ],
            "total": 2,
            "hasMore": false,
            "totalExact": true
        }"#
        .to_string()
    }

    #[test]
    fn search_parses_response() {
        let client = MockClient::new(vec![Ok(mock_response())]);
        let resp =
            super::super::search_with_client(&client, "code review", &SearchOptions::default())
                .unwrap();
        assert_eq!(resp.items.len(), 2);
        assert_eq!(resp.total, 2);
        assert_eq!(resp.items[0].name, "code-reviewer");
        assert_eq!(resp.items[0].owner, "alice");
        assert_eq!(resp.items[0].security_score, Some(92));
        assert_eq!(resp.items[0].stars, Some(150));
        assert!(resp.items[0].url.contains("agentskill.sh"));
        assert_eq!(resp.items[0].registry, RegistryId::AgentskillSh);
    }

    #[test]
    fn search_applies_min_score_filter() {
        let client = MockClient::new(vec![Ok(mock_response())]);
        let opts = SearchOptions {
            limit: 10,
            min_score: Some(80),
        };
        let resp = super::super::search_with_client(&client, "code review", &opts).unwrap();
        assert_eq!(resp.items.len(), 1);
        assert_eq!(resp.items[0].name, "code-reviewer");
    }

    #[test]
    fn search_handles_missing_optional_fields() {
        let json = r#"{
            "results": [
                {
                    "slug": "alice/minimal",
                    "name": "minimal",
                    "owner": null,
                    "description": null,
                    "securityScore": null,
                    "githubStars": null
                }
            ],
            "total": 1
        }"#;
        let client = MockClient::new(vec![Ok(json.to_string())]);
        let resp =
            super::super::search_with_client(&client, "test", &SearchOptions::default()).unwrap();
        assert_eq!(resp.items.len(), 1);
        assert_eq!(resp.items[0].name, "minimal");
        assert_eq!(resp.items[0].owner, "");
        assert!(resp.items[0].description.is_none());
        assert!(resp.items[0].security_score.is_none());
    }

    #[test]
    fn search_skips_results_without_name() {
        let json = r#"{
            "results": [
                {"slug": "x/y", "name": null, "owner": "x"},
                {"slug": "a/b", "name": "valid", "owner": "a"}
            ],
            "total": 2
        }"#;
        let client = MockClient::new(vec![Ok(json.to_string())]);
        let resp =
            super::super::search_with_client(&client, "test", &SearchOptions::default()).unwrap();
        assert_eq!(resp.items.len(), 1);
        assert_eq!(resp.items[0].name, "valid");
    }

    #[test]
    fn search_returns_error_on_network_failure() {
        let client = MockClient::new(vec![Err("connection refused".to_string())]);
        let result = super::super::search_with_client(&client, "test", &SearchOptions::default());
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("search failed"), "got: {err}");
    }

    #[test]
    fn search_returns_error_on_malformed_json() {
        let client = MockClient::new(vec![Ok("not json".to_string())]);
        let result = super::super::search_with_client(&client, "test", &SearchOptions::default());
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("failed to parse"), "got: {err}");
    }

    #[test]
    fn search_constructs_url_from_slug() {
        let client = MockClient::new(vec![Ok(mock_response())]);
        let resp =
            super::super::search_with_client(&client, "test", &SearchOptions::default()).unwrap();
        assert_eq!(
            resp.items[0].url,
            "https://agentskill.sh/@alice/code-reviewer"
        );
        // No GitHub coordinates in the mock → source_repo must be None.
        // The slug is in the URL, not source_repo.
        assert!(resp.items[0].source_repo.is_none());
        assert!(resp.items[0].source_path.is_none());
    }

    #[test]
    fn search_uses_github_coordinates_when_present() {
        let json = r#"{
            "results": [{
                "slug": "openclaw/fzf-fuzzy-finder",
                "name": "fzf-fuzzy-finder",
                "owner": "openclaw",
                "description": "Fuzzy finder skill",
                "securityScore": 80,
                "githubStars": 2218,
                "githubOwner": "openclaw",
                "githubRepo": "skills",
                "githubPath": "skills/arnarsson/fzf-fuzzy-finder/SKILL.md"
            }],
            "total": 1
        }"#
        .to_string();
        let client = MockClient::new(vec![Ok(json)]);
        let resp =
            super::super::search_with_client(&client, "fzf", &SearchOptions::default()).unwrap();

        assert_eq!(resp.items.len(), 1);
        assert_eq!(
            resp.items[0].source_repo.as_deref(),
            Some("openclaw/skills")
        );
        assert_eq!(
            resp.items[0].source_path.as_deref(),
            Some("skills/arnarsson/fzf-fuzzy-finder/SKILL.md")
        );
        assert_eq!(
            resp.items[0].url,
            "https://agentskill.sh/@openclaw/fzf-fuzzy-finder"
        );
    }

    // -- Detail API tests -------------------------------------------------------

    struct DetailMockParams<'a> {
        slug: &'a str,
        owner: &'a str,
        repo: &'a str,
        path: &'a str,
    }

    fn detail_mock(p: &DetailMockParams<'_>) -> String {
        let (slug, owner, repo, path) = (p.slug, p.owner, p.repo, p.path);
        format!(
            r#"{{"data": [{{"slug": "{slug}", "githubOwner": "{owner}", "githubRepo": "{repo}", "githubPath": "{path}"}}]}}"#
        )
    }

    #[test]
    fn fetch_github_meta_returns_coordinates() {
        let json = detail_mock(&DetailMockParams {
            slug: "openclaw/fzf-fuzzy-finder",
            owner: "openclaw",
            repo: "skills",
            path: "skills/arnarsson/fzf-fuzzy-finder/SKILL.md",
        });
        let client = MockClient::new(vec![Ok(json)]);
        let meta =
            fetch_agentskill_github_meta(&client, "openclaw/fzf-fuzzy-finder", "fzf-fuzzy-finder");
        let meta = meta.expect("should return meta");
        assert_eq!(meta.source_repo, "openclaw/skills");
        assert_eq!(
            meta.source_path,
            "skills/arnarsson/fzf-fuzzy-finder/SKILL.md"
        );
    }

    #[test]
    fn fetch_github_meta_case_insensitive_slug() {
        let json = detail_mock(&DetailMockParams {
            slug: "OpenClaw/FZF-Fuzzy-Finder",
            owner: "openclaw",
            repo: "skills",
            path: "skills/arnarsson/fzf-fuzzy-finder/SKILL.md",
        });
        let client = MockClient::new(vec![Ok(json)]);
        let meta =
            fetch_agentskill_github_meta(&client, "openclaw/fzf-fuzzy-finder", "fzf-fuzzy-finder");
        assert!(meta.is_some());
    }

    #[test]
    fn fetch_github_meta_no_match_returns_none() {
        let json = detail_mock(&DetailMockParams {
            slug: "other/skill",
            owner: "other",
            repo: "repo",
            path: "skill.md",
        });
        let client = MockClient::new(vec![Ok(json)]);
        let meta =
            fetch_agentskill_github_meta(&client, "openclaw/fzf-fuzzy-finder", "fzf-fuzzy-finder");
        assert!(meta.is_none());
    }

    #[test]
    fn fetch_github_meta_empty_data_returns_none() {
        let json = r#"{"data": []}"#.to_string();
        let client = MockClient::new(vec![Ok(json)]);
        let meta =
            fetch_agentskill_github_meta(&client, "openclaw/fzf-fuzzy-finder", "fzf-fuzzy-finder");
        assert!(meta.is_none());
    }

    #[test]
    fn fetch_github_meta_network_error_returns_none() {
        let client = MockClient::new(vec![Err("connection refused".to_string())]);
        let meta =
            fetch_agentskill_github_meta(&client, "openclaw/fzf-fuzzy-finder", "fzf-fuzzy-finder");
        assert!(meta.is_none());
    }

    #[test]
    fn fetch_github_meta_malformed_json_returns_none() {
        let client = MockClient::new(vec![Ok("not json".to_string())]);
        let meta =
            fetch_agentskill_github_meta(&client, "openclaw/fzf-fuzzy-finder", "fzf-fuzzy-finder");
        assert!(meta.is_none());
    }

    #[test]
    fn fetch_github_meta_missing_github_fields_returns_none() {
        let json = r#"{"data": [{"slug": "openclaw/fzf-fuzzy-finder"}]}"#.to_string();
        let client = MockClient::new(vec![Ok(json)]);
        let meta =
            fetch_agentskill_github_meta(&client, "openclaw/fzf-fuzzy-finder", "fzf-fuzzy-finder");
        assert!(meta.is_none());
    }

    #[test]
    fn fetch_github_meta_empty_github_fields_returns_none() {
        let json = r#"{"data": [{"slug": "openclaw/fzf-fuzzy-finder", "githubOwner": "", "githubRepo": "", "githubPath": ""}]}"#.to_string();
        let client = MockClient::new(vec![Ok(json)]);
        let meta =
            fetch_agentskill_github_meta(&client, "openclaw/fzf-fuzzy-finder", "fzf-fuzzy-finder");
        assert!(meta.is_none());
    }

    // -- Slug-as-source_repo regression tests ----------------------------------

    /// Regression: when the search API returns a result WITHOUT explicit GitHub
    /// coordinates (`githubOwner`, `githubRepo`, `githubPath` are all null),
    /// `source_repo` must NOT be set to the registry slug.
    ///
    /// The slug (e.g. `openclaw/k8s`) is a registry identifier, not a GitHub
    /// `owner/repo`. Treating it as one causes the Tree API to fail downstream,
    /// leading to a confusing "Path in repo:" prompt instead of a clear error.
    /// Regression: slug must NOT leak into `source_repo` when GitHub
    /// coordinates are absent from the search API response.
    #[test]
    fn map_result_without_github_coords_does_not_use_slug_as_source_repo() {
        let json = r#"{
            "results": [{
                "slug": "openclaw/k8s-config-gen",
                "name": "k8s-config-gen",
                "owner": "openclaw",
                "description": "Kubernetes config generator",
                "securityScore": 80,
                "githubStars": 100
            }],
            "total": 1
        }"#;
        let client = MockClient::new(vec![Ok(json.to_string())]);
        let resp =
            super::super::search_with_client(&client, "k8s", &SearchOptions::default()).unwrap();

        assert_eq!(resp.items.len(), 1);
        assert!(
            resp.items[0].source_repo.is_none(),
            "source_repo should be None when GitHub coords are missing, \
             got {:?} (slug leaked into source_repo)",
            resp.items[0].source_repo
        );
    }

    // -- Page scrape tests -------------------------------------------------------

    #[test]
    fn extract_repo_from_nuxt_escaped_html() {
        let html = r#"some stuff "https:\u002F\u002Fgithub.com\u002Fopenclaw\u002Fskills" more"#;
        assert_eq!(
            extract_repo_from_html(html).as_deref(),
            Some("openclaw/skills")
        );
    }

    #[test]
    fn extract_repo_from_plain_html() {
        let html = r#"<a href="https://github.com/openclaw/skills/tree/main">repo</a>"#;
        assert_eq!(
            extract_repo_from_html(html).as_deref(),
            Some("openclaw/skills")
        );
    }

    #[test]
    fn extract_repo_skips_avatar_urls() {
        let html =
            "https://avatars.githubusercontent.com/u/12345 https://github.com/real/repo stuff";
        assert_eq!(extract_repo_from_html(html).as_deref(), Some("real/repo"));
    }

    #[test]
    fn extract_repo_returns_none_for_no_github_url() {
        let html = "<html><body>no github links here</body></html>";
        assert!(extract_repo_from_html(html).is_none());
    }

    #[test]
    fn extract_repo_handles_hyphenated_names() {
        let html = r#""https:\u002F\u002Fgithub.com\u002Falphaonedev\u002Fopenclaw-graph""#;
        assert_eq!(
            extract_repo_from_html(html).as_deref(),
            Some("alphaonedev/openclaw-graph")
        );
    }

    #[test]
    fn extract_repo_plain_skips_malformed_first_match() {
        let html = "github.com/broken https://github.com/real/repo end";
        assert_eq!(extract_repo_from_html(html).as_deref(), Some("real/repo"));
    }

    #[test]
    fn extract_path_from_nuxt_html() {
        let html = r#"stuff "skills\u002Fivangdavila\u002Fk8s\u002FSKILL.md" more"#;
        assert_eq!(
            extract_path_from_html(html).as_deref(),
            Some("skills/ivangdavila/k8s/SKILL.md")
        );
    }

    #[test]
    fn extract_path_returns_none_when_missing() {
        let html = "<html>no skill path here</html>";
        assert!(extract_path_from_html(html).is_none());
    }

    #[test]
    fn scrape_page_returns_full_meta_from_mock_html() {
        let html = r#"<html>"https:\u002F\u002Fgithub.com\u002Fopenclaw\u002Fskills" and "skills\u002Fivangdavila\u002Fk8s\u002FSKILL.md"</html>"#;
        let client = MockClient::new(vec![Ok(html.to_string())]);
        let meta = scrape_github_meta_from_page(&client, "openclaw/k8s");
        let meta = meta.expect("should return meta");
        assert_eq!(meta.source_repo, "openclaw/skills");
        assert_eq!(meta.source_path, "skills/ivangdavila/k8s/SKILL.md");
    }

    #[test]
    fn scrape_page_returns_repo_only_when_no_path() {
        let html = r#"<html>"https:\u002F\u002Fgithub.com\u002Fopenclaw\u002Fskills"</html>"#;
        let client = MockClient::new(vec![Ok(html.to_string())]);
        let meta = scrape_github_meta_from_page(&client, "openclaw/k8s");
        let meta = meta.expect("should return meta with empty path");
        assert_eq!(meta.source_repo, "openclaw/skills");
        assert!(meta.source_path.is_empty());
    }

    #[test]
    fn scrape_page_returns_none_on_network_error() {
        let client = MockClient::new(vec![Err("connection refused".to_string())]);
        let meta = scrape_github_meta_from_page(&client, "openclaw/k8s");
        assert!(meta.is_none());
    }

    #[test]
    fn fetch_github_meta_picks_matching_slug_from_multiple() {
        let json = r#"{"data": [
            {"slug": "other/fzf", "githubOwner": "other", "githubRepo": "repo", "githubPath": "fzf.md"},
            {"slug": "openclaw/fzf-fuzzy-finder", "githubOwner": "openclaw", "githubRepo": "skills", "githubPath": "skills/arnarsson/fzf-fuzzy-finder/SKILL.md"}
        ]}"#.to_string();
        let client = MockClient::new(vec![Ok(json)]);
        let meta =
            fetch_agentskill_github_meta(&client, "openclaw/fzf-fuzzy-finder", "fzf-fuzzy-finder");
        let meta = meta.expect("should match second entry");
        assert_eq!(meta.source_repo, "openclaw/skills");
        assert_eq!(
            meta.source_path,
            "skills/arnarsson/fzf-fuzzy-finder/SKILL.md"
        );
    }

    // -- fetch_skill_content tests (Nuxt __NUXT_DATA__ scraping) ---------------

    fn make_nuxt_html(nuxt_data: &serde_json::Value) -> String {
        format!(
            r#"<html><head><script id="__NUXT_DATA__" type="application/json">{nuxt_data}</script></head></html>"#
        )
    }

    fn make_search_result(url: &str) -> SearchResult {
        SearchResult {
            name: "test-skill".into(),
            owner: "test".into(),
            description: None,
            security_score: None,
            stars: None,
            url: url.into(),
            registry: RegistryId::AgentskillSh,
            source_repo: None,
            source_path: None,
        }
    }

    #[test]
    fn fetch_skill_content_extracts_from_nuxt_payload() {
        let md = "---\nname: test-skill\n---\n# Test Skill\nBody.";
        // Real format: an object has {"skillMd": N} where data[N] is the markdown.
        let data = serde_json::json!(["padding", {"skillMd": 2}, md]);
        let html = make_nuxt_html(&data);
        let client = MockClient::new(vec![Ok(html)]);
        let item = make_search_result("https://agentskill.sh/@test/test-skill");
        let result = AgentskillSh.fetch_skill_content(&client, &item);
        assert_eq!(result.as_deref(), Some(md));
    }

    #[test]
    fn fetch_skill_content_returns_none_on_missing_payload() {
        let html = "<html><body>No Nuxt data</body></html>";
        let client = MockClient::new(vec![Ok(html.into())]);
        let item = make_search_result("https://agentskill.sh/@test/x");
        assert!(AgentskillSh.fetch_skill_content(&client, &item).is_none());
    }

    #[test]
    fn fetch_skill_content_returns_none_on_network_error() {
        let client = MockClient::new(vec![Err("refused".into())]);
        let item = make_search_result("https://agentskill.sh/@test/x");
        assert!(AgentskillSh.fetch_skill_content(&client, &item).is_none());
    }

    #[test]
    fn fetch_skill_content_returns_none_on_missing_skill_md_key() {
        let data = serde_json::json!(["no", "skillMd_key", "here"]);
        let html = make_nuxt_html(&data);
        let client = MockClient::new(vec![Ok(html)]);
        let item = make_search_result("https://agentskill.sh/@test/x");
        assert!(AgentskillSh.fetch_skill_content(&client, &item).is_none());
    }

    #[test]
    fn fetch_skill_content_returns_none_on_invalid_json() {
        let html = r#"<html><script id="__NUXT_DATA__">not json</script></html>"#;
        let client = MockClient::new(vec![Ok(html.into())]);
        let item = make_search_result("https://agentskill.sh/@test/x");
        assert!(AgentskillSh.fetch_skill_content(&client, &item).is_none());
    }

    #[test]
    fn extract_nuxt_json_handles_attributes_order() {
        let html = r#"<script type="application/json" id="__NUXT_DATA__">["a","b"]</script>"#;
        let json = extract_nuxt_json(html);
        assert_eq!(json, Some(r#"["a","b"]"#));
    }

    #[test]
    fn extract_skill_md_returns_none_when_ref_out_of_bounds() {
        let data = vec![serde_json::json!({"skillMd": 999})];
        assert!(extract_skill_md(&data).is_none());
    }
}