stax 0.29.4

Fast stacked Git branches and PRs
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
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use octocrab::params::repos::Reference;
use octocrab::service::middleware::retry::RetryConfig;
use octocrab::Octocrab;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use crate::config::Config;

const GITHUB_API_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const GITHUB_API_READ_TIMEOUT: Duration = Duration::from_secs(30);
const GITHUB_API_WRITE_TIMEOUT: Duration = Duration::from_secs(30);
const GITHUB_API_RETRY_COUNT: usize = 1;

pub struct GitHubClient {
    pub octocrab: Octocrab,
    pub owner: String,
    pub repo: String,
    api_call_tracker: Arc<ApiCallTracker>,
}

impl Clone for GitHubClient {
    fn clone(&self) -> Self {
        // Note: Octocrab doesn't implement Clone, so we create a minimal placeholder
        // This is only used in tests where we create fresh clients anyway
        Self {
            octocrab: self.octocrab.clone(),
            owner: self.owner.clone(),
            repo: self.repo.clone(),
            api_call_tracker: self.api_call_tracker.clone(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct ApiCallStats {
    pub total_requests: usize,
    pub by_operation: Vec<(String, usize)>,
}

#[derive(Default)]
struct ApiCallTracker {
    total_requests: AtomicUsize,
    by_operation: Mutex<BTreeMap<String, usize>>,
}

impl ApiCallTracker {
    fn record(&self, operation: &'static str, count: usize) {
        if count == 0 {
            return;
        }

        self.total_requests.fetch_add(count, Ordering::Relaxed);
        let mut by_operation = self.by_operation.lock().unwrap_or_else(|e| e.into_inner());
        *by_operation.entry(operation.to_string()).or_insert(0) += count;
    }

    fn snapshot(&self) -> ApiCallStats {
        let by_operation = self
            .by_operation
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .iter()
            .map(|(operation, count)| (operation.clone(), *count))
            .collect();

        ApiCallStats {
            total_requests: self.total_requests.load(Ordering::Relaxed),
            by_operation,
        }
    }
}

/// Response from the check-runs API
#[derive(Debug, Deserialize)]
struct CheckRunsResponse {
    total_count: usize,
    check_runs: Vec<CheckRun>,
}

#[derive(Debug, Deserialize)]
struct CheckRun {
    status: String,
    conclusion: Option<String>,
}

/// PR activity for standup reports
#[derive(Debug, Clone, Serialize)]
pub struct PrActivity {
    pub number: u64,
    pub title: String,
    pub timestamp: DateTime<Utc>,
    pub url: String,
}

/// Review activity for standup reports
#[derive(Debug, Clone, Serialize)]
pub struct ReviewActivity {
    pub pr_number: u64,
    pub pr_title: String,
    pub reviewer: String,
    pub state: String,
    pub timestamp: DateTime<Utc>,
    pub is_received: bool, // true = received on your PR, false = given by you
}

/// Open PR info for tracking command
#[derive(Debug, Clone)]
pub struct OpenPrInfo {
    pub number: u64,
    pub head_branch: String,
    pub base_branch: String,
    pub state: String,
    pub is_draft: bool,
}

#[derive(Debug, Deserialize)]
struct ReviewUser {
    login: String,
}

/// Response from GitHub reviews API
#[derive(Debug, Deserialize)]
struct Review {
    state: String,
    submitted_at: Option<DateTime<Utc>>,
    user: Option<ReviewUser>,
}

/// Response from GitHub search issues API
#[derive(Debug, Deserialize)]
struct SearchIssuesResponse {
    items: Vec<SearchIssue>,
}

#[derive(Debug, Deserialize)]
struct SearchIssue {
    number: u64,
    title: String,
    html_url: String,
    created_at: DateTime<Utc>,
    closed_at: Option<DateTime<Utc>>,
}

impl GitHubClient {
    /// Create a new GitHub client from config
    pub fn new(owner: &str, repo: &str, api_base_url: Option<String>) -> Result<Self> {
        let token = Config::github_token().context(
            "GitHub auth not configured. Use one of: `stax auth`, `stax auth --from-gh`, \
             `gh auth login`, or set `STAX_GITHUB_TOKEN`.",
        )?;

        let mut builder = Octocrab::builder()
            .personal_token(token.to_string())
            .add_retry_config(RetryConfig::Simple(GITHUB_API_RETRY_COUNT))
            .set_connect_timeout(Some(GITHUB_API_CONNECT_TIMEOUT))
            .set_read_timeout(Some(GITHUB_API_READ_TIMEOUT))
            .set_write_timeout(Some(GITHUB_API_WRITE_TIMEOUT));
        if let Some(api_base) = api_base_url {
            builder = builder
                .base_uri(api_base)
                .context("Failed to set GitHub API base URL")?;
        }

        let octocrab = builder.build().context("Failed to create GitHub client")?;

        Ok(Self {
            octocrab,
            owner: owner.to_string(),
            repo: repo.to_string(),
            api_call_tracker: Arc::new(ApiCallTracker::default()),
        })
    }

    /// Create a new GitHub client with a custom Octocrab instance (for testing)
    #[cfg(test)]
    pub fn with_octocrab(octocrab: Octocrab, owner: &str, repo: &str) -> Self {
        Self {
            octocrab,
            owner: owner.to_string(),
            repo: repo.to_string(),
            api_call_tracker: Arc::new(ApiCallTracker::default()),
        }
    }

    pub fn api_call_stats(&self) -> ApiCallStats {
        self.api_call_tracker.snapshot()
    }

    pub(crate) fn record_api_call(&self, operation: &'static str) {
        self.api_call_tracker.record(operation, 1);
    }

    /// Get combined CI status from both commit statuses AND check runs (GitHub Actions)
    pub async fn combined_status_state(&self, commit_sha: &str) -> Result<Option<String>> {
        // First, check legacy commit statuses
        let commit_status = self
            .octocrab
            .repos(&self.owner, &self.repo)
            .combined_status_for_ref(&Reference::Branch(commit_sha.to_string()))
            .await
            .ok();

        // Then, check GitHub Actions check runs
        let check_runs_status = self.get_check_runs_status(commit_sha).await.ok().flatten();

        // Combine results: prioritize check runs (more common), fall back to commit status
        match (check_runs_status, commit_status) {
            // If we have check runs, use that status
            (Some(cr_status), _) => Ok(Some(cr_status)),
            // Fall back to commit status
            (None, Some(status)) => Ok(Some(format!("{:?}", status.state).to_lowercase())),
            // No CI at all
            (None, None) => Ok(None),
        }
    }

    /// Get status from GitHub Actions check runs
    async fn get_check_runs_status(&self, commit_sha: &str) -> Result<Option<String>> {
        let url = format!(
            "/repos/{}/{}/commits/{}/check-runs",
            self.owner, self.repo, commit_sha
        );

        let response: CheckRunsResponse = self.octocrab.get(&url, None::<&()>).await?;

        if response.total_count == 0 {
            return Ok(None); // No check runs configured
        }

        // Analyze all check runs to determine overall status
        let mut has_pending = false;
        let mut has_failure = false;
        let mut all_success = true;

        for run in &response.check_runs {
            match run.status.as_str() {
                "completed" => match run.conclusion.as_deref() {
                    Some("success") | Some("skipped") | Some("neutral") => {}
                    Some("failure")
                    | Some("timed_out")
                    | Some("cancelled")
                    | Some("action_required") => {
                        has_failure = true;
                        all_success = false;
                    }
                    _ => {
                        all_success = false;
                    }
                },
                "queued" | "in_progress" | "waiting" | "requested" | "pending" => {
                    has_pending = true;
                    all_success = false;
                }
                _ => {
                    all_success = false;
                }
            }
        }

        if has_failure {
            Ok(Some("failure".to_string()))
        } else if has_pending {
            Ok(Some("pending".to_string()))
        } else if all_success {
            Ok(Some("success".to_string()))
        } else {
            Ok(Some("pending".to_string())) // Unknown state, treat as pending
        }
    }

    /// Get the authenticated user's login name
    pub async fn get_current_user(&self) -> Result<String> {
        let user = self.octocrab.current().user().await?;
        Ok(user.login)
    }

    /// Get PRs merged by the user in the last N hours
    pub async fn get_recent_merged_prs(
        &self,
        hours: i64,
        username: &str,
    ) -> Result<Vec<PrActivity>> {
        let since = Utc::now() - chrono::Duration::hours(hours);
        // Use search API to find only user's merged PRs - much faster than listing all
        let url = format!(
            "/search/issues?q=repo:{}/{}+author:{}+is:pr+is:merged&sort=updated&order=desc&per_page=30",
            self.owner, self.repo, username
        );

        let response: SearchIssuesResponse = self.octocrab.get(&url, None::<&()>).await?;

        let merged: Vec<PrActivity> = response
            .items
            .into_iter()
            .filter_map(|issue| {
                let closed_at = issue.closed_at?;
                // Filter by time locally (more reliable than URL date filters)
                if closed_at < since {
                    return None;
                }
                Some(PrActivity {
                    number: issue.number,
                    title: issue.title,
                    timestamp: closed_at,
                    url: issue.html_url,
                })
            })
            .collect();

        Ok(merged)
    }

    /// Get PRs opened by the user in the last N hours
    pub async fn get_recent_opened_prs(
        &self,
        hours: i64,
        username: &str,
    ) -> Result<Vec<PrActivity>> {
        let since = Utc::now() - chrono::Duration::hours(hours);
        // Use search API to find only user's created PRs
        let url = format!(
            "/search/issues?q=repo:{}/{}+author:{}+is:pr&sort=created&order=desc&per_page=30",
            self.owner, self.repo, username
        );

        let response: SearchIssuesResponse = self.octocrab.get(&url, None::<&()>).await?;

        let opened: Vec<PrActivity> = response
            .items
            .into_iter()
            .filter(|issue| issue.created_at >= since)
            .map(|issue| PrActivity {
                number: issue.number,
                title: issue.title,
                timestamp: issue.created_at,
                url: issue.html_url,
            })
            .collect();

        Ok(opened)
    }

    /// Get reviews received on user's open PRs in the last N hours
    /// Only fetches user's own PRs to keep it fast
    pub async fn get_reviews_received(
        &self,
        hours: i64,
        username: &str,
    ) -> Result<Vec<ReviewActivity>> {
        let since = Utc::now() - chrono::Duration::hours(hours);

        // Use search to get only user's open PRs (fast)
        let url = format!(
            "/search/issues?q=repo:{}/{}+author:{}+is:pr+is:open&per_page=20",
            self.owner, self.repo, username
        );
        let response: SearchIssuesResponse = self.octocrab.get(&url, None::<&()>).await?;

        let mut reviews = Vec::new();

        // Only check reviews on user's own PRs (small list, few API calls)
        for issue in response.items {
            let reviews_url = format!(
                "/repos/{}/{}/pulls/{}/reviews",
                self.owner, self.repo, issue.number
            );
            let pr_reviews: Vec<Review> = self
                .octocrab
                .get(&reviews_url, None::<&()>)
                .await
                .unwrap_or_default();

            for review in pr_reviews {
                if let Some(submitted) = review.submitted_at {
                    if submitted >= since {
                        if let Some(reviewer) = review.user {
                            // Don't include self-reviews
                            if reviewer.login != username {
                                reviews.push(ReviewActivity {
                                    pr_number: issue.number,
                                    pr_title: issue.title.clone(),
                                    reviewer: reviewer.login,
                                    state: review.state,
                                    timestamp: submitted,
                                    is_received: true,
                                });
                            }
                        }
                    }
                }
            }
        }

        Ok(reviews)
    }

    /// Get reviews given by user on others' PRs in the last N hours
    /// Note: This is expensive for large repos, returns empty to keep standup fast
    pub async fn get_reviews_given(
        &self,
        _hours: i64,
        _username: &str,
    ) -> Result<Vec<ReviewActivity>> {
        // Skip for now - scanning all PRs is too slow for large repos
        // Could be implemented with GitHub's GraphQL API in the future
        Ok(vec![])
    }

    /// Get all open PRs authored by the given user
    /// Uses Search API for efficient server-side filtering
    pub async fn get_user_open_prs(&self, username: &str) -> Result<Vec<OpenPrInfo>> {
        // Use search API to efficiently find user's open PRs
        let url = format!(
            "/search/issues?q=repo:{}/{}+author:{}+is:pr+is:open&per_page=100",
            self.owner, self.repo, username
        );

        let response: SearchIssuesResponse = self
            .octocrab
            .get(&url, None::<&()>)
            .await
            .context("Failed to search PRs")?;

        // For each PR from search, we need to get the branch info
        // Search API doesn't include head/base branch refs, so we fetch each PR
        let mut results = Vec::new();
        for issue in response.items {
            // Fetch full PR details to get branch info
            let pr = self
                .octocrab
                .pulls(&self.owner, &self.repo)
                .get(issue.number)
                .await;

            if let Ok(pr) = pr {
                results.push(OpenPrInfo {
                    number: pr.number,
                    head_branch: pr.head.ref_field.clone(),
                    base_branch: pr.base.ref_field.clone(),
                    state: "OPEN".to_string(),
                    is_draft: pr.draft.unwrap_or(false),
                });
            }
        }

        Ok(results)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    async fn create_test_client(server: &MockServer) -> GitHubClient {
        let octocrab = Octocrab::builder()
            .base_uri(server.uri())
            .unwrap()
            .personal_token("test-token".to_string())
            .build()
            .unwrap();

        GitHubClient::with_octocrab(octocrab, "test-owner", "test-repo")
    }

    #[tokio::test]
    async fn test_check_runs_all_success() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 2,
                "check_runs": [
                    {"status": "completed", "conclusion": "success"},
                    {"status": "completed", "conclusion": "success"}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        assert_eq!(status, Some("success".to_string()));
    }

    #[tokio::test]
    async fn test_check_runs_with_failure() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 3,
                "check_runs": [
                    {"status": "completed", "conclusion": "success"},
                    {"status": "completed", "conclusion": "failure"},
                    {"status": "completed", "conclusion": "success"}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        assert_eq!(status, Some("failure".to_string()));
    }

    #[tokio::test]
    async fn test_check_runs_with_pending() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 2,
                "check_runs": [
                    {"status": "completed", "conclusion": "success"},
                    {"status": "in_progress", "conclusion": null}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        assert_eq!(status, Some("pending".to_string()));
    }

    #[tokio::test]
    async fn test_check_runs_queued() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 1,
                "check_runs": [
                    {"status": "queued", "conclusion": null}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        assert_eq!(status, Some("pending".to_string()));
    }

    #[tokio::test]
    async fn test_check_runs_waiting() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 1,
                "check_runs": [
                    {"status": "waiting", "conclusion": null}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        assert_eq!(status, Some("pending".to_string()));
    }

    #[tokio::test]
    async fn test_check_runs_no_checks() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 0,
                "check_runs": []
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        assert_eq!(status, None);
    }

    #[tokio::test]
    async fn test_check_runs_skipped_and_neutral() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 3,
                "check_runs": [
                    {"status": "completed", "conclusion": "success"},
                    {"status": "completed", "conclusion": "skipped"},
                    {"status": "completed", "conclusion": "neutral"}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        assert_eq!(status, Some("success".to_string()));
    }

    #[tokio::test]
    async fn test_check_runs_timed_out() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 1,
                "check_runs": [
                    {"status": "completed", "conclusion": "timed_out"}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        assert_eq!(status, Some("failure".to_string()));
    }

    #[tokio::test]
    async fn test_check_runs_cancelled() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 1,
                "check_runs": [
                    {"status": "completed", "conclusion": "cancelled"}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        assert_eq!(status, Some("failure".to_string()));
    }

    #[tokio::test]
    async fn test_check_runs_action_required() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 1,
                "check_runs": [
                    {"status": "completed", "conclusion": "action_required"}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        assert_eq!(status, Some("failure".to_string()));
    }

    #[tokio::test]
    async fn test_check_runs_unknown_conclusion() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 1,
                "check_runs": [
                    {"status": "completed", "conclusion": "unknown_state"}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        // Unknown conclusion treated as not all_success, but not failure or pending
        assert_eq!(status, Some("pending".to_string()));
    }

    #[tokio::test]
    async fn test_check_runs_unknown_status() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 1,
                "check_runs": [
                    {"status": "some_unknown_status", "conclusion": null}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        // Unknown status treated as pending
        assert_eq!(status, Some("pending".to_string()));
    }

    #[tokio::test]
    async fn test_check_runs_requested_status() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 1,
                "check_runs": [
                    {"status": "requested", "conclusion": null}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        assert_eq!(status, Some("pending".to_string()));
    }

    #[tokio::test]
    async fn test_check_runs_pending_status() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path(
                "/repos/test-owner/test-repo/commits/abc123/check-runs",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "total_count": 1,
                "check_runs": [
                    {"status": "pending", "conclusion": null}
                ]
            })))
            .mount(&mock_server)
            .await;

        let client = create_test_client(&mock_server).await;
        let status = client.get_check_runs_status("abc123").await.unwrap();
        assert_eq!(status, Some("pending".to_string()));
    }

    #[tokio::test]
    async fn test_with_octocrab() {
        let mock_server = MockServer::start().await;

        let octocrab = Octocrab::builder()
            .base_uri(mock_server.uri())
            .unwrap()
            .personal_token("test-token".to_string())
            .build()
            .unwrap();

        let client = GitHubClient::with_octocrab(octocrab, "owner", "repo");
        assert_eq!(client.owner, "owner");
        assert_eq!(client.repo, "repo");
    }

    #[test]
    fn test_check_run_response_deserialization() {
        let json = r#"{
            "total_count": 2,
            "check_runs": [
                {"status": "completed", "conclusion": "success"},
                {"status": "in_progress", "conclusion": null}
            ]
        }"#;

        let response: CheckRunsResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.total_count, 2);
        assert_eq!(response.check_runs.len(), 2);
        assert_eq!(response.check_runs[0].status, "completed");
        assert_eq!(
            response.check_runs[0].conclusion,
            Some("success".to_string())
        );
        assert_eq!(response.check_runs[1].status, "in_progress");
        assert_eq!(response.check_runs[1].conclusion, None);
    }

    #[test]
    fn test_check_run_deserialization() {
        let json = r#"{"status": "completed", "conclusion": "failure"}"#;
        let check_run: CheckRun = serde_json::from_str(json).unwrap();
        assert_eq!(check_run.status, "completed");
        assert_eq!(check_run.conclusion, Some("failure".to_string()));
    }

    #[test]
    fn test_github_client_clone() {
        // This test just verifies Clone is implemented
        // We can't actually test it without a mock server setup
    }
}