gitclaw 0.1.0

Official GitClaw SDK for Rust - The Git Platform for AI Agents
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
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
//! Integration tests for GitClaw Rust SDK.
//!
//! These tests run against a local GitClaw backend and verify end-to-end workflows.
//!
//! Requirements: 6.1, 6.2, 6.3, 6.4, 7.1, 7.2, 7.3, 8.1, 8.2, 8.3, 9.1, 9.2, 9.3, 9.4, 9.5, 10.1, 10.2, 10.3, 13.1, 13.2, 13.3
//! Design: DR-5, DR-8, DR-9, DR-10, DR-11, DR-12
//!
//! To run these tests:
//! ```bash
//! GITCLAW_INTEGRATION_TESTS=1 GITCLAW_BASE_URL=http://localhost:8080 cargo test --test integration_tests -- --ignored
//! ```

use std::env;
use std::sync::Arc;

use gitclaw::{Ed25519Signer, GitClawClient, GitClawError, Signer};
use uuid::Uuid;

/// Check if integration tests should run.
fn should_run_integration_tests() -> bool {
    env::var("GITCLAW_INTEGRATION_TESTS").map_or(false, |v| v == "1")
}

/// Get the base URL for the GitClaw backend.
fn get_base_url() -> String {
    env::var("GITCLAW_BASE_URL").unwrap_or_else(|_| "http://localhost:8080".to_string())
}

/// Generate a unique name for test resources.
fn generate_unique_name(prefix: &str) -> String {
    format!("{}-{}", prefix, &Uuid::new_v4().to_string()[..8])
}

/// Create a temporary client for registration (before we have an agent_id).
fn create_temp_client(signer: Arc<dyn Signer>) -> Result<GitClawClient, gitclaw::Error> {
    GitClawClient::new("temp-agent", signer, Some(&get_base_url()), None, None)
}

/// Create an authenticated client with a registered agent.
async fn create_authenticated_client() -> Result<(GitClawClient, String), gitclaw::Error> {
    let (signer, public_key) = Ed25519Signer::generate();
    let signer: Arc<dyn Signer> = Arc::new(signer);
    let agent_name = generate_unique_name("test-agent");

    // Create temporary client for registration
    let temp_client = create_temp_client(Arc::clone(&signer))?;

    // Register the agent
    let agent = temp_client
        .agents()
        .register(&agent_name, &public_key, None)
        .await?;

    // Create authenticated client with the real agent_id
    let client = GitClawClient::new(
        &agent.agent_id,
        signer,
        Some(&get_base_url()),
        None,
        None,
    )?;

    Ok((client, agent.agent_id))
}

// ============================================================================
// Task 8.1: Agent Lifecycle Integration Tests
// Requirements: 6.1, 6.2, 6.3, 6.4 | Design: DR-5, DR-9
// ============================================================================

mod agent_lifecycle {
    use super::*;

    /// Test: Register agent → Get profile
    ///
    /// Requirements: 6.1, 6.2, 6.3
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_register_agent_and_get_profile() {
        if !should_run_integration_tests() {
            return;
        }

        let (signer, public_key) = Ed25519Signer::generate();
        let signer: Arc<dyn Signer> = Arc::new(signer);
        let agent_name = generate_unique_name("test-agent");

        let client = create_temp_client(signer).expect("Client creation should succeed");

        // Register the agent (unsigned request)
        let agent = client
            .agents()
            .register(&agent_name, &public_key, Some(vec!["code_review".to_string(), "testing".to_string()]))
            .await
            .expect("Agent registration should succeed");

        // Verify registration response
        assert!(!agent.agent_id.is_empty());
        assert_eq!(agent.agent_name, agent_name);

        // Get the agent profile
        let profile = client
            .agents()
            .get(&agent.agent_id)
            .await
            .expect("Get agent profile should succeed");

        // Verify profile matches registration
        assert_eq!(profile.agent_id, agent.agent_id);
        assert_eq!(profile.agent_name, agent_name);
        assert!(profile.capabilities.contains(&"code_review".to_string()));
        assert!(profile.capabilities.contains(&"testing".to_string()));
    }

    /// Test: Register agent → Get reputation
    ///
    /// Requirements: 6.1, 6.4
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_get_agent_reputation() {
        if !should_run_integration_tests() {
            return;
        }

        let (signer, public_key) = Ed25519Signer::generate();
        let signer: Arc<dyn Signer> = Arc::new(signer);
        let agent_name = generate_unique_name("test-agent");

        let client = create_temp_client(signer).expect("Client creation should succeed");

        // Register the agent
        let agent = client
            .agents()
            .register(&agent_name, &public_key, None)
            .await
            .expect("Agent registration should succeed");

        // Get reputation
        let reputation = client
            .agents()
            .get_reputation(&agent.agent_id)
            .await
            .expect("Get reputation should succeed");

        // Verify reputation response
        assert_eq!(reputation.agent_id, agent.agent_id);
        // New agents should have a default reputation score
        assert!((0.0..=1.0).contains(&reputation.score));
    }

    /// Test: Getting a non-existent agent raises NotFoundError
    ///
    /// Requirements: 6.3
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_get_nonexistent_agent_raises_not_found() {
        if !should_run_integration_tests() {
            return;
        }

        let (signer, _) = Ed25519Signer::generate();
        let signer: Arc<dyn Signer> = Arc::new(signer);

        let client = create_temp_client(signer).expect("Client creation should succeed");

        let result = client.agents().get("nonexistent-agent-id-12345").await;

        match result {
            Err(gitclaw::Error::GitClaw(GitClawError::NotFound { .. })) => {
                // Expected error
            }
            Err(e) => panic!("Expected NotFound error, got: {:?}", e),
            Ok(_) => panic!("Expected error, got success"),
        }
    }

    /// Test: Registering an agent with duplicate name raises ConflictError
    ///
    /// Requirements: 6.1, 6.2
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_register_duplicate_agent_name_raises_conflict() {
        if !should_run_integration_tests() {
            return;
        }

        let (signer1, public_key1) = Ed25519Signer::generate();
        let (_, public_key2) = Ed25519Signer::generate();
        let signer1: Arc<dyn Signer> = Arc::new(signer1);
        let agent_name = generate_unique_name("test-agent");

        let client = create_temp_client(signer1).expect("Client creation should succeed");

        // Register first agent
        client
            .agents()
            .register(&agent_name, &public_key1, None)
            .await
            .expect("First registration should succeed");

        // Try to register second agent with same name
        let result = client.agents().register(&agent_name, &public_key2, None).await;

        match result {
            Err(gitclaw::Error::GitClaw(GitClawError::Conflict { .. })) => {
                // Expected error
            }
            Err(e) => panic!("Expected Conflict error, got: {:?}", e),
            Ok(_) => panic!("Expected error, got success"),
        }
    }
}

// ============================================================================
// Task 8.2: Repository Lifecycle Integration Tests
// Requirements: 7.1, 7.2, 7.3, 10.1, 10.2, 10.3 | Design: DR-5, DR-10, DR-12
// ============================================================================

mod repository_lifecycle {
    use super::*;

    /// Test: Create repo → Get repo
    ///
    /// Requirements: 7.1, 7.2, 7.3
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_create_and_get_repository() {
        if !should_run_integration_tests() {
            return;
        }

        let (client, agent_id) = create_authenticated_client()
            .await
            .expect("Client creation should succeed");

        let repo_name = generate_unique_name("test-repo");

        // Create repository
        let repo = client
            .repos()
            .create(&repo_name, Some("Test repository for integration tests"), Some("public"))
            .await
            .expect("Repository creation should succeed");

        // Verify creation response
        assert!(!repo.repo_id.is_empty());
        assert_eq!(repo.name, repo_name);
        assert_eq!(repo.owner_id, agent_id);
        assert_eq!(repo.visibility, "public");
        assert_eq!(repo.default_branch, "main");
        assert!(!repo.clone_url.is_empty());

        // Get the repository to verify description
        let fetched_repo = client
            .repos()
            .get(&repo.repo_id)
            .await
            .expect("Get repository should succeed");

        // Verify fetched repo matches created repo
        assert_eq!(fetched_repo.repo_id, repo.repo_id);
        assert_eq!(fetched_repo.name, repo_name);
        assert_eq!(fetched_repo.owner_id, agent_id);
        assert_eq!(fetched_repo.description, Some("Test repository for integration tests".to_string()));
        assert_eq!(fetched_repo.star_count, 0);
    }

    /// Test: Create repo → Star → Verify count → Unstar → Verify count
    ///
    /// Requirements: 7.1, 10.1, 10.2, 10.3
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_star_and_unstar_repository() {
        if !should_run_integration_tests() {
            return;
        }

        let (client, agent_id) = create_authenticated_client()
            .await
            .expect("Client creation should succeed");

        let repo_name = generate_unique_name("test-repo");

        // Create repository
        let repo = client
            .repos()
            .create(&repo_name, None, None)
            .await
            .expect("Repository creation should succeed");

        assert_eq!(repo.star_count, 0);

        // Star the repository
        let star_response = client
            .stars()
            .star(&repo.repo_id, Some("Great project!"), true)
            .await
            .expect("Star should succeed");

        assert_eq!(star_response.repo_id, repo.repo_id);
        assert_eq!(star_response.agent_id, agent_id);
        assert!(star_response.action == "starred" || star_response.action == "star");
        assert_eq!(star_response.star_count, 1);

        // Get stars info
        let stars_info = client
            .stars()
            .get(&repo.repo_id)
            .await
            .expect("Get stars should succeed");

        assert_eq!(stars_info.star_count, 1);
        assert_eq!(stars_info.starred_by.len(), 1);
        assert_eq!(stars_info.starred_by[0].agent_id, agent_id);
        assert_eq!(stars_info.starred_by[0].reason, Some("Great project!".to_string()));

        // Unstar the repository
        let unstar_response = client
            .stars()
            .unstar(&repo.repo_id)
            .await
            .expect("Unstar should succeed");

        assert_eq!(unstar_response.repo_id, repo.repo_id);
        assert!(unstar_response.action == "unstarred" || unstar_response.action == "unstar");
        assert_eq!(unstar_response.star_count, 0);

        // Verify star count is back to 0
        let repo_after = client
            .repos()
            .get(&repo.repo_id)
            .await
            .expect("Get repository should succeed");

        assert_eq!(repo_after.star_count, 0);
    }

    /// Test: Star → Star again raises ConflictError
    ///
    /// Requirements: 10.1
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_duplicate_star_raises_conflict() {
        if !should_run_integration_tests() {
            return;
        }

        let (client, _) = create_authenticated_client()
            .await
            .expect("Client creation should succeed");

        let repo_name = generate_unique_name("test-repo");
        let repo = client
            .repos()
            .create(&repo_name, None, None)
            .await
            .expect("Repository creation should succeed");

        // Star the repository
        client
            .stars()
            .star(&repo.repo_id, None, false)
            .await
            .expect("First star should succeed");

        // Try to star again
        let result = client.stars().star(&repo.repo_id, None, false).await;

        match result {
            Err(gitclaw::Error::GitClaw(GitClawError::Conflict { .. })) => {
                // Expected error
            }
            Err(e) => panic!("Expected Conflict error, got: {:?}", e),
            Ok(_) => panic!("Expected error, got success"),
        }
    }

    /// Test: Getting a non-existent repository raises NotFoundError
    ///
    /// Requirements: 7.3
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_get_nonexistent_repository_raises_not_found() {
        if !should_run_integration_tests() {
            return;
        }

        let (client, _) = create_authenticated_client()
            .await
            .expect("Client creation should succeed");

        let result = client.repos().get("nonexistent-repo-id-12345").await;

        match result {
            Err(gitclaw::Error::GitClaw(GitClawError::NotFound { .. })) => {
                // Expected error
            }
            Err(e) => panic!("Expected NotFound error, got: {:?}", e),
            Ok(_) => panic!("Expected error, got success"),
        }
    }
}


// ============================================================================
// Task 8.3: Pull Request Workflow Integration Tests
// Requirements: 9.1, 9.2, 9.3, 9.4, 9.5 | Design: DR-5, DR-11
// ============================================================================

mod pull_request_workflow {
    use super::*;

    /// Helper to create a repository with two agents (owner and reviewer).
    async fn create_repo_with_agents() -> Result<(GitClawClient, GitClawClient, String, String), gitclaw::Error> {
        // Create owner agent
        let (owner_signer, owner_public_key) = Ed25519Signer::generate();
        let owner_signer: Arc<dyn Signer> = Arc::new(owner_signer);
        let owner_name = generate_unique_name("owner-agent");

        let temp_client = create_temp_client(Arc::clone(&owner_signer))?;
        let owner_agent = temp_client
            .agents()
            .register(&owner_name, &owner_public_key, None)
            .await?;

        let owner_client = GitClawClient::new(
            &owner_agent.agent_id,
            owner_signer,
            Some(&get_base_url()),
            None,
            None,
        )?;

        // Create reviewer agent
        let (reviewer_signer, reviewer_public_key) = Ed25519Signer::generate();
        let reviewer_signer: Arc<dyn Signer> = Arc::new(reviewer_signer);
        let reviewer_name = generate_unique_name("reviewer-agent");

        let temp_client2 = create_temp_client(Arc::clone(&reviewer_signer))?;
        let reviewer_agent = temp_client2
            .agents()
            .register(&reviewer_name, &reviewer_public_key, None)
            .await?;

        let reviewer_client = GitClawClient::new(
            &reviewer_agent.agent_id,
            reviewer_signer,
            Some(&get_base_url()),
            None,
            None,
        )?;

        // Create repository
        let repo_name = generate_unique_name("test-repo");
        let repo = owner_client.repos().create(&repo_name, None, None).await?;

        // Grant reviewer write access
        owner_client
            .access()
            .grant(&repo.repo_id, &reviewer_agent.agent_id, "write")
            .await?;

        Ok((owner_client, reviewer_client, repo.repo_id, reviewer_agent.agent_id))
    }

    /// Test: Create PR
    ///
    /// Requirements: 9.1, 9.2
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_create_pull_request() {
        if !should_run_integration_tests() {
            return;
        }

        let (owner_client, _, repo_id, _) = create_repo_with_agents()
            .await
            .expect("Setup should succeed");

        // Create a pull request
        // Note: Using main as both source and target since we can't create branches
        // without push functionality. The backend validates branch existence.
        let pr = owner_client
            .pulls()
            .create(
                &repo_id,
                "main",
                "main",
                "Add new feature",
                Some("This PR adds a new feature"),
            )
            .await
            .expect("PR creation should succeed");

        // Verify PR creation
        assert!(!pr.pr_id.is_empty());
        assert_eq!(pr.repo_id, repo_id);
        assert_eq!(pr.author_id, owner_client.agent_id());
        assert_eq!(pr.source_branch, "main");
        assert_eq!(pr.target_branch, "main");
        assert_eq!(pr.title, "Add new feature");
        assert_eq!(pr.description, Some("This PR adds a new feature".to_string()));
        assert_eq!(pr.status, "open");
        assert!(["pending", "running", "passed", "failed"].contains(&pr.ci_status.as_str()));
    }

    /// Test: Create PR → Get PR
    ///
    /// Requirements: 9.1, 9.2
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_get_pull_request() {
        if !should_run_integration_tests() {
            return;
        }

        let (owner_client, _, repo_id, _) = create_repo_with_agents()
            .await
            .expect("Setup should succeed");

        // Create a pull request
        let pr = owner_client
            .pulls()
            .create(&repo_id, "main", "main", "Test PR", None)
            .await
            .expect("PR creation should succeed");

        // Get the PR
        let fetched_pr = owner_client
            .pulls()
            .get(&repo_id, &pr.pr_id)
            .await
            .expect("Get PR should succeed");

        assert_eq!(fetched_pr.pr_id, pr.pr_id);
        assert_eq!(fetched_pr.title, "Test PR");
    }

    /// Test: Create PR → Submit review
    ///
    /// Requirements: 9.1, 9.3
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_submit_review() {
        if !should_run_integration_tests() {
            return;
        }

        let (owner_client, reviewer_client, repo_id, reviewer_agent_id) = create_repo_with_agents()
            .await
            .expect("Setup should succeed");

        // Create a pull request
        let pr = owner_client
            .pulls()
            .create(&repo_id, "main", "main", "Test PR for review", None)
            .await
            .expect("PR creation should succeed");

        // Submit a review (reviewer approves)
        let review = reviewer_client
            .reviews()
            .create(&repo_id, &pr.pr_id, "approve", Some("LGTM! Great work."))
            .await
            .expect("Review submission should succeed");

        // Verify review
        assert!(!review.review_id.is_empty());
        assert_eq!(review.pr_id, pr.pr_id);
        assert_eq!(review.reviewer_id, reviewer_agent_id);
        assert_eq!(review.verdict, "approve");
        assert_eq!(review.body, Some("LGTM! Great work.".to_string()));

        // List reviews
        let reviews = reviewer_client
            .reviews()
            .list(&repo_id, &pr.pr_id)
            .await
            .expect("List reviews should succeed");

        assert!(!reviews.is_empty());
        let review_ids: Vec<&str> = reviews.iter().map(|r| r.review_id.as_str()).collect();
        assert!(review_ids.contains(&review.review_id.as_str()));
    }

    /// Test: Create PR → Submit request_changes review
    ///
    /// Requirements: 9.3
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_request_changes_review() {
        if !should_run_integration_tests() {
            return;
        }

        let (owner_client, reviewer_client, repo_id, _) = create_repo_with_agents()
            .await
            .expect("Setup should succeed");

        // Create a pull request
        let pr = owner_client
            .pulls()
            .create(&repo_id, "main", "main", "Test PR for changes", None)
            .await
            .expect("PR creation should succeed");

        // Submit request_changes review
        let review = reviewer_client
            .reviews()
            .create(
                &repo_id,
                &pr.pr_id,
                "request_changes",
                Some("Please fix the formatting issues."),
            )
            .await
            .expect("Review submission should succeed");

        assert_eq!(review.verdict, "request_changes");
        assert_eq!(review.body, Some("Please fix the formatting issues.".to_string()));
    }
}

// ============================================================================
// Task 8.4: Access Control Integration Tests
// Requirements: 8.1, 8.2, 8.3 | Design: DR-5, DR-10
// ============================================================================

mod access_control {
    use super::*;

    /// Helper to create an owner agent with a repository and a collaborator agent.
    async fn create_owner_and_collaborator() -> Result<(GitClawClient, GitClawClient, String, String), gitclaw::Error> {
        // Create owner agent
        let (owner_signer, owner_public_key) = Ed25519Signer::generate();
        let owner_signer: Arc<dyn Signer> = Arc::new(owner_signer);
        let owner_name = generate_unique_name("owner-agent");

        let temp_client = create_temp_client(Arc::clone(&owner_signer))?;
        let owner_agent = temp_client
            .agents()
            .register(&owner_name, &owner_public_key, None)
            .await?;

        let owner_client = GitClawClient::new(
            &owner_agent.agent_id,
            owner_signer,
            Some(&get_base_url()),
            None,
            None,
        )?;

        // Create collaborator agent
        let (collab_signer, collab_public_key) = Ed25519Signer::generate();
        let collab_signer: Arc<dyn Signer> = Arc::new(collab_signer);
        let collab_name = generate_unique_name("collab-agent");

        let temp_client2 = create_temp_client(Arc::clone(&collab_signer))?;
        let collab_agent = temp_client2
            .agents()
            .register(&collab_name, &collab_public_key, None)
            .await?;

        let collab_client = GitClawClient::new(
            &collab_agent.agent_id,
            collab_signer,
            Some(&get_base_url()),
            None,
            None,
        )?;

        // Create repository
        let repo_name = generate_unique_name("test-repo");
        let repo = owner_client.repos().create(&repo_name, None, None).await?;

        Ok((owner_client, collab_client, repo.repo_id, collab_agent.agent_id))
    }

    /// Test: Grant access to collaborator
    ///
    /// Requirements: 8.1
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_grant_access() {
        if !should_run_integration_tests() {
            return;
        }

        let (owner_client, _, repo_id, collab_agent_id) = create_owner_and_collaborator()
            .await
            .expect("Setup should succeed");

        // Grant write access
        let response = owner_client
            .access()
            .grant(&repo_id, &collab_agent_id, "write")
            .await
            .expect("Grant access should succeed");

        assert_eq!(response.repo_id, repo_id);
        assert_eq!(response.agent_id, collab_agent_id);
        assert_eq!(response.role, Some("write".to_string()));
        assert_eq!(response.action, "granted");
    }

    /// Test: Grant access → List collaborators
    ///
    /// Requirements: 8.1, 8.3
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_list_collaborators() {
        if !should_run_integration_tests() {
            return;
        }

        let (owner_client, _, repo_id, collab_agent_id) = create_owner_and_collaborator()
            .await
            .expect("Setup should succeed");

        // Grant access
        owner_client
            .access()
            .grant(&repo_id, &collab_agent_id, "read")
            .await
            .expect("Grant access should succeed");

        // List collaborators
        let collaborators = owner_client
            .access()
            .list(&repo_id)
            .await
            .expect("List collaborators should succeed");

        // Find the collaborator we just added
        let collab_ids: Vec<&str> = collaborators.iter().map(|c| c.agent_id.as_str()).collect();
        assert!(collab_ids.contains(&collab_agent_id.as_str()));

        // Verify collaborator details
        let collab = collaborators
            .iter()
            .find(|c| c.agent_id == collab_agent_id)
            .expect("Collaborator should be in list");

        assert_eq!(collab.role, "read");
        assert!(!collab.agent_name.is_empty());
    }

    /// Test: Grant access → Revoke access
    ///
    /// Requirements: 8.1, 8.2
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_revoke_access() {
        if !should_run_integration_tests() {
            return;
        }

        let (owner_client, _, repo_id, collab_agent_id) = create_owner_and_collaborator()
            .await
            .expect("Setup should succeed");

        // Grant access
        owner_client
            .access()
            .grant(&repo_id, &collab_agent_id, "write")
            .await
            .expect("Grant access should succeed");

        // Revoke access
        let response = owner_client
            .access()
            .revoke(&repo_id, &collab_agent_id)
            .await
            .expect("Revoke access should succeed");

        assert_eq!(response.repo_id, repo_id);
        assert_eq!(response.agent_id, collab_agent_id);
        assert_eq!(response.action, "revoked");

        // Verify collaborator is no longer in the list
        let collaborators = owner_client
            .access()
            .list(&repo_id)
            .await
            .expect("List collaborators should succeed");

        let collab_ids: Vec<&str> = collaborators.iter().map(|c| c.agent_id.as_str()).collect();
        assert!(!collab_ids.contains(&collab_agent_id.as_str()));
    }

    /// Test: Grant different access roles (read, write, admin)
    ///
    /// Requirements: 8.1
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_grant_different_roles() {
        if !should_run_integration_tests() {
            return;
        }

        let (owner_client, _, repo_id, collab_agent_id) = create_owner_and_collaborator()
            .await
            .expect("Setup should succeed");

        // Test each role
        for role in ["read", "write", "admin"] {
            let response = owner_client
                .access()
                .grant(&repo_id, &collab_agent_id, role)
                .await
                .expect("Grant access should succeed");

            assert_eq!(response.role, Some(role.to_string()));

            // Verify in collaborators list
            let collaborators = owner_client
                .access()
                .list(&repo_id)
                .await
                .expect("List collaborators should succeed");

            let collab = collaborators
                .iter()
                .find(|c| c.agent_id == collab_agent_id)
                .expect("Collaborator should be in list");

            assert_eq!(collab.role, role);
        }
    }

    /// Test: Full lifecycle - Grant → List → Revoke → Verify removed
    ///
    /// Requirements: 8.1, 8.2, 8.3
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_access_control_full_lifecycle() {
        if !should_run_integration_tests() {
            return;
        }

        let (owner_client, _, repo_id, collab_agent_id) = create_owner_and_collaborator()
            .await
            .expect("Setup should succeed");

        // Grant access
        let grant_response = owner_client
            .access()
            .grant(&repo_id, &collab_agent_id, "write")
            .await
            .expect("Grant access should succeed");

        assert_eq!(grant_response.action, "granted");

        // List and verify
        let collaborators = owner_client
            .access()
            .list(&repo_id)
            .await
            .expect("List collaborators should succeed");

        assert!(collaborators.iter().any(|c| c.agent_id == collab_agent_id));

        // Revoke access
        let revoke_response = owner_client
            .access()
            .revoke(&repo_id, &collab_agent_id)
            .await
            .expect("Revoke access should succeed");

        assert_eq!(revoke_response.action, "revoked");

        // Verify removed
        let collaborators_after = owner_client
            .access()
            .list(&repo_id)
            .await
            .expect("List collaborators should succeed");

        assert!(!collaborators_after.iter().any(|c| c.agent_id == collab_agent_id));
    }
}


// ============================================================================
// Task 8.5: Error Handling Integration Tests
// Requirements: 13.1, 13.2, 13.3 | Design: DR-8
// ============================================================================

mod error_handling {
    use super::*;

    /// Test: Duplicate star raises ConflictError
    ///
    /// Requirements: 13.1, 13.2
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_duplicate_star_raises_conflict_error() {
        if !should_run_integration_tests() {
            return;
        }

        let (client, _) = create_authenticated_client()
            .await
            .expect("Client creation should succeed");

        let repo_name = generate_unique_name("test-repo");
        let repo = client
            .repos()
            .create(&repo_name, None, None)
            .await
            .expect("Repository creation should succeed");

        // First star succeeds
        client
            .stars()
            .star(&repo.repo_id, None, false)
            .await
            .expect("First star should succeed");

        // Second star raises ConflictError
        let result = client.stars().star(&repo.repo_id, None, false).await;

        match result {
            Err(gitclaw::Error::GitClaw(GitClawError::Conflict { code, message, .. })) => {
                // Verify error has code and message
                assert!(!code.is_empty());
                assert!(!message.is_empty());
            }
            Err(e) => panic!("Expected Conflict error, got: {:?}", e),
            Ok(_) => panic!("Expected error, got success"),
        }
    }

    /// Test: NotFoundError contains code, message, and request_id
    ///
    /// Requirements: 13.2, 13.3
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_not_found_error_has_proper_fields() {
        if !should_run_integration_tests() {
            return;
        }

        let (client, _) = create_authenticated_client()
            .await
            .expect("Client creation should succeed");

        let result = client.repos().get("nonexistent-repo-id-12345").await;

        match result {
            Err(gitclaw::Error::GitClaw(GitClawError::NotFound { code, message, .. })) => {
                assert!(!code.is_empty());
                assert!(!message.is_empty());
            }
            Err(e) => panic!("Expected NotFound error, got: {:?}", e),
            Ok(_) => panic!("Expected error, got success"),
        }
    }

    /// Test: Invalid signature raises AuthenticationError
    ///
    /// Requirements: 13.1, 13.2
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_invalid_signature_raises_authentication_error() {
        if !should_run_integration_tests() {
            return;
        }

        // Create a client with mismatched agent_id and signer
        let (signer, public_key) = Ed25519Signer::generate();
        let signer: Arc<dyn Signer> = Arc::new(signer);
        let agent_name = generate_unique_name("test-agent");

        // Register the agent
        let temp_client = create_temp_client(Arc::clone(&signer)).expect("Client creation should succeed");
        let agent = temp_client
            .agents()
            .register(&agent_name, &public_key, None)
            .await
            .expect("Agent registration should succeed");

        // Create a different signer (not matching the registered public key)
        let (wrong_signer, _) = Ed25519Signer::generate();
        let wrong_signer: Arc<dyn Signer> = Arc::new(wrong_signer);

        // Create client with correct agent_id but wrong signer
        let client = GitClawClient::new(
            &agent.agent_id,
            wrong_signer,
            Some(&get_base_url()),
            None,
            None,
        )
        .expect("Client creation should succeed");

        // Try to create a repo with invalid signature
        let result = client
            .repos()
            .create(&generate_unique_name("test-repo"), None, None)
            .await;

        match result {
            Err(gitclaw::Error::GitClaw(GitClawError::Authentication { code, message, .. })) => {
                assert!(!code.is_empty());
                assert!(!message.is_empty());
            }
            Err(e) => panic!("Expected Authentication error, got: {:?}", e),
            Ok(_) => panic!("Expected error, got success"),
        }
    }

    /// Test: All errors inherit from GitClawError (via Error enum)
    ///
    /// Requirements: 13.4
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_error_inheritance() {
        if !should_run_integration_tests() {
            return;
        }

        let (client, _) = create_authenticated_client()
            .await
            .expect("Client creation should succeed");

        // Test NotFoundError
        let result = client.repos().get("nonexistent-repo-id").await;
        assert!(matches!(result, Err(gitclaw::Error::GitClaw(_))));

        // Test ConflictError
        let repo = client
            .repos()
            .create(&generate_unique_name("test-repo"), None, None)
            .await
            .expect("Repository creation should succeed");

        client
            .stars()
            .star(&repo.repo_id, None, false)
            .await
            .expect("First star should succeed");

        let result = client.stars().star(&repo.repo_id, None, false).await;
        assert!(matches!(result, Err(gitclaw::Error::GitClaw(_))));
    }

    /// Test: Error string representation includes code and message
    ///
    /// Requirements: 13.2
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_error_string_representation() {
        if !should_run_integration_tests() {
            return;
        }

        let (client, _) = create_authenticated_client()
            .await
            .expect("Client creation should succeed");

        let result = client.repos().get("nonexistent-repo-id").await;

        match result {
            Err(gitclaw::Error::GitClaw(error)) => {
                let error_str = error.to_string();
                // String should contain the error code
                assert!(
                    error_str.contains(error.code()),
                    "Error string should contain code: {}",
                    error_str
                );
            }
            Err(e) => panic!("Expected GitClaw error, got: {:?}", e),
            Ok(_) => panic!("Expected error, got success"),
        }
    }

    /// Test: GitClawError helper methods work correctly
    ///
    /// Requirements: 13.2, 13.3
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_gitclaw_error_helper_methods() {
        if !should_run_integration_tests() {
            return;
        }

        let (client, _) = create_authenticated_client()
            .await
            .expect("Client creation should succeed");

        let result = client.repos().get("nonexistent-repo-id").await;

        match result {
            Err(gitclaw::Error::GitClaw(error)) => {
                // Test helper methods
                assert!(!error.code().is_empty());
                assert!(!error.message().is_empty());
                // request_id may or may not be present
                let _ = error.request_id();

                // NotFound errors should not be retryable
                assert!(!error.is_retryable());
            }
            Err(e) => panic!("Expected GitClaw error, got: {:?}", e),
            Ok(_) => panic!("Expected error, got success"),
        }
    }
}

// ============================================================================
// Additional Integration Tests
// ============================================================================

mod additional_tests {
    use super::*;

    /// Test: Client can be created from environment variables
    ///
    /// Requirements: 1.2, 1.3
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and environment variables"]
    async fn test_client_from_env() {
        if !should_run_integration_tests() {
            return;
        }

        // This test requires GITCLAW_AGENT_ID and GITCLAW_PRIVATE_KEY_PATH to be set
        if env::var("GITCLAW_AGENT_ID").is_err() || env::var("GITCLAW_PRIVATE_KEY_PATH").is_err() {
            // Skip if env vars not set
            return;
        }

        let client = GitClawClient::from_env().expect("Client creation from env should succeed");
        assert!(!client.agent_id().is_empty());
    }

    /// Test: Trending endpoint works without authentication
    ///
    /// Requirements: 11.1, 11.2, 11.3
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_trending_without_auth() {
        if !should_run_integration_tests() {
            return;
        }

        let (signer, _) = Ed25519Signer::generate();
        let signer: Arc<dyn Signer> = Arc::new(signer);

        // Create client without registering (trending doesn't require auth)
        let client = create_temp_client(signer).expect("Client creation should succeed");

        // Get trending repositories
        let result = client.trending().get(Some("24h"), Some(10)).await;

        // Should succeed (even if empty)
        match result {
            Ok(trending) => {
                // Verify response structure
                assert!(trending.window == "24h" || trending.window.is_empty());
                // repos may be empty if no trending repos
            }
            Err(e) => {
                // Some backends may not have trending implemented
                println!("Trending endpoint returned error (may not be implemented): {:?}", e);
            }
        }
    }

    /// Test: Multiple operations in sequence
    ///
    /// Requirements: All
    #[tokio::test]
    #[ignore = "Integration test requires GITCLAW_INTEGRATION_TESTS=1 and a running backend"]
    async fn test_full_workflow() {
        if !should_run_integration_tests() {
            return;
        }

        // Create authenticated client
        let (client, agent_id) = create_authenticated_client()
            .await
            .expect("Client creation should succeed");

        // 1. Create a repository
        let repo_name = generate_unique_name("workflow-repo");
        let repo = client
            .repos()
            .create(&repo_name, Some("Workflow test repo"), Some("public"))
            .await
            .expect("Repository creation should succeed");

        assert_eq!(repo.owner_id, agent_id);

        // 2. Star the repository
        let star_response = client
            .stars()
            .star(&repo.repo_id, Some("Testing workflow"), false)
            .await
            .expect("Star should succeed");

        assert_eq!(star_response.star_count, 1);

        // 3. Get repository and verify star count
        let repo_after_star = client
            .repos()
            .get(&repo.repo_id)
            .await
            .expect("Get repository should succeed");

        assert_eq!(repo_after_star.star_count, 1);

        // 4. Create a pull request
        let pr = client
            .pulls()
            .create(
                &repo.repo_id,
                "main",
                "main",
                "Workflow PR",
                Some("Testing the full workflow"),
            )
            .await
            .expect("PR creation should succeed");

        assert_eq!(pr.status, "open");

        // 5. Unstar the repository
        let unstar_response = client
            .stars()
            .unstar(&repo.repo_id)
            .await
            .expect("Unstar should succeed");

        assert_eq!(unstar_response.star_count, 0);

        // 6. Verify final state
        let final_repo = client
            .repos()
            .get(&repo.repo_id)
            .await
            .expect("Get repository should succeed");

        assert_eq!(final_repo.star_count, 0);
    }
}