rs-guard 1.0.0

AI-powered code review CLI for GitHub 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
//! Full pipeline integration tests with mock GitHub and mock LLM servers.
//!
//! Tests [`run_pipeline`] end-to-end, verifying that the orchestration
//! correctly sequences diff fetching, LLM calling, verdict parsing, and
//! review submission.

use rs_guard::config::Config;
use rs_guard::pipeline::{run_pipeline, PipelineResult};
use serde_json::json;
use wiremock::matchers::{method, path_regex};
use wiremock::{Mock, MockServer, ResponseTemplate};

/// Builds a minimal Config for CI-mode integration tests.
fn ci_config(pr_number: u64, provider: &str, api_key: &str) -> Config {
    let mut c = Config::empty();
    c.is_ci = true;
    c.pr_number = Some(pr_number);
    c.repo_owner = Some("test-owner".into());
    c.repo_name = Some("test-repo".into());
    c.github_token = Some(api_key.into());
    c.provider = provider.into();
    c.model = "test-model".into();
    c.temperature = 0.1;
    c.prompt = "You are a code reviewer.".into();
    c.api_key = "test-llm-key".into();
    c
}

/// Builds a minimal Config for local-mode integration tests.
fn local_config() -> Config {
    let mut c = Config::empty();
    c.is_ci = false;
    c.provider = "deepseek".into();
    c.model = "test-model".into();
    c.temperature = 0.1;
    c.prompt = "You are a code reviewer.".into();
    c.api_key = "test-llm-key".into();
    c
}

const VALID_DIFF: &str =
    "diff --git a/f.rs b/f.rs\n--- a/f.rs\n+++ b/f.rs\n@@ -1 +1,2 @@\n+line1\n line0";

const POSITIVE_RESPONSE: &str = "Looks good.\n\n[RS_GUARD_VERDICT_METADATA]\nVerdict: POSITIVE\nCriticalIssues: 0\nSecurityIssues: 0\nImportantIssues: 0\nSuggestions: 0";

const NEGATIVE_RESPONSE: &str = "Found issues.\n\n[RS_GUARD_VERDICT_METADATA]\nVerdict: NEGATIVE\nCriticalIssues: 2\nSecurityIssues: 1\nImportantIssues: 0\nSuggestions: 0";

/// LLM response with 2 important issues and no critical/security — should yield COMMENT.
const IMPORTANT_ISSUES_RESPONSE: &str = "Review complete.\n\n[RS_GUARD_VERDICT_METADATA]\nVerdict: POSITIVE\nCriticalIssues: 0\nSecurityIssues: 0\nImportantIssues: 2\nSuggestions: 1";

#[tokio::test]
async fn test_full_pipeline_ci_approve() {
    let github = MockServer::start().await;
    let llm = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+"))
        .respond_with(ResponseTemplate::new(200).set_body_string(VALID_DIFF))
        .mount(&github)
        .await;

    Mock::given(method("POST"))
        .and(path_regex(r"/chat/completions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "choices": [{"message": {"content": POSITIVE_RESPONSE}}]
        })))
        .mount(&llm)
        .await;

    Mock::given(method("POST"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+/reviews"))
        .respond_with(ResponseTemplate::new(200))
        .mount(&github)
        .await;

    let mut config = ci_config(42, "deepseek", "test-token");
    config.github_base_url = github.uri();
    config.provider_config.base_url = Some(llm.uri());
    config.no_cache = true; // Disable cache to avoid conflicts

    let result = run_pipeline(config, None).await;
    assert!(matches!(result, Ok(PipelineResult::Success)));
}

#[tokio::test]
async fn test_full_pipeline_ci_request_changes() {
    let github = MockServer::start().await;
    let llm = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+"))
        .respond_with(ResponseTemplate::new(200).set_body_string(VALID_DIFF))
        .mount(&github)
        .await;

    Mock::given(method("POST"))
        .and(path_regex(r"/chat/completions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "choices": [{"message": {"content": NEGATIVE_RESPONSE}}]
        })))
        .mount(&llm)
        .await;

    // REQUEST_CHANGES submission, but no dismissal (state is blocking)
    Mock::given(method("POST"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+/reviews"))
        .respond_with(ResponseTemplate::new(200))
        .mount(&github)
        .await;

    let mut config = ci_config(42, "deepseek", "test-token");
    config.github_base_url = github.uri();
    config.provider_config.base_url = Some(llm.uri());
    config.no_cache = true; // Disable cache to avoid conflicts

    let result = run_pipeline(config, None).await;
    assert!(matches!(result, Ok(PipelineResult::Success)));
}

#[tokio::test]
async fn test_full_pipeline_ci_dismisses_previous_reviews() {
    let github = MockServer::start().await;
    let llm = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+"))
        .respond_with(ResponseTemplate::new(200).set_body_string(VALID_DIFF))
        .mount(&github)
        .await;

    Mock::given(method("POST"))
        .and(path_regex(r"/chat/completions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "choices": [{"message": {"content": POSITIVE_RESPONSE}}]
        })))
        .mount(&llm)
        .await;

    // APPROVE submission succeeds
    Mock::given(method("POST"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+/reviews"))
        .respond_with(ResponseTemplate::new(200))
        .mount(&github)
        .await;

    // Dismissal query returns a bot review
    Mock::given(method("GET"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+/reviews"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!([{
            "id": 1,
            "state": "CHANGES_REQUESTED",
            "body": "Previous review\n\n<!-- rs-guard-bot -->"
        }])))
        .mount(&github)
        .await;

    // Dismissal succeeds
    Mock::given(method("PUT"))
        .and(path_regex(
            r"/repos/test-owner/test-repo/pulls/\d+/reviews/\d+/dismissals",
        ))
        .respond_with(ResponseTemplate::new(200))
        .mount(&github)
        .await;

    let mut config = ci_config(42, "deepseek", "test-token");
    config.github_base_url = github.uri();
    config.provider_config.base_url = Some(llm.uri());
    config.no_cache = true; // Disable cache to avoid conflicts

    let result = run_pipeline(config, None).await;
    assert!(matches!(result, Ok(PipelineResult::Success)));
}

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

    Mock::given(method("POST"))
        .and(path_regex(r"/chat/completions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "choices": [{"message": {"content": POSITIVE_RESPONSE}}]
        })))
        .mount(&llm)
        .await;

    let mut config = local_config();
    config.provider_config.base_url = Some(llm.uri());
    config.no_cache = true; // Disable cache to avoid conflicts

    let dir = tempfile::tempdir().unwrap();
    let diff_path = dir.path().join("test.diff");
    std::fs::write(&diff_path, VALID_DIFF).unwrap();

    let result = run_pipeline(config, Some(diff_path.to_str().unwrap())).await;
    assert!(matches!(result, Ok(PipelineResult::Success)));
}

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

    Mock::given(method("GET"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+"))
        .respond_with(ResponseTemplate::new(200).set_body_string(""))
        .mount(&github)
        .await;

    let mut config = ci_config(42, "deepseek", "test-token");
    config.github_base_url = github.uri();
    config.no_cache = true; // Disable cache to avoid conflicts

    let result = run_pipeline(config, None).await;
    assert!(matches!(result, Ok(PipelineResult::Success)));
}

#[tokio::test]
#[serial_test::serial]
async fn test_full_pipeline_cache_hit() {
    // Clear cache before this test to ensure clean state
    let cache_dir = std::path::Path::new(".rs-guard/cache");
    if cache_dir.exists() {
        let _ = std::fs::remove_dir_all(cache_dir);
    }

    let github = MockServer::start().await;
    let llm = MockServer::start().await;

    // Use unique diff content to avoid cache collisions with other tests
    let unique_diff = format!(
        "diff --git a/unique{}.rs b/unique{}.rs\n+line{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos(),
        42
    );

    Mock::given(method("GET"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+"))
        .respond_with(ResponseTemplate::new(200).set_body_string(&unique_diff))
        .mount(&github)
        .await;

    Mock::given(method("POST"))
        .and(path_regex(r"/chat/completions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "choices": [{"message": {"content": POSITIVE_RESPONSE}}]
        })))
        .expect(1) // Should only be called once (first run)
        .mount(&llm)
        .await;

    Mock::given(method("POST"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+/reviews"))
        .respond_with(ResponseTemplate::new(200))
        .expect(2) // Should be called twice (two runs)
        .mount(&github)
        .await;

    let mut config1 = ci_config(42, "deepseek", "test-token");
    config1.github_base_url = github.uri();
    config1.provider_config.base_url = Some(llm.uri());

    // First run - should call LLM
    let result1 = run_pipeline(config1, None).await;
    assert!(matches!(result1, Ok(PipelineResult::Success)));

    // Second run - should use cache
    let mut config2 = ci_config(42, "deepseek", "test-token");
    config2.github_base_url = github.uri();
    config2.provider_config.base_url = Some(llm.uri());

    let result2 = run_pipeline(config2, None).await;
    assert!(matches!(result2, Ok(PipelineResult::Success)));

    // Verify LLM was only called once (cache hit on second run)
    // The mock's expect(1) will fail if called more than once
}

#[tokio::test]
async fn test_full_pipeline_chunked_diff() {
    let github = MockServer::start().await;
    let llm = MockServer::start().await;

    // Generate a large diff (20 valid unified diff blocks)
    let large_diff: String = (0..20)
        .map(|i| {
            format!(
                "diff --git a/file{}.rs b/file{}.rs\n--- a/file{}.rs\n+++ b/file{}.rs\n@@ -1,1 +1,1 @@\n-old line {}\n+new line {}\n",
                i, i, i, i, i, i
            )
        })
        .collect::<Vec<_>>()
        .join("\n");

    Mock::given(method("GET"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+"))
        .respond_with(ResponseTemplate::new(200).set_body_string(large_diff))
        .mount(&github)
        .await;

    Mock::given(method("POST"))
        .and(path_regex(r"/chat/completions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "choices": [{"message": {"content": POSITIVE_RESPONSE}}]
        })))
        .mount(&llm)
        .await;

    Mock::given(method("POST"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+/reviews"))
        .respond_with(ResponseTemplate::new(200))
        .mount(&github)
        .await;

    let mut config = ci_config(42, "deepseek", "test-token");
    config.github_base_url = github.uri();
    config.provider_config.base_url = Some(llm.uri());
    config.no_cache = true; // Disable cache to avoid conflicts

    let result = run_pipeline(config, None).await;
    assert!(matches!(result, Ok(PipelineResult::Success)));

    // The pipeline should have chunked the diff and added a warning
    // We can't easily verify the warning was added to the review body
    // without inspecting the mock server's request history
}

#[tokio::test]
#[serial_test::serial]
async fn test_full_pipeline_metrics_file_created() {
    let github = MockServer::start().await;
    let llm = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+"))
        .respond_with(ResponseTemplate::new(200).set_body_string(VALID_DIFF))
        .mount(&github)
        .await;

    Mock::given(method("POST"))
        .and(path_regex(r"/chat/completions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "choices": [{"message": {"content": POSITIVE_RESPONSE}}]
        })))
        .mount(&llm)
        .await;

    Mock::given(method("POST"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+/reviews"))
        .respond_with(ResponseTemplate::new(200))
        .mount(&github)
        .await;

    let mut config = ci_config(42, "deepseek", "test-token");
    config.github_base_url = github.uri();
    config.provider_config.base_url = Some(llm.uri());
    config.no_cache = true; // Disable cache to avoid conflicts

    // Use temp file for metrics to ensure cleanup
    let metrics_file = tempfile::NamedTempFile::new().unwrap();
    let metrics_path = metrics_file.path();
    std::env::set_var("RS_GUARD_METRICS_PATH", metrics_path);

    let result = run_pipeline(config, None).await;
    assert!(matches!(result, Ok(PipelineResult::Success)));

    // Verify metrics file contains expected fields
    let content = std::fs::read_to_string(metrics_path).unwrap();
    assert!(content.contains("provider"));
    assert!(content.contains("estimated_tokens_in"));
    assert!(content.contains("estimated_tokens_out"));
    assert!(content.contains("latency_secs"));
    assert!(content.contains("estimated_cost_cents"));

    // Temp file is automatically cleaned up on drop
    std::env::remove_var("RS_GUARD_METRICS_PATH");
}

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

    Mock::given(method("POST"))
        .and(path_regex(r"/chat/completions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "choices": [{"message": {"content": NEGATIVE_RESPONSE}}]
        })))
        .mount(&llm)
        .await;

    let mut config = local_config();
    config.provider_config.base_url = Some(llm.uri());
    config.no_cache = true; // Disable cache to avoid conflicts

    let dir = tempfile::tempdir().unwrap();
    let diff_path = dir.path().join("test.diff");
    std::fs::write(&diff_path, VALID_DIFF).unwrap();

    let result = run_pipeline(config, Some(diff_path.to_str().unwrap())).await;
    assert!(matches!(result, Ok(PipelineResult::ReviewBlocked)));
}

#[tokio::test]
async fn test_full_pipeline_llm_retries_exhausted() {
    let github = MockServer::start().await;
    let llm = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+"))
        .respond_with(ResponseTemplate::new(200).set_body_string(VALID_DIFF))
        .mount(&github)
        .await;

    // LLM server returns 500 errors - this will trigger retries with exponential backoff and eventually fail
    Mock::given(method("POST"))
        .and(path_regex(r"/chat/completions"))
        .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
        .mount(&llm)
        .await;

    let mut config = ci_config(42, "deepseek", "test-token");
    config.github_base_url = github.uri();
    config.provider_config.base_url = Some(llm.uri());
    config.no_cache = true; // Disable cache to avoid conflicts

    // The call should fail after retries due to repeated 500 errors
    let result = run_pipeline(config, None).await;
    assert!(result.is_err());
}

#[tokio::test]
async fn test_full_pipeline_ci_important_issues_yield_comment_not_blocked() {
    // Arrange: LLM returns 2 important issues (below the 3-issue REQUEST_CHANGES threshold).
    // The pipeline should succeed (COMMENT state is not a ReviewBlocked result).
    let github = MockServer::start().await;
    let llm = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+"))
        .respond_with(ResponseTemplate::new(200).set_body_string(VALID_DIFF))
        .mount(&github)
        .await;

    Mock::given(method("POST"))
        .and(path_regex(r"/chat/completions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "choices": [{"message": {"content": IMPORTANT_ISSUES_RESPONSE}}]
        })))
        .mount(&llm)
        .await;

    // COMMENT review submission
    Mock::given(method("POST"))
        .and(path_regex(r"/repos/test-owner/test-repo/pulls/\d+/reviews"))
        .respond_with(ResponseTemplate::new(200))
        .mount(&github)
        .await;

    let mut config = ci_config(42, "deepseek", "test-token");
    config.github_base_url = github.uri();
    config.provider_config.base_url = Some(llm.uri());
    config.no_cache = true;

    let result = run_pipeline(config, None).await;
    // Assert: pipeline succeeds — important issues produce COMMENT, not ReviewBlocked
    assert!(matches!(result, Ok(PipelineResult::Success)));

    // Assert: the review POST body sent to GitHub contains event=COMMENT, not APPROVE or
    // REQUEST_CHANGES — verifying that the correct review state was actually submitted.
    let requests = github.received_requests().await.unwrap_or_default();
    let review_request = requests
        .iter()
        .find(|r| r.method == wiremock::http::Method::POST && r.url.path().ends_with("/reviews"))
        .expect("expected a POST to /reviews");
    let body: serde_json::Value =
        serde_json::from_slice(&review_request.body).expect("review body is valid JSON");
    assert_eq!(
        body["event"].as_str(),
        Some("COMMENT"),
        "expected COMMENT event, got: {}",
        body["event"]
    );
}