skrills-intelligence 0.8.2

Intelligent skill recommendations based on usage patterns and project context.
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
//! Search GitHub for existing SKILL.md files.

use anyhow::Result;
use reqwest::header::AUTHORIZATION;
use serde::{Deserialize, Serialize};

const GITHUB_API_BASE: &str = "https://api.github.com";

/// Get the GitHub API base URL, allowing override for testing.
fn github_api_base() -> String {
    std::env::var("GITHUB_API_BASE_URL").unwrap_or_else(|_| GITHUB_API_BASE.to_string())
}

/// Get the raw content base URL, allowing override for testing.
fn raw_content_base() -> String {
    std::env::var("GITHUB_RAW_BASE_URL")
        .unwrap_or_else(|_| "https://raw.githubusercontent.com".to_string())
}

fn github_token() -> Option<String> {
    let raw = std::env::var("GITHUB_TOKEN").ok()?;
    let token = raw.trim();
    if token.is_empty() {
        None
    } else {
        Some(token.to_string())
    }
}

fn apply_github_auth(builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
    match github_token() {
        Some(token) => builder.header(AUTHORIZATION, format!("Bearer {token}")),
        None => builder,
    }
}

/// A skill found on GitHub.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitHubSkillResult {
    /// Repository URL.
    pub repo_url: String,
    /// Path to the skill file within the repo.
    pub skill_path: String,
    /// Direct URL to the skill file on GitHub.
    pub file_url: String,
    /// Repository description.
    pub description: Option<String>,
    /// Number of stars.
    pub stars: u64,
    /// Last update date.
    pub last_updated: String,
    /// Raw URL to fetch the skill content.
    pub raw_url: Option<String>,
}

#[derive(Deserialize)]
struct SearchResponse {
    items: Vec<SearchItem>,
}

#[derive(Deserialize)]
struct SearchItem {
    path: String,
    html_url: String,
    repository: Repository,
}

#[derive(Deserialize)]
struct Repository {
    full_name: String,
    html_url: String,
    #[serde(default)]
    stargazers_count: u64,
    #[serde(default)]
    updated_at: String,
    description: Option<String>,
}

/// Sanitize user input to prevent GitHub search operator injection.
/// Strips known GitHub search operators that could manipulate search semantics.
fn sanitize_github_query(query: &str) -> String {
    // GitHub search operators that could be injected (colon-based operators)
    let colon_operators = [
        "repo:",
        "org:",
        "user:",
        "in:",
        "size:",
        "fork:",
        "forks:",
        "stars:",
        "topics:",
        "topic:",
        "created:",
        "pushed:",
        "updated:",
        "is:",
        "archived:",
        "license:",
        "language:",
        "filename:",
        "path:",
        "extension:",
    ];

    // Boolean operators (must be standalone words, case-insensitive)
    let boolean_operators = ["NOT", "AND", "OR"];

    let mut sanitized = query.to_string();

    // Remove colon-based operators
    for op in colon_operators {
        loop {
            let lower = sanitized.to_lowercase();
            if let Some(pos) = lower.find(&op.to_lowercase()) {
                // Find the end of the operator value (space or end of string)
                let rest = &sanitized[pos + op.len()..];
                let end = if rest.starts_with('"') {
                    // Quoted value - find closing quote
                    rest.strip_prefix('"')
                        .and_then(|s| s.find('"'))
                        .map(|p| pos + op.len() + p + 2)
                        .unwrap_or(sanitized.len())
                } else {
                    // Unquoted value - find next space
                    rest.find(' ')
                        .map(|p| pos + op.len() + p)
                        .unwrap_or(sanitized.len())
                };
                sanitized = format!("{}{}", &sanitized[..pos], &sanitized[end..]);
            } else {
                break;
            }
        }
    }

    // Remove standalone boolean operators (word boundaries check)
    let words: Vec<&str> = sanitized.split_whitespace().collect();
    let filtered_words: Vec<&str> = words
        .into_iter()
        .filter(|word| {
            !boolean_operators
                .iter()
                .any(|op| word.eq_ignore_ascii_case(op))
        })
        .collect();

    filtered_words.join(" ")
}

/// Search GitHub for skills matching the query.
pub async fn search_github_skills(query: &str, limit: usize) -> Result<Vec<GitHubSkillResult>> {
    // Sanitize user input to prevent search operator injection
    let sanitized_query = sanitize_github_query(query);

    // Build search query for SKILL.md files
    let search_query = format!("{} filename:SKILL.md", sanitized_query);

    search_github_raw(&search_query, limit).await
}

/// Internal search function that performs the raw GitHub API call.
/// This function does NOT sanitize the query, so it should only be called
/// with trusted input (e.g., from `search_skills_advanced`).
async fn search_github_raw(query: &str, limit: usize) -> Result<Vec<GitHubSkillResult>> {
    let client = reqwest::Client::new();

    let response = apply_github_auth(
        client
            .get(format!("{}/search/code", github_api_base()))
            .query(&[("q", query), ("per_page", &limit.to_string())])
            .header("Accept", "application/vnd.github.v3+json")
            .header("User-Agent", "skrills-intelligence/0.4.0"),
    )
    .send()
    .await?;

    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await.unwrap_or_default();

        // Provide actionable error messages for common GitHub API errors
        let error_msg = match status.as_u16() {
            403 => {
                if body.contains("rate limit") || body.contains("API rate limit exceeded") {
                    "GitHub API rate limit exceeded. Wait a few minutes and try again, or set GITHUB_TOKEN environment variable for higher limits."
                } else {
                    "GitHub API access forbidden. Check your GITHUB_TOKEN permissions."
                }
            }
            401 => "GitHub API authentication failed. Verify your GITHUB_TOKEN is valid.",
            422 => "GitHub search query invalid. Try simplifying your search terms.",
            _ => "",
        };

        // Construct via the structured `IntelligenceError::GitHubApi`
        // variant so callers can match on `status` to decide whether
        // to retry, fall back, or surface to the user. The `?`
        // operator promotes it into anyhow::Error transparently.
        let message = if error_msg.is_empty() {
            body
        } else {
            format!("{error_msg} (body: {body})")
        };
        return Err(crate::IntelligenceError::GitHubApi {
            status: status.as_u16(),
            message,
        }
        .into());
    }

    let search_result: SearchResponse = response.json().await?;

    Ok(search_result
        .items
        .into_iter()
        .map(|item| {
            let raw_url = build_raw_url(&item.repository.full_name, &item.path);
            GitHubSkillResult {
                repo_url: item.repository.html_url,
                skill_path: item.path,
                file_url: item.html_url,
                description: item.repository.description,
                stars: item.repository.stargazers_count,
                last_updated: item.repository.updated_at,
                raw_url: Some(raw_url),
            }
        })
        .collect())
}

/// Build a raw.githubusercontent.com URL for fetching file content.
fn build_raw_url(full_name: &str, path: &str) -> String {
    format!("{}/{}/HEAD/{}", raw_content_base(), full_name, path)
}

/// Fetch the content of a skill from its raw URL.
pub async fn fetch_skill_content(raw_url: &str) -> Result<String> {
    let client = reqwest::Client::new();

    let response = apply_github_auth(
        client
            .get(raw_url)
            .header("User-Agent", "skrills-intelligence/0.4.0"),
    )
    .send()
    .await?;

    if !response.status().is_success() {
        return Err(crate::IntelligenceError::FetchFailed {
            status: response.status().as_u16(),
        }
        .into());
    }

    Ok(response.text().await?)
}

/// Search for skills with specific criteria.
pub async fn search_skills_advanced(
    keywords: &[String],
    language: Option<&str>,
    min_stars: Option<u64>,
    limit: usize,
) -> Result<Vec<GitHubSkillResult>> {
    let mut query_parts = vec!["filename:SKILL.md".to_string()];

    // Add sanitized keywords (user input)
    for keyword in keywords {
        let sanitized = sanitize_github_query(keyword);
        if !sanitized.is_empty() {
            query_parts.push(sanitized);
        }
    }

    // Add language filter (trusted input, not from user)
    if let Some(lang) = language {
        query_parts.push(format!("language:{}", lang));
    }

    // Add star filter (trusted input, not from user)
    if let Some(stars) = min_stars {
        query_parts.push(format!("stars:>={}", stars));
    }

    let query = query_parts.join(" ");
    // Use raw search since we've already sanitized user input and
    // added trusted operators
    search_github_raw(&query, limit).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::{env_guard, set_env_var};
    use reqwest::header::AUTHORIZATION;
    use serial_test::serial;

    #[test]
    #[serial]
    fn test_build_raw_url_default() {
        let _g = env_guard();
        let _raw_guard = set_env_var("GITHUB_RAW_BASE_URL", None);
        let url = build_raw_url("owner/repo", "skills/test/SKILL.md");
        assert_eq!(
            url,
            "https://raw.githubusercontent.com/owner/repo/HEAD/skills/test/SKILL.md"
        );
    }

    #[test]
    #[serial]
    fn test_build_raw_url_with_custom_base() {
        let _g = env_guard();
        let _raw_guard = set_env_var("GITHUB_RAW_BASE_URL", Some("http://localhost:8080"));
        let url = build_raw_url("owner/repo", "skills/test/SKILL.md");
        assert_eq!(
            url,
            "http://localhost:8080/owner/repo/HEAD/skills/test/SKILL.md"
        );
    }

    #[test]
    #[serial]
    fn test_github_api_base_default() {
        let _g = env_guard();
        let _api_guard = set_env_var("GITHUB_API_BASE_URL", None);
        assert_eq!(github_api_base(), "https://api.github.com");
    }

    #[test]
    #[serial]
    fn test_github_api_base_custom() {
        let _g = env_guard();
        let _api_guard = set_env_var("GITHUB_API_BASE_URL", Some("http://localhost:9090"));
        assert_eq!(github_api_base(), "http://localhost:9090");
    }

    #[test]
    #[serial]
    fn test_github_auth_header_set_when_token_present() {
        let _g = env_guard();
        let _token_guard = set_env_var("GITHUB_TOKEN", Some("test-token"));
        let client = reqwest::Client::new();
        let request = apply_github_auth(client.get("https://api.github.com"))
            .build()
            .unwrap();
        let header = request.headers().get(AUTHORIZATION).unwrap();
        assert_eq!(header.to_str().unwrap(), "Bearer test-token");
    }

    #[test]
    #[serial]
    fn test_github_auth_header_absent_when_no_token() {
        let _g = env_guard();
        let _token_guard = set_env_var("GITHUB_TOKEN", None);
        let client = reqwest::Client::new();
        let request = apply_github_auth(client.get("https://api.github.com"))
            .build()
            .unwrap();
        assert!(request.headers().get(AUTHORIZATION).is_none());
    }

    #[test]
    #[serial]
    fn test_github_auth_header_absent_when_empty_token() {
        let _g = env_guard();
        let _token_guard = set_env_var("GITHUB_TOKEN", Some(""));
        let client = reqwest::Client::new();
        let request = apply_github_auth(client.get("https://api.github.com"))
            .build()
            .unwrap();
        assert!(request.headers().get(AUTHORIZATION).is_none());
    }

    #[test]
    #[serial]
    fn test_github_auth_header_absent_when_whitespace_only_token() {
        let _g = env_guard();
        let _token_guard = set_env_var("GITHUB_TOKEN", Some("   \t\n  "));
        let client = reqwest::Client::new();
        let request = apply_github_auth(client.get("https://api.github.com"))
            .build()
            .unwrap();
        assert!(request.headers().get(AUTHORIZATION).is_none());
    }

    #[test]
    #[serial]
    fn test_github_auth_trims_token_whitespace() {
        let _g = env_guard();
        let _token_guard = set_env_var("GITHUB_TOKEN", Some("  test-token  "));
        let client = reqwest::Client::new();
        let request = apply_github_auth(client.get("https://api.github.com"))
            .build()
            .unwrap();
        let header = request.headers().get(AUTHORIZATION).unwrap();
        assert_eq!(header.to_str().unwrap(), "Bearer test-token");
    }

    #[test]
    fn test_sanitize_github_query_removes_operators() {
        // Test removal of common injection operators
        assert_eq!(sanitize_github_query("test repo:evil/repo"), "test");
        assert_eq!(sanitize_github_query("test org:malicious"), "test");
        assert_eq!(sanitize_github_query("test stars:>1000"), "test");
        assert_eq!(sanitize_github_query("test language:rust"), "test");
        assert_eq!(sanitize_github_query("test is:archived"), "test");
    }

    #[test]
    fn test_sanitize_github_query_removes_all_colon_operators() {
        // Test all defined colon operators
        let operators = [
            "repo:",
            "org:",
            "user:",
            "in:",
            "size:",
            "fork:",
            "forks:",
            "stars:",
            "topics:",
            "topic:",
            "created:",
            "pushed:",
            "updated:",
            "is:",
            "archived:",
            "license:",
            "language:",
            "filename:",
            "path:",
            "extension:",
        ];
        for op in operators {
            let query = format!("test {}value", op);
            let result = sanitize_github_query(&query);
            assert_eq!(result, "test", "Failed to remove operator: {}", op);
        }
    }

    #[test]
    fn test_sanitize_github_query_preserves_normal_text() {
        // Normal queries should pass through unchanged
        assert_eq!(sanitize_github_query("testing skills"), "testing skills");
        assert_eq!(sanitize_github_query("rust async"), "rust async");
        assert_eq!(sanitize_github_query("hello world"), "hello world");
    }

    #[test]
    fn test_sanitize_github_query_handles_quoted_values() {
        // Quoted operator values should be removed
        assert_eq!(sanitize_github_query(r#"test repo:"owner/repo""#), "test");
    }

    #[test]
    fn test_sanitize_github_query_collapses_whitespace() {
        // Multiple spaces should be collapsed
        assert_eq!(
            sanitize_github_query("test   multiple   spaces"),
            "test multiple spaces"
        );
    }

    #[test]
    fn test_sanitize_github_query_case_insensitive() {
        // Operators should be removed regardless of case
        assert_eq!(sanitize_github_query("test REPO:evil"), "test");
        assert_eq!(sanitize_github_query("test Repo:evil"), "test");
    }

    #[test]
    fn test_sanitize_github_query_removes_boolean_operators() {
        // Boolean operators should be removed as standalone words only
        assert_eq!(sanitize_github_query("foo AND bar"), "foo bar");
        assert_eq!(sanitize_github_query("foo OR bar"), "foo bar");
        assert_eq!(sanitize_github_query("NOT foo"), "foo");
        // But words containing these should NOT be affected
        assert_eq!(sanitize_github_query("Oregon skills"), "Oregon skills");
        assert_eq!(sanitize_github_query("android app"), "android app");
    }

    #[test]
    fn test_sanitize_github_query_handles_empty_string() {
        assert_eq!(sanitize_github_query(""), "");
    }

    #[test]
    fn test_sanitize_github_query_handles_only_operators() {
        assert_eq!(sanitize_github_query("repo:owner/repo"), "");
        assert_eq!(sanitize_github_query("repo:owner/repo stars:>100"), "");
    }

    #[test]
    fn test_sanitize_github_query_removes_multiple_operators() {
        assert_eq!(
            sanitize_github_query("test repo:evil stars:>100 language:rust"),
            "test"
        );
    }

    #[test]
    fn test_sanitize_github_query_preserves_colons_in_normal_text() {
        // Colons not part of operators should be preserved
        assert_eq!(sanitize_github_query("time 12:30"), "time 12:30");
        assert_eq!(sanitize_github_query("key:value"), "key:value");
    }

    #[test]
    fn test_github_skill_result_serialization() {
        let result = GitHubSkillResult {
            repo_url: "https://github.com/owner/repo".to_string(),
            skill_path: "skills/test/SKILL.md".to_string(),
            file_url: "https://github.com/owner/repo/blob/main/skills/test/SKILL.md".to_string(),
            description: Some("Test repo".to_string()),
            stars: 100,
            last_updated: "2024-01-01T00:00:00Z".to_string(),
            raw_url: Some(
                "https://raw.githubusercontent.com/owner/repo/HEAD/skills/test/SKILL.md"
                    .to_string(),
            ),
        };

        let json = serde_json::to_string(&result).unwrap();
        let deserialized: GitHubSkillResult = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.repo_url, result.repo_url);
        assert_eq!(deserialized.stars, 100);
        assert_eq!(deserialized.description, Some("Test repo".to_string()));
    }

    #[test]
    fn test_github_skill_result_with_none_description() {
        let result = GitHubSkillResult {
            repo_url: "https://github.com/owner/repo".to_string(),
            skill_path: "SKILL.md".to_string(),
            file_url: "https://github.com/owner/repo/blob/main/SKILL.md".to_string(),
            description: None,
            stars: 0,
            last_updated: "".to_string(),
            raw_url: None,
        };

        let json = serde_json::to_string(&result).unwrap();
        let deserialized: GitHubSkillResult = serde_json::from_str(&json).unwrap();

        assert!(deserialized.description.is_none());
        assert!(deserialized.raw_url.is_none());
    }
}

/// Property-based tests for sanitize_github_query using proptest.
/// These tests generate random inputs to find edge cases that manual tests might miss.
#[cfg(test)]
mod proptest_tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        /// Property: sanitize_github_query should never panic on any input.
        #[test]
        fn sanitize_never_panics(input in "\\PC*") {
            let _ = sanitize_github_query(&input);
        }

        /// Property: sanitize_github_query should never return a string longer than input.
        /// (We only remove content, never add)
        #[test]
        fn sanitize_never_increases_length(input in "\\PC*") {
            let result = sanitize_github_query(&input);
            prop_assert!(result.len() <= input.len());
        }

        /// Property: sanitize_github_query should always return valid UTF-8.
        /// In Rust, String is guaranteed valid UTF-8, so reaching here without panic proves validity.
        #[test]
        fn sanitize_returns_valid_utf8(input in "\\PC*") {
            let result = sanitize_github_query(&input);
            // Verify we can iterate chars (would panic on invalid UTF-8 if String were somehow corrupted)
            let char_count = result.chars().count();
            prop_assert!(char_count <= input.chars().count());
        }

        /// Property: If input has no operators, only whitespace normalization should occur.
        #[test]
        fn sanitize_preserves_safe_words(
            words in prop::collection::vec("[a-zA-Z0-9]+", 1..5)
        ) {
            let input = words.join(" ");
            let result = sanitize_github_query(&input);
            // Each word should appear in the result (unless it's a boolean operator)
            for word in &words {
                let is_boolean_op = ["NOT", "AND", "OR"]
                    .iter()
                    .any(|op| word.eq_ignore_ascii_case(op));
                if !is_boolean_op {
                    prop_assert!(
                        result.contains(word.as_str()),
                        "Word '{}' missing from result '{}'", word, result
                    );
                }
            }
        }

        /// Property: No colon operators should survive sanitization.
        #[test]
        fn sanitize_removes_all_colon_operators(
            prefix in "[a-zA-Z0-9 ]{0,20}",
            operator in prop::sample::select(vec![
                "repo:", "org:", "user:", "in:", "size:", "fork:", "forks:",
                "stars:", "topics:", "topic:", "created:", "pushed:", "updated:",
                "is:", "archived:", "license:", "language:", "filename:", "path:",
                "extension:"
            ]),
            value in "[a-zA-Z0-9/\\-><=]+",
            suffix in "[a-zA-Z0-9 ]{0,20}"
        ) {
            let input = format!("{} {}{} {}", prefix.trim(), operator, value, suffix.trim());
            let result = sanitize_github_query(&input);

            // The operator:value should be completely removed
            prop_assert!(
                !result.to_lowercase().contains(&operator.to_lowercase()),
                "Operator '{}' found in result '{}' (input: '{}')",
                operator, result, input
            );
        }

        /// Property: Standalone boolean operators should be removed.
        #[test]
        fn sanitize_removes_boolean_operators(
            prefix in "[a-z]{1,10}",
            boolean_op in prop::sample::select(vec!["AND", "OR", "NOT", "and", "or", "not"]),
            suffix in "[a-z]{1,10}"
        ) {
            let input = format!("{} {} {}", prefix, boolean_op, suffix);
            let result = sanitize_github_query(&input);

            // The result should contain prefix and suffix but not the boolean operator as standalone
            let words: Vec<&str> = result.split_whitespace().collect();
            let has_boolean = words.iter().any(|w| {
                w.eq_ignore_ascii_case("AND") || w.eq_ignore_ascii_case("OR") || w.eq_ignore_ascii_case("NOT")
            });
            prop_assert!(
                !has_boolean,
                "Boolean operator found in result '{}' (input: '{}')",
                result, input
            );
        }

        /// Property: Words containing boolean operator substrings should NOT be affected.
        /// E.g., "android", "Oregon", "annotation" should pass through.
        #[test]
        fn sanitize_preserves_words_with_operator_substrings(
            word in "(android|Oregon|annotation|manor|donor|canopy|mandate|bandana|panorama|grandma)"
        ) {
            let input = format!("test {}", word);
            let result = sanitize_github_query(&input);
            prop_assert!(
                result.contains(&word),
                "Word '{}' should be preserved in result '{}'",
                word, result
            );
        }

        /// Property: Empty and whitespace-only inputs should return empty string.
        #[test]
        fn sanitize_handles_whitespace_only(spaces in "[ \t\n\r]*") {
            let result = sanitize_github_query(&spaces);
            prop_assert!(
                result.is_empty(),
                "Whitespace-only input should produce empty result, got '{}'",
                result
            );
        }
    }
}

/// Integration tests using wiremock for HTTP mocking.
/// These tests verify the actual HTTP behavior of the GitHub search functions.
#[cfg(test)]
mod integration_tests {
    use super::*;
    use crate::test_support::set_env_var;
    use serde_json::json;
    use serial_test::serial;
    use wiremock::matchers::{method, path, query_param_contains};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    #[serial]
    async fn test_search_github_skills_success() {
        let server = MockServer::start().await;

        let _api_guard = set_env_var("GITHUB_API_BASE_URL", Some(&server.uri()));
        let _token_guard = set_env_var("GITHUB_TOKEN", None);

        let mock_response = json!({
            "items": [
                {
                    "path": "skills/testing/SKILL.md",
                    "html_url": "https://github.com/owner/repo/blob/main/skills/testing/SKILL.md",
                    "repository": {
                        "full_name": "owner/repo",
                        "html_url": "https://github.com/owner/repo",
                        "stargazers_count": 42,
                        "updated_at": "2024-06-15T10:00:00Z",
                        "description": "A test repository"
                    }
                },
                {
                    "path": "SKILL.md",
                    "html_url": "https://github.com/another/project/blob/main/SKILL.md",
                    "repository": {
                        "full_name": "another/project",
                        "html_url": "https://github.com/another/project",
                        "stargazers_count": 100,
                        "updated_at": "2024-07-20T15:30:00Z",
                        "description": null
                    }
                }
            ]
        });

        Mock::given(method("GET"))
            .and(path("/search/code"))
            .and(query_param_contains("q", "testing"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
            .mount(&server)
            .await;

        let results = search_github_skills("testing", 10).await.unwrap();

        assert_eq!(results.len(), 2);

        // First result
        assert_eq!(results[0].repo_url, "https://github.com/owner/repo");
        assert_eq!(results[0].skill_path, "skills/testing/SKILL.md");
        assert_eq!(results[0].stars, 42);
        assert_eq!(
            results[0].description,
            Some("A test repository".to_string())
        );
        assert!(results[0].raw_url.is_some());

        // Second result
        assert_eq!(results[1].repo_url, "https://github.com/another/project");
        assert_eq!(results[1].skill_path, "SKILL.md");
        assert_eq!(results[1].stars, 100);
        assert!(results[1].description.is_none());
    }

    #[tokio::test]
    #[serial]
    async fn test_search_github_skills_empty_results() {
        let server = MockServer::start().await;

        let _api_guard = set_env_var("GITHUB_API_BASE_URL", Some(&server.uri()));
        let _token_guard = set_env_var("GITHUB_TOKEN", None);

        let mock_response = json!({
            "items": []
        });

        Mock::given(method("GET"))
            .and(path("/search/code"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
            .mount(&server)
            .await;

        let results = search_github_skills("nonexistent", 10).await.unwrap();

        assert!(results.is_empty());
    }

    #[tokio::test]
    #[serial]
    async fn test_search_github_skills_rate_limit_error() {
        let server = MockServer::start().await;

        let _api_guard = set_env_var("GITHUB_API_BASE_URL", Some(&server.uri()));
        let _token_guard = set_env_var("GITHUB_TOKEN", None);

        Mock::given(method("GET"))
            .and(path("/search/code"))
            .respond_with(ResponseTemplate::new(403).set_body_json(json!({
                "message": "API rate limit exceeded for IP"
            })))
            .mount(&server)
            .await;

        let result = search_github_skills("testing", 10).await;

        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("rate limit") || error_msg.contains("403"),
            "Expected rate limit error, got: {}",
            error_msg
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_search_github_skills_auth_error() {
        let server = MockServer::start().await;

        let _api_guard = set_env_var("GITHUB_API_BASE_URL", Some(&server.uri()));
        let _token_guard = set_env_var("GITHUB_TOKEN", Some("invalid-token"));

        Mock::given(method("GET"))
            .and(path("/search/code"))
            .respond_with(ResponseTemplate::new(401).set_body_json(json!({
                "message": "Bad credentials"
            })))
            .mount(&server)
            .await;

        let result = search_github_skills("testing", 10).await;

        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("authentication") || error_msg.contains("401"),
            "Expected auth error, got: {}",
            error_msg
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_search_github_skills_invalid_query_error() {
        let server = MockServer::start().await;

        let _api_guard = set_env_var("GITHUB_API_BASE_URL", Some(&server.uri()));
        let _token_guard = set_env_var("GITHUB_TOKEN", None);

        Mock::given(method("GET"))
            .and(path("/search/code"))
            .respond_with(ResponseTemplate::new(422).set_body_json(json!({
                "message": "Validation Failed"
            })))
            .mount(&server)
            .await;

        let result = search_github_skills("", 10).await;

        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("invalid") || error_msg.contains("422"),
            "Expected validation error, got: {}",
            error_msg
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_search_github_skills_server_error() {
        let server = MockServer::start().await;

        let _api_guard = set_env_var("GITHUB_API_BASE_URL", Some(&server.uri()));
        let _token_guard = set_env_var("GITHUB_TOKEN", None);

        Mock::given(method("GET"))
            .and(path("/search/code"))
            .respond_with(ResponseTemplate::new(500).set_body_json(json!({
                "message": "Internal Server Error"
            })))
            .mount(&server)
            .await;

        let result = search_github_skills("testing", 10).await;

        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("500") || error_msg.contains("error"),
            "Expected server error, got: {}",
            error_msg
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_fetch_skill_content_success() {
        let server = MockServer::start().await;
        let _token_guard = set_env_var("GITHUB_TOKEN", None);

        let skill_content = r#"---
description: Test skill
triggers:
  - test
---
# Test Skill

This is a test skill."#;

        Mock::given(method("GET"))
            .and(path("/owner/repo/HEAD/SKILL.md"))
            .respond_with(ResponseTemplate::new(200).set_body_string(skill_content))
            .mount(&server)
            .await;

        let url = format!("{}/owner/repo/HEAD/SKILL.md", server.uri());
        let content = fetch_skill_content(&url).await.unwrap();

        assert!(content.contains("Test skill"));
        assert!(content.contains("This is a test skill"));
    }

    #[tokio::test]
    #[serial]
    async fn test_fetch_skill_content_not_found() {
        let server = MockServer::start().await;
        let _token_guard = set_env_var("GITHUB_TOKEN", None);

        Mock::given(method("GET"))
            .and(path("/owner/repo/HEAD/SKILL.md"))
            .respond_with(ResponseTemplate::new(404))
            .mount(&server)
            .await;

        let url = format!("{}/owner/repo/HEAD/SKILL.md", server.uri());
        let result = fetch_skill_content(&url).await;

        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("404") || error_msg.contains("Failed"),
            "Expected not found error, got: {}",
            error_msg
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_search_skills_advanced_with_language_filter() {
        let server = MockServer::start().await;

        let _api_guard = set_env_var("GITHUB_API_BASE_URL", Some(&server.uri()));
        let _token_guard = set_env_var("GITHUB_TOKEN", None);

        let mock_response = json!({
            "items": [
                {
                    "path": "SKILL.md",
                    "html_url": "https://github.com/rust-project/skills/blob/main/SKILL.md",
                    "repository": {
                        "full_name": "rust-project/skills",
                        "html_url": "https://github.com/rust-project/skills",
                        "stargazers_count": 50,
                        "updated_at": "2024-08-01T00:00:00Z",
                        "description": "Rust skills"
                    }
                }
            ]
        });

        Mock::given(method("GET"))
            .and(path("/search/code"))
            .and(query_param_contains("q", "language:rust"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
            .mount(&server)
            .await;

        let keywords = vec!["async".to_string()];
        let results = search_skills_advanced(&keywords, Some("rust"), None, 10)
            .await
            .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(
            results[0].repo_url,
            "https://github.com/rust-project/skills"
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_search_skills_advanced_with_stars_filter() {
        let server = MockServer::start().await;

        let _api_guard = set_env_var("GITHUB_API_BASE_URL", Some(&server.uri()));
        let _token_guard = set_env_var("GITHUB_TOKEN", None);

        let mock_response = json!({
            "items": [
                {
                    "path": "SKILL.md",
                    "html_url": "https://github.com/popular/repo/blob/main/SKILL.md",
                    "repository": {
                        "full_name": "popular/repo",
                        "html_url": "https://github.com/popular/repo",
                        "stargazers_count": 1500,
                        "updated_at": "2024-08-01T00:00:00Z",
                        "description": "Popular repo"
                    }
                }
            ]
        });

        Mock::given(method("GET"))
            .and(path("/search/code"))
            .and(query_param_contains("q", "stars:>=100"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
            .mount(&server)
            .await;

        let keywords = vec!["testing".to_string()];
        let results = search_skills_advanced(&keywords, None, Some(100), 10)
            .await
            .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].stars, 1500);
    }

    #[tokio::test]
    #[serial]
    async fn test_search_github_skills_sanitizes_input() {
        let server = MockServer::start().await;

        let _api_guard = set_env_var("GITHUB_API_BASE_URL", Some(&server.uri()));
        let _token_guard = set_env_var("GITHUB_TOKEN", None);

        let mock_response = json!({
            "items": []
        });

        // The mock should receive a sanitized query without the injected operators
        Mock::given(method("GET"))
            .and(path("/search/code"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
            .mount(&server)
            .await;

        // Try to inject operators - they should be sanitized
        let result = search_github_skills("test repo:evil/repo stars:>10000", 10).await;

        result.expect("search with sanitized injected operators should succeed");
    }

    #[tokio::test]
    #[serial]
    async fn test_search_github_skills_uses_auth_header_when_token_present() {
        let server = MockServer::start().await;

        let _api_guard = set_env_var("GITHUB_API_BASE_URL", Some(&server.uri()));
        let _token_guard = set_env_var("GITHUB_TOKEN", Some("test-github-token"));

        let mock_response = json!({
            "items": []
        });

        // Verify the auth header is included
        Mock::given(method("GET"))
            .and(path("/search/code"))
            .and(wiremock::matchers::header(
                "Authorization",
                "Bearer test-github-token",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
            .expect(1)
            .mount(&server)
            .await;

        let result = search_github_skills("testing", 10).await;
        result.expect("search with auth header should succeed");
    }

    #[tokio::test]
    #[serial]
    async fn test_search_github_skills_handles_forbidden_non_rate_limit() {
        let server = MockServer::start().await;

        let _api_guard = set_env_var("GITHUB_API_BASE_URL", Some(&server.uri()));
        let _token_guard = set_env_var("GITHUB_TOKEN", None);

        // 403 without rate limit message
        Mock::given(method("GET"))
            .and(path("/search/code"))
            .respond_with(ResponseTemplate::new(403).set_body_json(json!({
                "message": "Repository access blocked"
            })))
            .mount(&server)
            .await;

        let result = search_github_skills("testing", 10).await;

        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("forbidden")
                || error_msg.contains("403")
                || error_msg.contains("permission"),
            "Expected forbidden error, got: {}",
            error_msg
        );
    }
}