drep-ai 2.7.0

A local commit gate: runs the linters your repo configures, and sends changed code to an LLM for review
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
//! End-to-end contracts for the bounded semantic-review cycle.

use std::path::{Path, PathBuf};

use wiremock::MockServer;

use super::super::review_budget::{Budget, Claim};
use super::support::{check_args as args, run_drep};
use crate::analysis::acknowledgements::Store;
use crate::analysis::findings::{Finding, Severity};
use crate::cli::check;
use crate::diff::hunks::Hunk;
use crate::llm::cache::Cache;
use crate::test_support::{
    git_commit_all as commit_all, git_output, server_returning, write_executable,
};

async fn setup_mock(body: &str) -> (tempfile::TempDir, MockServer) {
    let dir = tempfile::tempdir().expect("tempdir");
    let server = server_returning(&[body]).await;
    (dir, server)
}

fn git_head(dir: &Path) -> String {
    git_output(dir, &["rev-parse", "HEAD"])
}

async fn commit_rounds(root: &Path, rounds: u32) {
    let budget = Budget::for_repo(root, 3).await.expect("budget");
    for _ in 0..rounds {
        let Claim::Reserved(claim) = budget.claim().expect("claim") else {
            panic!("round must be available");
        };
        claim.commit().expect("commit round");
    }
}

#[test]
fn fourth_fresh_staged_review_is_blocked_but_cache_and_overrides_remain_available() {
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .expect("runtime");
    let (dir, server) = runtime.block_on(async {
        let dir = tempfile::tempdir().expect("tempdir");
        crate::test_support::git_init(dir.path());
        let server = server_returning(&[
            r#"{"issues":[{"line":1,"severity":"high","category":"bug","message":"fix me"}]}"#,
        ])
        .await;
        crate::test_support::write_drep_toml(dir.path(), &format!("{}/v1", server.uri()));
        std::fs::write(dir.path().join("lib.py"), "x = 0\n").expect("lib.py");
        commit_all(dir.path(), "base");
        (dir, server)
    });

    for round in 1..=3 {
        std::fs::write(dir.path().join("lib.py"), format!("x = {round}\n")).expect("lib.py");
        crate::test_support::git_add(dir.path(), "lib.py");
        let output = run_drep(dir.path(), &["check", "--staged"]);
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert_eq!(output.status.code(), Some(0), "stdout: {stdout}");
        assert!(
            stdout.contains(&format!("Fresh LLM review round {round} of 3")),
            "stdout: {stdout}"
        );
    }

    std::fs::write(dir.path().join("lib.py"), "x = 4\n").expect("lib.py");
    crate::test_support::git_add(dir.path(), "lib.py");
    let blocked = run_drep(dir.path(), &["check", "--staged"]);
    let blocked_stdout = String::from_utf8_lossy(&blocked.stdout);
    assert_eq!(blocked.status.code(), Some(2), "stdout: {blocked_stdout}");
    assert!(
        blocked_stdout.contains("fresh LLM review limit reached (3 of 3)"),
        "stdout: {blocked_stdout}"
    );
    assert_eq!(
        runtime.block_on(crate::test_support::request_count(&server)),
        3
    );

    // The cap blocks only a cold fourth review. Restoring already-reviewed
    // content reuses its cached verdict without another provider request.
    std::fs::write(dir.path().join("lib.py"), "x = 3\n").expect("lib.py");
    crate::test_support::git_add(dir.path(), "lib.py");
    let cached = run_drep(dir.path(), &["check", "--staged"]);
    assert_eq!(cached.status.code(), Some(0));
    assert_eq!(
        runtime.block_on(crate::test_support::request_count(&server)),
        3
    );

    std::fs::write(dir.path().join("lib.py"), "x = 4\n").expect("lib.py");
    crate::test_support::git_add(dir.path(), "lib.py");
    let extended = run_drep(
        dir.path(),
        &["check", "--staged", "--max-review-rounds", "4"],
    );
    let extended_stdout = String::from_utf8_lossy(&extended.stdout);
    assert_eq!(extended.status.code(), Some(0), "stdout: {extended_stdout}");
    assert!(
        extended_stdout.contains("Fresh LLM review round 4 of 4"),
        "stdout: {extended_stdout}"
    );
    assert_eq!(
        runtime.block_on(crate::test_support::request_count(&server)),
        4
    );

    std::fs::write(dir.path().join("lib.py"), "x = 5\n").expect("lib.py");
    crate::test_support::git_add(dir.path(), "lib.py");
    let unlimited = run_drep(dir.path(), &["check", "--staged", "--unlimited-reviews"]);
    let unlimited_stdout = String::from_utf8_lossy(&unlimited.stdout);
    assert_eq!(
        unlimited.status.code(),
        Some(0),
        "stdout: {unlimited_stdout}"
    );
    assert!(
        unlimited_stdout.contains("Fresh LLM review ran with no round limit"),
        "stdout: {unlimited_stdout}"
    );
    assert_eq!(
        runtime.block_on(crate::test_support::request_count(&server)),
        5
    );
}

#[tokio::test]
async fn clean_push_gate_warm_resets_the_review_cycle() {
    let (dir, server) = setup_mock(r#"{"issues": []}"#).await;
    crate::test_support::git_init(dir.path());
    crate::test_support::write_drep_toml(dir.path(), &format!("{}/v1", server.uri()));
    std::fs::write(dir.path().join("lib.py"), "x = 0\n").expect("lib.py");
    commit_all(dir.path(), "base");
    let base = git_head(dir.path());
    std::fs::write(dir.path().join("lib.py"), "x = 1\n").expect("lib.py");
    commit_all(dir.path(), "change one");

    commit_rounds(dir.path(), 3).await;

    let cache = Cache::new(dir.path().join("reset-cache"), 30, 8 * 1024 * 1024);
    let mut check_args = args(Vec::new(), None);
    check_args.diff = Some(base.clone());
    check_args.push_gate = true;
    check_args.max_review_rounds = Some(4);
    let first = check::run_with(&check_args, dir.path(), cache.clone())
        .await
        .expect("extended clean warm");
    assert_eq!(first, check::Exit::CacheMiss);

    std::fs::write(dir.path().join("lib.py"), "x = 2\n").expect("lib.py");
    commit_all(dir.path(), "change two");
    check_args.max_review_rounds = None;
    let second = check::run_with(&check_args, dir.path(), cache)
        .await
        .expect("default budget after reset");

    assert_eq!(second, check::Exit::CacheMiss);
    assert_eq!(crate::test_support::request_count(&server).await, 2);
}

#[tokio::test]
async fn a_clean_named_path_check_does_not_reset_an_authoritative_cycle() {
    let (dir, server) = setup_mock(r#"{"issues": []}"#).await;
    crate::test_support::git_init(dir.path());
    crate::test_support::write_drep_toml(dir.path(), &format!("{}/v1", server.uri()));
    std::fs::write(dir.path().join("lib.py"), "x = 0\n").expect("lib.py");
    commit_all(dir.path(), "base");

    commit_rounds(dir.path(), 3).await;

    let cache = Cache::new(dir.path().join("named-cache"), 30, 8 * 1024 * 1024);
    let named = check::run_with(
        &args(vec![dir.path().join("lib.py")], None),
        dir.path(),
        cache.clone(),
    )
    .await
    .expect("named check");
    assert_eq!(named, check::Exit::Clean);

    std::fs::write(dir.path().join("lib.py"), "x = 1\n").expect("lib.py");
    crate::test_support::git_add(dir.path(), "lib.py");
    let mut staged = args(Vec::new(), None);
    staged.staged = true;
    let blocked = check::run_with(&staged, dir.path(), cache)
        .await
        .expect("bounded staged check");

    assert_eq!(blocked, check::Exit::Unanalyzed);
    assert_eq!(crate::test_support::request_count(&server).await, 1);
}

#[tokio::test]
async fn a_clean_staged_subset_does_not_reset_the_full_change_cycle() {
    let (dir, server) = setup_mock(r#"{"issues": []}"#).await;
    crate::test_support::git_init(dir.path());
    crate::test_support::write_drep_toml(dir.path(), &format!("{}/v1", server.uri()));
    std::fs::write(dir.path().join("lib.py"), "x = 0\n").expect("lib.py");
    commit_all(dir.path(), "base");

    commit_rounds(dir.path(), 3).await;

    // The cached staged result is clean, but staged input can be only a subset
    // of the branch. It must not clear a cycle that the full diff has not yet
    // completed.
    std::fs::write(dir.path().join("lib.py"), "x = 1\n").expect("lib.py");
    crate::test_support::git_add(dir.path(), "lib.py");
    let mut staged = args(Vec::new(), None);
    staged.staged = true;
    staged.max_review_rounds = Some(4);
    let cache = Cache::new(dir.path().join("staged-cache"), 30, 8 * 1024 * 1024);
    let clean = check::run_with(&staged, dir.path(), cache.clone())
        .await
        .expect("extended staged review");
    assert_eq!(clean, check::Exit::Clean);

    std::fs::write(dir.path().join("lib.py"), "x = 2\n").expect("lib.py");
    crate::test_support::git_add(dir.path(), "lib.py");
    staged.max_review_rounds = None;
    let blocked = check::run_with(&staged, dir.path(), cache)
        .await
        .expect("default staged review");
    assert_eq!(blocked, check::Exit::Unanalyzed);
    assert_eq!(crate::test_support::request_count(&server).await, 1);
}

#[tokio::test]
async fn pure_analysis_failure_refunds_the_reserved_round() {
    let (dir, server) = setup_mock("this is not JSON").await;
    crate::test_support::git_init(dir.path());
    crate::test_support::write_drep_toml(dir.path(), &format!("{}/v1", server.uri()));
    std::fs::write(dir.path().join("lib.py"), "x = 0\n").expect("lib.py");
    commit_all(dir.path(), "base");
    std::fs::write(dir.path().join("lib.py"), "x = 1\n").expect("lib.py");
    crate::test_support::git_add(dir.path(), "lib.py");
    let mut staged = args(Vec::new(), None);
    staged.staged = true;

    let exit = check::run_with(
        &staged,
        dir.path(),
        Cache::new(dir.path().join("failure-cache"), 30, 8 * 1024 * 1024),
    )
    .await
    .expect("failed analysis still returns a verdict");
    assert_eq!(exit, check::Exit::Unanalyzed);

    let budget = Budget::for_repo(dir.path(), 3).await.expect("budget");
    let Claim::Reserved(claim) = budget.claim().expect("round refunded") else {
        panic!("pure failure must not consume a round");
    };
    assert_eq!(claim.round(), 1);
}

#[tokio::test]
async fn mixed_actionable_finding_and_analysis_failure_consumes_the_round() {
    let (dir, server) = setup_mock(
        r#"{"issues":[{"line":1,"severity":"high","category":"bug","message":"real"},{"line":1,"severity":"unknown","category":"bug","message":"bad record"}]}"#,
    )
    .await;
    crate::test_support::git_init(dir.path());
    crate::test_support::write_drep_toml(dir.path(), &format!("{}/v1", server.uri()));
    std::fs::write(dir.path().join("lib.py"), "x = 0\n").expect("lib.py");
    commit_all(dir.path(), "base");
    std::fs::write(dir.path().join("lib.py"), "x = 1\n").expect("lib.py");
    crate::test_support::git_add(dir.path(), "lib.py");
    let mut staged = args(Vec::new(), None);
    staged.staged = true;

    let exit = check::run_with(
        &staged,
        dir.path(),
        Cache::new(dir.path().join("mixed-cache"), 30, 8 * 1024 * 1024),
    )
    .await
    .expect("mixed result returns a verdict");
    assert_eq!(exit, check::Exit::Unanalyzed);

    let budget = Budget::for_repo(dir.path(), 3).await.expect("budget");
    let Claim::Reserved(claim) = budget.claim().expect("next round") else {
        panic!("two rounds should remain");
    };
    assert_eq!(claim.round(), 2);
}

#[tokio::test]
async fn an_acknowledged_live_finding_does_not_consume_a_round() {
    let (dir, server) = setup_mock(
        r#"{"issues":[{"line":1,"severity":"high","category":"bug","message":"known false positive"}]}"#,
    )
    .await;
    crate::test_support::git_init(dir.path());
    crate::test_support::write_drep_toml(dir.path(), &format!("{}/v1", server.uri()));
    std::fs::write(dir.path().join("lib.py"), "x = 0\n").expect("lib.py");
    commit_all(dir.path(), "base");
    std::fs::write(dir.path().join("lib.py"), "x = 1\n").expect("lib.py");
    crate::test_support::git_add(dir.path(), "lib.py");

    let mut candidate = vec![Finding {
        kind: "bug".to_owned(),
        severity: Severity::Error,
        file_path: "lib.py".to_owned(),
        line: 1,
        column: None,
        message: "known false positive".to_owned(),
        suggestion: None,
        asserts_compile_failure: false,
        fingerprint: None,
    }];
    let hunks = vec![vec![Hunk::whole_file(PathBuf::from("lib.py"), "x = 1\n")]];
    crate::analysis::acknowledgements::apply(&mut candidate, &hunks, &Store::default());
    let mut store = Store::default();
    store.insert(
        candidate[0]
            .fingerprint
            .clone()
            .expect("source-sensitive fingerprint"),
    );
    store.save(dir.path()).expect("save acknowledgement");

    let mut staged = args(Vec::new(), None);
    staged.staged = true;
    let exit = check::run_with(
        &staged,
        dir.path(),
        Cache::new(dir.path().join("acknowledged-cache"), 30, 8 * 1024 * 1024),
    )
    .await
    .expect("acknowledged review");

    assert_eq!(exit, check::Exit::Clean);
    assert_eq!(crate::test_support::request_count(&server).await, 1);
    let budget = Budget::for_repo(dir.path(), 3).await.expect("budget");
    let Claim::Reserved(claim) = budget.claim().expect("round one") else {
        panic!("the acknowledged finding must refund the reservation");
    };
    assert_eq!(claim.round(), 1);
}

#[tokio::test]
async fn a_compiler_disproved_live_finding_does_not_consume_a_round() {
    let (dir, server) = setup_mock(
        r#"{"issues":[{"line":1,"severity":"high","category":"bug","message":"this does not compile","compile_failure":true}]}"#,
    )
    .await;
    crate::test_support::git_init(dir.path());
    crate::test_support::write_drep_toml(dir.path(), &format!("{}/v1", server.uri()));
    std::fs::create_dir(dir.path().join("src")).expect("src directory");
    std::fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"fixture\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
    )
    .expect("Cargo.toml");
    std::fs::write(
        dir.path().join("src/lib.rs"),
        "pub fn value() -> u8 { 0 }\n",
    )
    .expect("lib.rs");
    commit_all(dir.path(), "base");
    std::fs::write(
        dir.path().join("src/lib.rs"),
        "pub fn value() -> u8 { 1 }\n",
    )
    .expect("lib.rs");
    crate::test_support::git_add(dir.path(), "src/lib.rs");

    let mut staged = args(Vec::new(), None);
    staged.staged = true;
    let exit = check::run_with(
        &staged,
        dir.path(),
        Cache::new(dir.path().join("compile-cache"), 30, 8 * 1024 * 1024),
    )
    .await
    .expect("compiler-grounded review");

    assert_eq!(exit, check::Exit::Clean);
    assert_eq!(crate::test_support::request_count(&server).await, 1);
    let budget = Budget::for_repo(dir.path(), 3).await.expect("budget");
    let Claim::Reserved(claim) = budget.claim().expect("round one") else {
        panic!("the disproved finding must refund the reservation");
    };
    assert_eq!(claim.round(), 1);
}

#[tokio::test]
async fn deterministic_findings_prevent_a_full_diff_from_resetting_the_cycle() {
    let (dir, server) = setup_mock(r#"{"issues": []}"#).await;
    crate::test_support::git_init(dir.path());
    crate::test_support::write_drep_toml(dir.path(), &format!("{}/v1", server.uri()));
    std::fs::write(dir.path().join("pyproject.toml"), "").expect("pyproject.toml");
    std::fs::create_dir_all(dir.path().join("venv/bin")).expect("venv bin");
    write_executable(
        &dir.path().join("venv/bin/ruff"),
        "#!/bin/sh\nprintf '%s' '[{\"code\":\"F401\",\"filename\":\"lib.py\",\"location\":{\"row\":1,\"column\":1},\"message\":\"unused import\"}]'\n",
    );
    std::fs::write(dir.path().join("lib.py"), "x = 0\n").expect("lib.py");
    commit_all(dir.path(), "base");
    let base = git_head(dir.path());
    std::fs::write(dir.path().join("lib.py"), "x = 1\n").expect("lib.py");
    commit_all(dir.path(), "change one");

    commit_rounds(dir.path(), 3).await;

    let cache = Cache::new(dir.path().join("tool-cache"), 30, 8 * 1024 * 1024);
    let mut diff = args(Vec::new(), None);
    diff.diff = Some(base.clone());
    diff.max_review_rounds = Some(4);
    let with_tool_finding = check::run_with(&diff, dir.path(), cache.clone())
        .await
        .expect("extended full diff");
    assert_eq!(with_tool_finding, check::Exit::FoundIssues);

    std::fs::write(dir.path().join("lib.py"), "x = 2\n").expect("lib.py");
    commit_all(dir.path(), "change two");
    diff.max_review_rounds = None;
    let still_bounded = check::run_with(&diff, dir.path(), cache)
        .await
        .expect("default full diff");

    assert_eq!(still_bounded, check::Exit::Unanalyzed);
    assert_eq!(crate::test_support::request_count(&server).await, 1);
}