cargo-impact 0.5.0

Blast-radius analysis and selective test execution for Rust workspaces
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
//! End-to-end integration test: exercises the full `cargo-impact` binary
//! against a seeded git fixture, parses the JSON output, and asserts the
//! expected findings flow through from git diff to structured report.
//!
//! Runs the *release* binary that cargo stamps into
//! `CARGO_BIN_EXE_cargo-impact` for integration tests (see the
//! [cargo book](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates)).
//! This catches regressions that per-module unit tests can't โ€” argv
//! stripping, feature resolution, orchestrator ordering, JSON envelope
//! stability, and the overall exit-code contract.

use serde_json::Value;
use std::fs;
use std::path::Path;
use std::process::Command;
use tempfile::TempDir;

/// Location of the built binary. Cargo sets this env var at compile time
/// for every integration test in this crate.
fn binary() -> &'static str {
    env!("CARGO_BIN_EXE_cargo-impact")
}

/// Run `git` in `dir` and panic if it fails โ€” integration-test hygiene.
fn git(dir: &Path, args: &[&str]) {
    let status = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .status()
        .expect("spawn git");
    assert!(status.success(), "git {args:?} failed in {}", dir.display());
}

/// Seed a single-crate git repo with an initial commit, then overwrite
/// files per `modifications` so the working tree holds the "after" state.
/// Returns the temp dir so callers can run `cargo-impact` against it.
fn seed_repo(initial: &[(&str, &str)], modifications: &[(&str, &str)]) -> TempDir {
    let dir = TempDir::new().expect("tempdir");
    let root = dir.path();

    git(root, &["init", "-q"]);
    git(root, &["config", "user.email", "t@t"]);
    git(root, &["config", "user.name", "t"]);
    git(root, &["config", "commit.gpgsign", "false"]);
    // Windows defaults `core.autocrlf = true`, which mutates the index
    // version of committed files and can make our diff-vs-WT comparison
    // observe phantom differences (or miss real ones) on that platform.
    // Hold line endings verbatim across init/add/commit.
    git(root, &["config", "core.autocrlf", "false"]);
    // `-B` (create-or-reset) instead of `-b`: handles the case where
    // `git init`'s default branch is already `main` (git 2.28+ with
    // `init.defaultBranch = main`, common on CI runners).
    git(root, &["checkout", "-q", "-B", "main"]);

    for (rel, body) in initial {
        let path = root.join(rel);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(&path, body).unwrap();
    }
    git(root, &["add", "-A"]);
    git(root, &["commit", "-q", "-m", "init"]);

    for (rel, body) in modifications {
        let path = root.join(rel);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(&path, body).unwrap();
    }

    dir
}

/// Run `cargo-impact` against a fixture root, capturing stdout. Returns
/// (stdout, exit_code). Never panics on non-zero โ€” tests assert
/// explicitly. On failure the stderr is eprintln'd so it surfaces in
/// nextest's per-test output when the caller's assertion fires
/// (especially useful for Windows CI where we can't pull per-test
/// logs without repo-admin auth).
fn run_impact(root: &Path, extra_args: &[&str]) -> (String, i32) {
    let mut cmd = Command::new(binary());
    cmd.arg("--manifest-dir").arg(root);
    for a in extra_args {
        cmd.arg(a);
    }
    let output = cmd.output().expect("spawn cargo-impact");
    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
    let stderr = String::from_utf8_lossy(&output.stderr);
    let code = output.status.code().unwrap_or(-1);
    // Exit 0 = clean, 1 = --fail-on tripped (expected by one test). Any
    // other code means cargo-impact itself blew up โ€” surface its stderr.
    if code != 0 && code != 1 {
        eprintln!(
            "cargo-impact exited with code {code}\n\
             args: --manifest-dir <tmp> {}\n\
             stderr:\n{stderr}",
            extra_args.join(" ")
        );
    }
    (stdout, code)
}

fn manifest() -> &'static str {
    "[package]\nname = \"fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[lib]\npath = \"src/lib.rs\"\n"
}

// ---------------------------------------------------------------------------

#[test]
fn clean_workspace_reports_no_findings_and_exits_zero() {
    let body = "pub fn untouched() {}\n";
    let dir = seed_repo(
        &[("Cargo.toml", manifest()), ("src/lib.rs", body)],
        // No modifications = clean working tree.
        &[],
    );
    let (stdout, code) = run_impact(dir.path(), &["--format", "json"]);
    assert_eq!(code, 0, "clean workspace exit code; stdout:\n{stdout}");

    let report: Value = serde_json::from_str(&stdout).expect("parse JSON");
    assert_eq!(report["summary"]["total"], 0);
    assert!(report["findings"].as_array().unwrap().is_empty());
}

#[test]
fn clean_workspace_context_mode_emits_empty_file_list() {
    let body = "pub fn untouched() {}\n";
    let dir = seed_repo(
        &[("Cargo.toml", manifest()), ("src/lib.rs", body)],
        // No modifications = clean working tree.
        &[],
    );
    let (stdout, code) = run_impact(dir.path(), &["--context"]);
    assert_eq!(code, 0, "clean --context exit code; stdout:\n{stdout}");
    assert_eq!(
        stdout, "",
        "--context must be a pure file-list stream; clean trees should not emit prose"
    );
}

#[test]
fn trait_signature_change_emits_high_severity_findings() {
    let dir = seed_repo(
        &[
            ("Cargo.toml", manifest()),
            (
                "src/lib.rs",
                // One trait, one impl, one test that references the impl.
                "pub trait Greeter { fn hi(&self) -> u32; }\n\
                 pub struct Friend;\n\
                 impl Greeter for Friend { fn hi(&self) -> u32 { 1 } }\n\
                 \n\
                 #[cfg(test)]\n\
                 mod tests {\n\
                 use super::*;\n\
                 #[test] fn greets() { let _ = Friend.hi(); }\n\
                 }\n",
            ),
        ],
        // Modify the trait's required-method signature (return type flip).
        &[(
            "src/lib.rs",
            "pub trait Greeter { fn hi(&self) -> String; }\n\
             pub struct Friend;\n\
             impl Greeter for Friend { fn hi(&self) -> String { String::new() } }\n\
             \n\
             #[cfg(test)]\n\
             mod tests {\n\
             use super::*;\n\
             #[test] fn greets() { let _ = Friend.hi(); }\n\
             }\n",
        )],
    );
    let (stdout, code) = run_impact(dir.path(), &["--format", "json"]);
    assert_eq!(code, 0, "no --fail-on; stdout:\n{stdout}");

    let report: Value = serde_json::from_str(&stdout).expect("parse JSON");
    let findings = report["findings"].as_array().expect("findings array");
    assert!(
        !findings.is_empty(),
        "expected findings for a trait signature change; got none"
    );

    let kinds: Vec<&str> = findings.iter().filter_map(|f| f["kind"].as_str()).collect();
    assert!(
        kinds.contains(&"trait_definition_change"),
        "expected trait_definition_change finding; kinds = {kinds:?}"
    );
    assert!(
        kinds.contains(&"trait_impl"),
        "expected trait_impl finding; kinds = {kinds:?}"
    );
    // Severity bucket for a required-method sig change is High.
    assert!(report["summary"]["by_severity"]["high"].as_u64().unwrap() >= 1);
}

#[test]
fn fail_on_high_exits_nonzero_when_high_severity_finding_present() {
    let dir = seed_repo(
        &[
            ("Cargo.toml", manifest()),
            (
                "src/lib.rs",
                "pub trait Greeter { fn hi(&self); }\n\
                 pub struct F;\n\
                 impl Greeter for F { fn hi(&self) {} }\n",
            ),
        ],
        &[(
            "src/lib.rs",
            // Required-method sig change โ†’ High / Likely.
            "pub trait Greeter { fn hi(&self, n: u32); }\n\
             pub struct F;\n\
             impl Greeter for F { fn hi(&self, n: u32) { let _ = n; } }\n",
        )],
    );
    let (_stdout, code) = run_impact(dir.path(), &["--format", "json", "--fail-on", "high"]);
    assert_eq!(code, 1, "--fail-on high should trip on trait sig change");
}

#[test]
fn derive_of_changed_trait_is_flagged() {
    let dir = seed_repo(
        &[
            ("Cargo.toml", manifest()),
            (
                "src/lib.rs",
                "pub trait Bundle {}\n\
                 pub struct User;\n",
            ),
        ],
        &[(
            "src/lib.rs",
            // Trait gains a method (required, since no default) AND a
            // user-defined struct acquires `#[derive(Bundle)]`.
            "pub trait Bundle { fn count(&self) -> u32; }\n\
             #[derive(Bundle)]\n\
             pub struct User;\n",
        )],
    );
    let (stdout, _code) = run_impact(dir.path(), &["--format", "json"]);
    let report: Value = serde_json::from_str(&stdout).expect("parse JSON");
    let findings = report["findings"].as_array().unwrap();
    let kinds: Vec<&str> = findings.iter().filter_map(|f| f["kind"].as_str()).collect();
    assert!(
        kinds.contains(&"derived_trait_impl"),
        "expected derived_trait_impl finding; kinds = {kinds:?}"
    );
}

#[test]
fn test_flag_emits_nextest_filter_expression() {
    let dir = seed_repo(
        &[
            ("Cargo.toml", manifest()),
            (
                "src/lib.rs",
                "pub fn engine() -> u32 { 0 }\n\
                 #[cfg(test)] mod tests {\n\
                 use super::*;\n\
                 #[test] fn uses_engine() { let _ = engine(); }\n\
                 }\n",
            ),
        ],
        &[(
            "src/lib.rs",
            "pub fn engine() -> u32 { 1 }\n\
             #[cfg(test)] mod tests {\n\
             use super::*;\n\
             #[test] fn uses_engine() { let _ = engine(); }\n\
             }\n",
        )],
    );
    let (stdout, code) = run_impact(dir.path(), &["--test"]);
    assert_eq!(code, 0);
    assert!(
        stdout.contains("test(uses_engine)"),
        "expected nextest filter to include the affected test; got {stdout:?}"
    );
}

#[test]
fn mcp_version_tool_responds_to_tools_call_over_stdio() {
    // Spawn the MCP server and pipe a single `tools/call impact_version`
    // request. Small JSON-RPC smoke test that proves the subcommand
    // dispatch + protocol handler + tool invocation all work end to end.
    use std::io::Write;
    use std::process::Stdio;

    let mut child = Command::new(binary())
        .arg("mcp")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn mcp server");

    let stdin = child.stdin.as_mut().expect("stdin handle");
    let req = r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"impact_version","arguments":{}}}"#;
    writeln!(stdin, "{req}").expect("write");
    // Closing stdin signals EOF so the server's line loop terminates.
    drop(child.stdin.take());

    let out = child.wait_with_output().expect("wait");
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        out.status.success(),
        "mcp server exited non-zero ({:?})\nstdout:\n{stdout}\nstderr:\n{stderr}",
        out.status.code()
    );

    // Response is one JSON line; parse it.
    let line = stdout
        .lines()
        .find(|l| !l.trim().is_empty())
        .unwrap_or_else(|| {
            panic!("no response on mcp stdout\nstdout:\n{stdout}\nstderr:\n{stderr}")
        });
    let resp: Value = serde_json::from_str(line)
        .unwrap_or_else(|e| panic!("parse response `{line}`: {e}\nstderr:\n{stderr}"));
    assert_eq!(resp["jsonrpc"], "2.0");
    assert_eq!(resp["id"], 1);
    let text = resp["result"]["content"][0]["text"].as_str().unwrap();
    assert!(
        !text.is_empty() && text.chars().any(|c| c.is_ascii_digit()),
        "expected a version string, got {text:?}"
    );
}

#[cfg(unix)]
#[test]
fn macro_expand_flag_is_graceful_when_tool_is_unavailable() {
    // Ensures the CLI accepts --macro-expand and degrades cleanly
    // when `cargo-expand` is missing from PATH. Removing the tool
    // from PATH is the reliable cross-platform way to simulate
    // "tool not installed" without uninstalling the user's actual
    // cargo-expand binary โ€” we scrub PATH for the child, not ours.
    //
    // On a fresh CI runner cargo-expand is usually absent anyway,
    // so this doubles as the "tool missing" path coverage without
    // needing a branch on `is_installed()`.
    let dir = seed_repo(
        &[
            ("Cargo.toml", manifest()),
            ("src/lib.rs", "pub trait T { fn hi(&self); }\n"),
        ],
        &[("src/lib.rs", "pub trait T { fn hi(&self) -> String; }\n")],
    );

    // PATH is trimmed to system dirs only โ€” enough for `git` (which
    // the analyzer shells to) but essentially guaranteed not to contain
    // cargo-expand, which normally lives under `~/.cargo/bin` on end-
    // user machines. The goal is to exercise the "tool not installed"
    // branch deterministically regardless of host setup.
    let slim_path = "/usr/bin:/bin";
    let mut cmd = Command::new(binary());
    cmd.arg("--manifest-dir")
        .arg(dir.path())
        .arg("--macro-expand")
        .arg("--format")
        .arg("json")
        .env("PATH", slim_path);
    let out = cmd.output().expect("spawn cargo-impact");
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);

    // Whether or not cargo-expand was found, the run must not crash
    // on the --macro-expand flag alone, and must still emit a
    // well-formed JSON report.
    assert!(
        out.status.success(),
        "--macro-expand caused non-zero exit unexpectedly. stdout:\n{stdout}\nstderr:\n{stderr}"
    );
    let _: Value = serde_json::from_str(&stdout).unwrap_or_else(|e| {
        panic!(
            "invalid JSON output with --macro-expand. stdout:\n{stdout}\nstderr:\n{stderr}\nerr: {e}"
        )
    });
    // With PATH scrubbed, the stderr notice must mention the missing
    // tool so users know why they got no expansion-backed findings.
    assert!(
        stderr.contains("cargo-expand") || stderr.contains("macro-expand"),
        "expected stderr to mention cargo-expand when the tool is unavailable. stderr:\n{stderr}"
    );
}

#[test]
fn feature_powerset_surfaces_findings_hidden_under_default_features() {
    // Fixture: a trait and two impls โ€” one visible at defaults, the
    // other gated behind `feature = "extra"`. Changing the trait should
    // surface BOTH impls under --feature-powerset (because --all-features
    // activates "extra"), even though the baseline-feature view only
    // sees the unconditional impl.
    let cargo_toml = "[package]\nname=\"fixture\"\nversion=\"0.1.0\"\nedition=\"2021\"\n\
         [features]\ndefault = []\nextra = []\n\
         [lib]\npath=\"src/lib.rs\"\n";
    let initial_src = "pub trait Greeter { fn hi(&self) -> u32; }\n\
         pub struct Always;\n\
         impl Greeter for Always { fn hi(&self) -> u32 { 1 } }\n\
         #[cfg(feature = \"extra\")]\n\
         pub struct Gated;\n\
         #[cfg(feature = \"extra\")]\n\
         impl Greeter for Gated { fn hi(&self) -> u32 { 2 } }\n";
    let changed_src = "pub trait Greeter { fn hi(&self) -> String; }\n\
         pub struct Always;\n\
         impl Greeter for Always { fn hi(&self) -> String { String::new() } }\n\
         #[cfg(feature = \"extra\")]\n\
         pub struct Gated;\n\
         #[cfg(feature = \"extra\")]\n\
         impl Greeter for Gated { fn hi(&self) -> String { String::new() } }\n";
    let dir = seed_repo(
        &[("Cargo.toml", cargo_toml), ("src/lib.rs", initial_src)],
        &[("src/lib.rs", changed_src)],
    );

    // Baseline run (default features only; `extra` is off).
    let (baseline_out, baseline_code) = run_impact(dir.path(), &["--format", "json"]);
    assert_eq!(baseline_code, 0, "baseline should exit 0: {baseline_out}");
    let baseline: Value = serde_json::from_str(&baseline_out).expect("parse baseline json");
    let baseline_evidence: Vec<String> = baseline["findings"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|f| f["evidence"].as_str().map(str::to_string))
        .collect();
    assert!(
        !baseline_evidence.iter().any(|e| e.contains("Gated")),
        "baseline view must NOT mention `Gated` โ€” it's behind a feature gate. Got: {baseline_evidence:?}"
    );

    // Powerset run: --all-features activates `extra`, so the gated
    // impl becomes visible and should surface with the annotation.
    let (powerset_out, powerset_code) =
        run_impact(dir.path(), &["--format", "json", "--feature-powerset"]);
    assert_eq!(powerset_code, 0, "powerset should exit 0: {powerset_out}");
    let powerset: Value = serde_json::from_str(&powerset_out).expect("parse powerset json");
    let powerset_evidence: Vec<String> = powerset["findings"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|f| f["evidence"].as_str().map(str::to_string))
        .collect();
    let gated_hit = powerset_evidence
        .iter()
        .find(|e| e.contains("Gated"))
        .unwrap_or_else(|| {
            panic!(
                "powerset view must surface the `Gated` impl. Got evidence: {powerset_evidence:?}"
            )
        });
    assert!(
        gated_hit.contains("--all-features"),
        "feature-revealed finding must be annotated with the set that revealed it. Got: {gated_hit}"
    );
}

#[test]
fn mcp_impact_analyze_streams_progress_notifications_before_result() {
    // When a client calls `tools/call impact_analyze`, the server must
    // emit one or more `notifications/message` events describing stage
    // progress BEFORE the final `result` arrives. This is the contract
    // that lets long-running analyses show live feedback instead of a
    // 30-second silence.
    use std::io::Write;
    use std::process::Stdio;

    // Non-trivial workspace so progress has content to emit on (the
    // pipeline short-circuits on an empty diff and emits nothing).
    let dir = seed_repo(
        &[
            ("Cargo.toml", manifest()),
            ("src/lib.rs", "pub trait T { fn hi(&self); }\n"),
        ],
        &[("src/lib.rs", "pub trait T { fn hi(&self) -> String; }\n")],
    );

    let mut child = Command::new(binary())
        .arg("mcp")
        .current_dir(dir.path())
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn mcp server");

    let stdin = child.stdin.as_mut().expect("stdin");
    let manifest_dir = dir.path().to_string_lossy().replace('\\', "/");
    let req = format!(
        r#"{{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{{"name":"impact_analyze","arguments":{{"manifest_dir":"{manifest_dir}"}}}}}}"#
    );
    writeln!(stdin, "{req}").expect("write");
    drop(child.stdin.take());

    let out = child.wait_with_output().expect("wait");
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        out.status.success(),
        "mcp server exited non-zero ({:?})\nstdout:\n{stdout}\nstderr:\n{stderr}",
        out.status.code()
    );

    // Parse every non-empty line. Expect at least one notification
    // message followed by exactly one result with id=7.
    let mut notifications = Vec::new();
    let mut result: Option<Value> = None;
    for line in stdout.lines().filter(|l| !l.trim().is_empty()) {
        let v: Value = serde_json::from_str(line).unwrap_or_else(|e| {
            panic!("parse line `{line}`: {e}\nfull stdout:\n{stdout}\nstderr:\n{stderr}")
        });
        if v["method"] == "notifications/message" {
            notifications.push(v);
        } else if v["id"] == 7 {
            result = Some(v);
        }
    }

    assert!(
        !notifications.is_empty(),
        "expected at least one progress notification; full stdout:\n{stdout}"
    );
    // Structural check on the first notification.
    let first = &notifications[0];
    assert_eq!(first["params"]["level"], "info");
    assert!(
        first["params"]["data"]["stage"].is_string(),
        "notification data must carry a stage string; got {first}"
    );

    // A final `done` stage event must appear before the result so
    // clients can transition their progress UI to complete.
    let has_done = notifications
        .iter()
        .any(|n| n["params"]["data"]["stage"] == "done");
    assert!(
        has_done,
        "expected a `done` progress event; stages seen: {:?}",
        notifications
            .iter()
            .map(|n| n["params"]["data"]["stage"].as_str().unwrap_or(""))
            .collect::<Vec<_>>()
    );

    let result = result.expect("no result envelope on stdout");
    assert!(result["result"]["content"][0]["text"].is_string());
}

#[test]
fn json_output_schema_is_stable() {
    // Agents and CI scripts consume this shape โ€” treat it as a contract.
    // If these fields ever need to change, update the schema document in
    // README ยง8 first, then update this assertion.
    let dir = seed_repo(
        &[
            ("Cargo.toml", manifest()),
            ("src/lib.rs", "pub fn a() {}\n"),
        ],
        &[("src/lib.rs", "pub fn a() { let _ = 1; }\n")],
    );
    let (stdout, _code) = run_impact(dir.path(), &["--format", "json"]);
    let report: Value = serde_json::from_str(&stdout).expect("parse JSON");

    for field in [
        "version",
        "changed_files",
        "candidate_symbols",
        "findings",
        "summary",
    ] {
        assert!(
            !report[field].is_null(),
            "JSON envelope missing required field `{field}`; got:\n{stdout}"
        );
    }
    for field in ["total", "by_severity", "by_tier"] {
        assert!(
            !report["summary"][field].is_null(),
            "summary missing `{field}`"
        );
    }
}

#[test]
fn output_is_byte_identical_across_two_runs_for_every_format() {
    // Determinism gate (v0.4 core): two invocations of cargo-impact on
    // the same fixture must produce byte-identical stdout across every
    // format. CI jobs that cache by content hash and PR-diff tools that
    // compare across runs rely on this; if any format leaks a timestamp
    // or HashMap-ordered field, this test catches it.
    let dir = seed_repo(
        &[
            ("Cargo.toml", manifest()),
            (
                "src/lib.rs",
                "pub trait Greeter { fn hi(&self); }\n\
                 pub struct F;\n\
                 impl Greeter for F { fn hi(&self) {} }\n\
                 #[cfg(test)] mod tests {\n\
                 use super::*;\n\
                 #[test] fn smoke() { F.hi(); }\n\
                 }\n",
            ),
        ],
        &[(
            "src/lib.rs",
            "pub trait Greeter { fn hi(&self, n: u32); }\n\
             pub struct F;\n\
             impl Greeter for F { fn hi(&self, n: u32) { let _ = n; } }\n\
             #[cfg(test)] mod tests {\n\
             use super::*;\n\
             #[test] fn smoke() { F.hi(1); }\n\
             }\n",
        )],
    );

    // Every user-facing format must be byte-stable. Include --test
    // (which emits the nextest filter expression) too since that path
    // is also consumed by downstream scripts.
    for args in [
        vec!["--format", "text"],
        vec!["--format", "markdown"],
        vec!["--format", "json"],
        vec!["--format", "sarif"],
        vec!["--format", "pr-comment"],
        vec!["--test"],
    ] {
        let (first, code_a) = run_impact(dir.path(), &args);
        let (second, code_b) = run_impact(dir.path(), &args);
        assert_eq!(code_a, code_b, "exit codes diverged for {args:?}");
        assert_eq!(
            first, second,
            "stdout diverged for {args:?}\n--- first ---\n{first}\n--- second ---\n{second}"
        );
    }
}