tga 2.19.0

Developer productivity analytics — git commit collection, classification, and reporting
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
//! Tests for the AUDIT sweep and the `tga audit` clap wiring.

use std::time::Instant;

use clap::{Args as _, FromArgMatches, Parser};

use crate::audit::{run_full_sweep, AuditSweepStats, StageStatus, SweepOptions, SweepStage};
use crate::commands::audit::AuditArgs;
use crate::core::config::Config;
use crate::core::db::Database;
use crate::core::progress::{ProgressBus, Stage};

/// The order `run_full_sweep` is contracted to execute in.
///
/// Data-flow order, not DOC-67 §5's prose order — deployments and incidents
/// populate what dora reduces, and report renders what everything else wrote.
const EXPECTED_ORDER: [SweepStage; 8] = [
    SweepStage::Collect,
    SweepStage::Classify,
    SweepStage::JiraSync,
    SweepStage::Deployments,
    SweepStage::Incidents,
    SweepStage::Dora,
    SweepStage::PrMetrics,
    SweepStage::Report,
];

// ---------------------------------------------------------------------------
// AuditSweepStats — per-stage outcome reporting, including a failing stage
// ---------------------------------------------------------------------------

#[test]
fn failed_stage_is_recorded_and_does_not_stop_the_sweep() {
    let mut stats = AuditSweepStats::default();

    stats.record(SweepStage::Collect, Instant::now(), Ok(()));
    stats.record(
        SweepStage::JiraSync,
        Instant::now(),
        Err(anyhow::anyhow!("no JIRA project configured")),
    );
    stats.record(SweepStage::Report, Instant::now(), Ok(()));

    // Every stage recorded, in call order — the failure did not truncate the run.
    let stages: Vec<_> = stats.outcomes.iter().map(|o| o.stage).collect();
    assert_eq!(
        stages,
        vec![
            SweepStage::Collect,
            SweepStage::JiraSync,
            SweepStage::Report
        ]
    );

    // The failure is individually observable, with its message intact.
    let failures: Vec<_> = stats.failures().collect();
    assert_eq!(failures.len(), 1);
    assert_eq!(failures[0].stage, SweepStage::JiraSync);
    assert_eq!(
        failures[0].status,
        StageStatus::Failed("no JIRA project configured".to_string())
    );
    assert!(stats.any_failed());
}

#[test]
fn error_cause_chain_is_preserved_in_the_stage_record() {
    let mut stats = AuditSweepStats::default();
    let err = anyhow::anyhow!("connection refused").context("fetching deploy events");

    stats.record(SweepStage::Deployments, Instant::now(), Err(err));

    let StageStatus::Failed(msg) = &stats.outcomes[0].status else {
        panic!("expected a failed status");
    };
    assert!(
        msg.contains("fetching deploy events") && msg.contains("connection refused"),
        "cause chain lost: {msg}"
    );
}

#[test]
fn summary_counts_successes_and_failures() {
    let mut stats = AuditSweepStats::default();
    assert_eq!(stats.summary(), "0 of 0 stage(s) succeeded");
    assert!(!stats.any_failed());

    stats.record(SweepStage::Collect, Instant::now(), Ok(()));
    stats.record(
        SweepStage::Dora,
        Instant::now(),
        Err(anyhow::anyhow!("boom")),
    );
    assert_eq!(stats.summary(), "1 of 2 stage(s) succeeded");
}

#[test]
fn stage_names_match_their_subcommands() {
    assert_eq!(SweepStage::JiraSync.as_str(), "jira sync");
    assert_eq!(SweepStage::PrMetrics.to_string(), "pr-metrics");
    assert_eq!(SweepStage::Deployments.as_str(), "deployments collect");
}

// ---------------------------------------------------------------------------
// run_full_sweep — sequencing over a real (empty) database
// ---------------------------------------------------------------------------

/// An empty config has no repositories, no JIRA, and no DORA sources, so no
/// stage touches the network. Stages that need configuration that is absent
/// fail — which is the point: the sweep must record them and keep going.
#[tokio::test]
async fn sweep_runs_every_stage_in_order_and_survives_failures() {
    let dir = tempfile::tempdir().expect("tempdir");
    let mut db = Database::open(&dir.path().join("tga.db")).expect("open db");
    let options = SweepOptions {
        output: Some(dir.path().join("out")),
        weeks: Some(1),
    };

    let stats = run_full_sweep(&Config::default(), &mut db, &options, None)
        .await
        .expect("sequencing itself must not fail");

    let stages: Vec<_> = stats.outcomes.iter().map(|o| o.stage).collect();
    assert_eq!(stages, EXPECTED_ORDER.to_vec());
    // The "stage N of 8" denominator in the progress start events is this
    // constant; a stage added without updating it would lie to the operator.
    assert_eq!(stages.len(), super::sweep::TOTAL_STAGES);

    // JIRA is unconfigured here, so that stage must have failed — and the
    // seven stages after it must still have run.
    assert!(
        stats.any_failed(),
        "an unconfigured JIRA sync should have been recorded as a failure"
    );
    assert!(
        stats.failures().any(|o| o.stage == SweepStage::JiraSync),
        "expected the jira sync stage among the failures, got {:?}",
        stats.failures().map(|o| o.stage).collect::<Vec<_>>()
    );
    let jira_index = stages
        .iter()
        .position(|s| *s == SweepStage::JiraSync)
        .expect("jira stage present");
    assert_eq!(
        &stages[jira_index + 1..],
        &EXPECTED_ORDER[jira_index + 1..],
        "stages after the failing jira-sync stage should still have run, but were missing"
    );
}

#[tokio::test]
async fn sweep_writes_reports_into_the_requested_directory() {
    let dir = tempfile::tempdir().expect("tempdir");
    let out = dir.path().join("audit-out");
    let mut db = Database::open(&dir.path().join("tga.db")).expect("open db");
    let options = SweepOptions {
        output: Some(out.clone()),
        weeks: None,
    };

    let stats = run_full_sweep(&Config::default(), &mut db, &options, None)
        .await
        .expect("sweep");

    let report = stats
        .outcomes
        .iter()
        .find(|o| o.stage == SweepStage::Report)
        .expect("report stage ran");
    assert_eq!(
        report.status,
        StageStatus::Succeeded,
        "report stage failed: {:?}",
        report.status
    );
    assert!(
        out.is_dir(),
        "report stage did not create {}",
        out.display()
    );

    // `is_dir()` alone would pass for a sweep that creates the directory and
    // writes nothing, so assert the artifacts themselves. `summary.csv` and
    // `report.json` are fixed names from the CSV and JSON formatters, and
    // `pr-metrics.csv` is the name the sweep hands `pr-metrics --output`.
    let written: Vec<String> = std::fs::read_dir(&out)
        .expect("read report dir")
        .map(|e| {
            e.expect("dir entry")
                .file_name()
                .to_string_lossy()
                .into_owned()
        })
        .collect();
    assert!(
        written.len() > 1,
        "report stage wrote {} file(s) into {}: {written:?}",
        written.len(),
        out.display()
    );
    for expected in [
        crate::report::formatters::csv::SUMMARY_CSV,
        crate::report::formatters::json::REPORT_JSON,
        "pr-metrics.csv",
    ] {
        assert!(
            out.join(expected).is_file(),
            "expected artifact {expected} missing from {}: {written:?}",
            out.display()
        );
    }
}

// ---------------------------------------------------------------------------
// Progress reporting from every stage, not just collection (#5361)
// ---------------------------------------------------------------------------

/// #5361: `run_full_sweep` used to bind and discard its `progress` parameter,
/// so a caller that supplied a bus saw nothing for classify, report, pr-metrics,
/// jira sync, dora, deployments, or incidents — a ~10-minute sweep behind a
/// frozen screen. This asserts the non-collection stages reach the bus the
/// caller passed in; before the fix the drained event list is empty.
#[tokio::test]
async fn sweep_emits_progress_for_non_collection_stages() {
    let dir = tempfile::tempdir().expect("tempdir");
    let mut db = Database::open(&dir.path().join("tga.db")).expect("open db");
    let options = SweepOptions {
        output: Some(dir.path().join("out")),
        weeks: Some(1),
    };
    let bus = ProgressBus::new();

    let stats = run_full_sweep(&Config::default(), &mut db, &options, Some(&bus))
        .await
        .expect("sweep");

    let events = bus.drain();
    assert_eq!(bus.dropped(), 0, "the run must fit in the default ring");
    assert!(
        !events.is_empty(),
        "a bus handed to run_full_sweep received nothing at all"
    );

    // Report and classify are the stages furthest from collection: neither has
    // any instrumentation of its own, so if the parameter is not threaded they
    // are silent no matter what the collection pipeline does.
    for stage in [SweepStage::Classify, SweepStage::Report] {
        let mine: Vec<_> = events
            .iter()
            .filter(|e| e.stage == Stage::Audit && e.target == stage.as_str())
            .collect();
        assert!(
            mine.iter().any(|e| !e.is_terminal()),
            "no start event for the {stage} stage: {events:#?}"
        );
        assert!(
            mine.iter().any(|e| e.is_terminal()),
            "no completion event for the {stage} stage: {events:#?}"
        );
    }

    // Every stage, not just those two — and the bus's verdict agrees with the
    // recorded one, so a stage cannot report green on screen and red in stats.
    for outcome in &stats.outcomes {
        let terminal = events
            .iter()
            .find(|e| {
                e.stage == Stage::Audit && e.target == outcome.stage.as_str() && e.is_terminal()
            })
            .unwrap_or_else(|| panic!("no terminal event for {}", outcome.stage));
        let announced_failure = terminal
            .outcome
            .as_ref()
            .is_some_and(|o| matches!(o, crate::core::progress::Outcome::Failed { .. }));
        assert_eq!(
            announced_failure,
            outcome.status.is_failure(),
            "{} announced and recorded different verdicts",
            outcome.stage
        );
    }
}

/// An inactive bus must change nothing — the `None` caller's contract, proved
/// through the one shape that is observable from outside.
#[tokio::test]
async fn a_disabled_bus_stays_a_no_op() {
    let dir = tempfile::tempdir().expect("tempdir");
    let mut db = Database::open(&dir.path().join("tga.db")).expect("open db");
    let options = SweepOptions {
        output: Some(dir.path().join("out")),
        weeks: Some(1),
    };
    let bus = ProgressBus::disabled();

    let stats = run_full_sweep(&Config::default(), &mut db, &options, Some(&bus))
        .await
        .expect("sweep");

    assert!(bus.drain().is_empty(), "a disabled bus queued events");
    assert_eq!(bus.dropped(), 0);
    let stages: Vec<_> = stats.outcomes.iter().map(|o| o.stage).collect();
    assert_eq!(
        stages,
        EXPECTED_ORDER.to_vec(),
        "sequencing must not depend on whether anybody is watching"
    );
}

// ---------------------------------------------------------------------------
// clap wiring — `tga audit` parses its flags and dispatches
// ---------------------------------------------------------------------------

/// Standalone parser so the wiring can be asserted without building the whole
/// `tga` CLI, which the binary target owns.
#[derive(Parser, Debug)]
struct AuditOnly {
    #[command(flatten)]
    args: AuditArgs,
}

#[test]
fn audit_args_parse_every_flag() {
    let parsed = AuditOnly::try_parse_from([
        "tga-audit",
        "--org",
        "acme",
        "--title",
        "Acme DD",
        "--analyst",
        "J. Reviewer",
        "--client",
        "Acme Holdings",
        "--output",
        "/tmp/acme-dd",
        "--weeks",
        "26",
    ])
    .expect("flags must parse");

    assert_eq!(parsed.args.org.as_deref(), Some("acme"));
    assert_eq!(parsed.args.title.as_deref(), Some("Acme DD"));
    assert_eq!(parsed.args.analyst.as_deref(), Some("J. Reviewer"));
    assert_eq!(parsed.args.client.as_deref(), Some("Acme Holdings"));
    assert_eq!(
        parsed.args.output.as_deref(),
        Some(std::path::Path::new("/tmp/acme-dd"))
    );
    assert_eq!(parsed.args.weeks, Some(26));
}

#[test]
fn audit_runs_with_no_flags_at_all() {
    // DOC-67 §2: `tga audit` must be runnable as one shot with no operator
    // input, so no flag may be required.
    let parsed = AuditOnly::try_parse_from(["tga-audit"]).expect("bare invocation must parse");
    assert!(parsed.args.org.is_none());
    assert!(parsed.args.output.is_none());
}

#[test]
fn audit_takes_no_positional_arguments() {
    // A positional would be a place for an operator to be asked for something.
    // Which `ErrorKind` clap picks for an unexpected positional depends on the
    // command shape and the clap version, so assert the observable contract —
    // the parse fails and the message names the rejected argument — instead of
    // pinning the discriminant.
    let err = AuditOnly::try_parse_from(["tga-audit", "acme"])
        .expect_err("a positional argument must be rejected");
    let rendered = err.to_string();
    assert!(
        rendered.contains("acme"),
        "rejection must name the offending argument, got: {rendered}"
    );
}

#[test]
fn audit_args_expose_a_complete_clap_command() {
    // Guards the derive itself: every declared flag must reach the command.
    let cmd = AuditArgs::augment_args(clap::Command::new("audit"));
    let names: Vec<_> = cmd.get_arguments().map(|a| a.get_id().as_str()).collect();
    for expected in ["org", "title", "analyst", "client", "output", "weeks"] {
        assert!(
            names.contains(&expected),
            "missing --{expected} in {names:?}"
        );
    }

    let matches = cmd
        .try_get_matches_from(["audit", "--analyst", "me"])
        .expect("parse");
    let args = AuditArgs::from_arg_matches(&matches).expect("from_arg_matches");
    assert_eq!(args.analyst.as_deref(), Some("me"));
}

// ---------------------------------------------------------------------------
// Gaps & Caveats lines from the sweep's own record (#5239, #5244)
// ---------------------------------------------------------------------------

/// A config holding no credentials. The redaction path itself is proved end to
/// end against a real token in
/// `crate::report::dd_manifest_tests::a_token_straddling_the_excerpt_boundary_leaves_no_fragment`;
/// these tests are about the wording and ordering of the lines.
const NO_SECRETS: &[&str] = &[];

#[test]
fn sweep_gap_lines_name_each_failed_stage() {
    let mut stats = AuditSweepStats::default();
    stats.record(SweepStage::Collect, Instant::now(), Ok(()));
    stats.record(
        SweepStage::JiraSync,
        Instant::now(),
        Err(anyhow::anyhow!("no JIRA project configured")),
    );
    stats.record(
        SweepStage::Dora,
        Instant::now(),
        Err(anyhow::anyhow!("fact_deployments is empty")),
    );

    let lines = crate::audit::sweep_gap_lines(&stats, NO_SECRETS);

    assert_eq!(lines.len(), 2, "one line per failure, none for success");
    assert!(lines[0].contains("`jira sync`"), "{}", lines[0]);
    assert!(
        lines[0].contains("no JIRA project configured"),
        "{}",
        lines[0]
    );
    assert!(lines[1].contains("`dora`"), "{}", lines[1]);
    // DOC-67 §9: the line must refuse to read as a clean result.
    for line in &lines {
        assert!(line.contains("not assessed"), "{line}");
    }
    // Execution order, so two runs over the same failures read identically.
    assert_eq!(lines, crate::audit::sweep_gap_lines(&stats, NO_SECRETS));
}

/// #5321: a `collect` stage that fell back to stale local refs used to reach
/// the report as nothing at all.
///
/// The sweep hard-codes `--allow-stale` (DOC-67 §9), so an unreachable remote
/// is not an error: the pipeline walks whatever the local clone already had and
/// the stage records `Succeeded`. `sweep_gap_lines` only reads
/// [`AuditSweepStats::failures`], so a succeeded stage contributed no line and
/// the manifest carried no note — the reader could not tell "no stale refs" from
/// "the data may be months behind". Before the fix this test fails on the final
/// assertion: the gap lines name the failed `jira sync` stage and nothing else.
#[tokio::test]
async fn a_repo_that_fell_back_to_stale_local_refs_is_named_in_the_gap_lines() {
    let dir = tempfile::tempdir().expect("tempdir");
    let repo_path = dir.path().join("acme-service");
    // An `origin` whose scheme has no transport: the fetch fails without
    // touching the network, exactly as the reported run's SSH remote did
    // ("unsupported URL protocol"), so the test is offline and deterministic.
    init_repo_with_dead_origin(
        &repo_path,
        "sshx://git@example.invalid/acme/acme-service.git",
    );

    let mut config = Config::default();
    config
        .repositories
        .push(crate::core::config::RepositoryConfig {
            name: Some("acme-service".to_string()),
            path: repo_path,
            branch: None,
            since_date: None,
            until_date: None,
            org: None,
            head_only: false,
            fetch_timeout_secs: None,
        });

    let mut db = Database::open(&dir.path().join("tga.db")).expect("open db");
    let options = SweepOptions {
        output: Some(dir.path().join("out")),
        weeks: Some(1),
    };
    let stats = run_full_sweep(&config, &mut db, &options, None)
        .await
        .expect("sweep");

    // The defect's own shape: the stage reports `ok`. That is correct — the
    // sweep must not abort — which is exactly why the degradation needs its own
    // channel to the report.
    let collect = stats
        .outcomes
        .iter()
        .find(|o| o.stage == SweepStage::Collect)
        .expect("collect stage ran");
    assert_eq!(
        collect.status,
        StageStatus::Succeeded,
        "collect should still report ok under --allow-stale: {:?}",
        collect.status
    );

    let lines = crate::audit::sweep_gap_lines(&stats, NO_SECRETS);
    let stale = lines
        .iter()
        .find(|l| l.contains("acme-service"))
        .unwrap_or_else(|| {
            panic!("no Gaps & Caveats line names the repo that fell back to stale refs: {lines:#?}")
        });
    assert!(
        stale.contains("origin"),
        "the line must name the affected remote: {stale}"
    );
    assert!(
        stale.contains("behind the true remote state"),
        "the line must say the data may be out of date: {stale}"
    );
}

/// A git repository with one commit and an `origin` that cannot be fetched.
fn init_repo_with_dead_origin(path: &std::path::Path, remote_url: &str) {
    std::fs::create_dir_all(path).expect("mkdir");
    let repo = git2::Repository::init(path).expect("git init");
    repo.remote("origin", remote_url).expect("add origin");

    std::fs::write(path.join("README.md"), "acme").expect("write file");
    let mut index = repo.index().expect("index");
    index
        .add_path(std::path::Path::new("README.md"))
        .expect("index add");
    index.write().expect("index write");
    let tree = repo
        .find_tree(index.write_tree().expect("write_tree"))
        .expect("find_tree");
    let sig = git2::Signature::now("Test", "t@example.com").expect("signature");
    repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
        .expect("commit");
}

/// The stale-refs line travels the same redaction path a stage message does,
/// and it needs to: git2 quotes the remote URL back in the error, so an HTTPS
/// remote with an embedded token puts that token in the manifest and the
/// delivered report. Also pins the ordering — failed stages first, then the
/// repositories that were collected anyway.
#[test]
fn a_credential_in_a_fetch_error_never_reaches_the_gap_line() {
    let mut stats = AuditSweepStats::default();
    stats.record(
        SweepStage::Dora,
        Instant::now(),
        Err(anyhow::anyhow!("fact_deployments is empty")),
    );
    stats.record_stale_fetch(crate::audit::StaleFetch {
        repo: "acme-service".to_string(),
        remote: "origin".to_string(),
        error: "failed to connect to https://x-access-token:ghp_SECRETVALUE@github.com/acme/svc"
            .to_string(),
    });

    let lines = crate::audit::sweep_gap_lines(&stats, &["ghp_SECRETVALUE"]);

    assert_eq!(lines.len(), 2, "{lines:#?}");
    assert!(lines[0].contains("`dora`"), "{}", lines[0]);
    assert!(lines[1].contains("acme-service"), "{}", lines[1]);
    assert!(
        !lines[1].contains("ghp_SECRETVALUE"),
        "the token survived into the report: {}",
        lines[1]
    );
}

#[test]
fn sweep_gap_lines_are_empty_for_a_clean_run() {
    let mut stats = AuditSweepStats::default();
    for stage in EXPECTED_ORDER {
        stats.record(stage, Instant::now(), Ok(()));
    }
    assert!(crate::audit::sweep_gap_lines(&stats, NO_SECRETS).is_empty());
}

#[test]
fn long_stage_reasons_are_truncated() {
    let mut stats = AuditSweepStats::default();
    stats.record(
        SweepStage::Collect,
        Instant::now(),
        Err(anyhow::anyhow!("x".repeat(4000))),
    );

    let line = crate::audit::sweep_gap_lines(&stats, NO_SECRETS).remove(0);

    assert!(line.contains('…'), "a long reason is excerpted: {line}");
    assert!(
        line.chars().count() < 400,
        "one verbose error must not dominate the Gaps section ({} chars)",
        line.chars().count()
    );
}

#[test]
fn data_handling_note_is_a_pending_claim() {
    let note = crate::audit::DATA_HANDLING_NOTE;
    // DOC-67 §10: pending, never asserted — and #5218 is where the real one comes from.
    assert!(note.contains("pending"), "{note}");
    assert!(note.contains("#5218"), "{note}");
    // §10's exact scope claim; the broader "no code" claim is wrong and must
    // not appear, because free-text columns can carry pasted snippets.
    assert!(note.contains("no file content, diffs, patches, hunks, or blobs"));
    assert!(!note.contains("no code"), "{note}");
}

// ---------------------------------------------------------------------------
// Invoking trusty-review as a subprocess (#5238)
// ---------------------------------------------------------------------------

#[test]
fn artifact_paths_are_parsed_from_stdout() {
    // trusty-review prints one written path per line on stdout; blank lines and
    // trailing whitespace must not become phantom artifacts.
    let stdout = "  /out/acme.md\n\n/out/acme.json\n";
    let paths = crate::audit::artifact_paths(stdout);
    assert_eq!(
        paths,
        vec![
            std::path::PathBuf::from("/out/acme.md"),
            std::path::PathBuf::from("/out/acme.json")
        ]
    );
    assert!(crate::audit::artifact_paths("").is_empty());
}

#[tokio::test]
async fn missing_binary_is_a_named_actionable_error() {
    // A renderer that is not installed must produce a message an operator can
    // act on — never a panic, and never a silent skip that leaves the run
    // looking successful with no report.
    let dir = tempfile::tempdir().expect("tempdir");
    let manifest = dir.path().join("manifest.toml");
    std::fs::write(&manifest, "[report]\ntitle = \"T\"\n").expect("write");

    // The binary is passed in, never installed through the environment: this is
    // the same path `run_review_report` takes once resolution has happened, and
    // it stays sound under the parallel harness (#5308 review).
    let missing = dir.path().join("definitely-not-installed");
    let err =
        super::review::run_review_report_with(missing.display().to_string(), &manifest, dir.path())
            .await
            .expect_err("a missing binary must be an error");

    let msg = err.to_string();
    assert!(
        matches!(err, crate::audit::ReviewRunError::BinaryNotFound { .. }),
        "{msg}"
    );
    assert!(
        msg.contains("TRUSTY_REVIEW_BIN"),
        "names the override: {msg}"
    );
    assert!(msg.contains("cargo install"), "names the fix: {msg}");
    assert!(
        msg.contains(&manifest.display().to_string()),
        "the written manifest is still usable and must be named: {msg}"
    );
}

/// The rule is exercised as a pure function over the override value, which is
/// what `resolve_review_binary` reads `TRUSTY_REVIEW_BIN` into. Mutating the
/// process environment to test it would be unsound under the parallel test
/// harness, and no `unsafe` block can make it sound (#5308 review).
#[test]
fn binary_resolution_prefers_the_env_override() {
    use super::review::binary_from_override;

    assert_eq!(
        binary_from_override(Some("/opt/bin/trusty-review")),
        "/opt/bin/trusty-review"
    );
    assert_eq!(
        binary_from_override(Some("")),
        crate::audit::DEFAULT_REVIEW_BIN,
        "an empty override falls back to the PATH lookup"
    );
    assert_eq!(binary_from_override(None), crate::audit::DEFAULT_REVIEW_BIN);
    // The public entry point returns one of the two, whatever this machine's
    // environment happens to hold — read only, never written.
    let resolved = crate::audit::resolve_review_binary();
    assert!(!resolved.is_empty(), "{resolved}");
}

// ─── #5454: inference is required ────────────────────────────────────────────

/// #5454 regression. Before this change `invoke` built `report --manifest <m>
/// --analyze --out <dir>` and never passed `--synthesize`, so `model.synthesis`
/// was `None` on every audit that had ever run and the whole report was
/// deterministic. Pins the flag into the argument vector, and pins the rest of
/// the vector alongside it so a future edit cannot drop `--analyze` while
/// "fixing" this one.
#[test]
fn invocation_requests_inference() {
    use std::path::Path;

    let args = super::review::report_args(Path::new("/o/manifest.toml"), Path::new("/o"));
    let rendered: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();

    assert_eq!(
        rendered,
        vec![
            "report",
            "--manifest",
            "/o/manifest.toml",
            "--analyze",
            "--synthesize",
            "--out",
            "/o",
        ],
        "the audit's renderer invocation must request inference"
    );
}

/// #5454. The credential is the one prerequisite knowable before the sweep
/// starts, and DOC-67 §2 gives the run a single non-interactive shot — so a
/// missing key must be named up front, with the variable and the way to set it,
/// rather than surfacing minutes later at the render step.
#[test]
fn absent_credential_is_a_named_actionable_error() {
    use super::review::credential_is_present;

    assert!(!credential_is_present(None), "unset is absent");
    assert!(!credential_is_present(Some("")), "empty is absent");
    assert!(
        !credential_is_present(Some("   \n")),
        "whitespace-only is absent"
    );

    let msg = crate::audit::MissingInferenceCredential.to_string();
    assert!(
        msg.contains(crate::audit::ENV_INFERENCE_CREDENTIAL),
        "names the variable: {msg}"
    );
    assert!(
        msg.contains("export OPENROUTER_API_KEY="),
        "says how to set it: {msg}"
    );
}

/// #5454. The preflight must not stand between an operator who HAS a key and
/// their run, and it must never copy the key anywhere — the message it can
/// produce is a constant with no interpolation site for one.
#[test]
fn present_credential_passes_the_precheck() {
    use super::review::credential_is_present;

    let secret = "sk-or-v1-DEADBEEFdeadbeef";
    assert!(credential_is_present(Some(secret)));

    let msg = crate::audit::MissingInferenceCredential.to_string();
    assert!(!msg.contains(secret), "no key material may appear: {msg}");
    assert!(!msg.contains("sk-or"), "no key-shaped text: {msg}");
}

// ─── #5454 review: exit 0 is not evidence of a synthesis pass ────────────────

/// A `ReviewRun` shaped like a clean render: the child exited 0 and printed both
/// halves of the report pair.
///
/// Writes `report_json` to a real file, because the check reads the artifact the
/// renderer wrote rather than anything the child said about it.
fn successful_run_over(dir: &std::path::Path, report_json: &str) -> crate::audit::ReviewRun {
    let md = dir.join("2026-08-11-acme.md");
    let json = dir.join("2026-08-11-acme.json");
    std::fs::write(&md, "# Acme\n").expect("write md");
    std::fs::write(&json, report_json).expect("write json");
    crate::audit::ReviewRun {
        success: true,
        code: Some(0),
        stdout: format!("{}\n{}\n", md.display(), json.display()),
        stderr: String::new(),
        artifacts: vec![md, json],
    }
}

/// The exact JSON a pre-0.15 `trusty-review` writes when its provider fails
/// mid-render: `SynthesisStatus::Unavailable` and every prose field empty.
const DEGRADED_0_14_REPORT: &str = r#"{
  "title": "Acme — Technical Due Diligence",
  "synthesis": {
    "status": { "state": "unavailable", "reason": "provider build failed: 401 Unauthorized" },
    "top_risks": [],
    "findings": [],
    "notes": []
  }
}"#;

/// #5454 review, THE arm this guard exists for. A new `tga` beside a pre-0.15
/// `trusty-review` is an ordinary pairing — the two are resolved through PATH,
/// not a Cargo edge — and that renderer takes `--synthesize`, falls back to a
/// deterministic report on any provider failure, writes it, and exits 0.
/// `ReviewRun::success` is `output.status.success()` and nothing more, so the
/// `if !run.success` check never fired and `tga audit` reported a clean pass over
/// the exact narrative-free report #5454 exists to abolish.
///
/// Pins the failure AND its remedy: a message that says only "no narrative"
/// leaves the operator with a symptom and no action.
#[test]
fn exit_zero_over_a_narrative_free_report_is_a_failure() {
    let dir = tempfile::tempdir().expect("tempdir");
    let run = successful_run_over(dir.path(), DEGRADED_0_14_REPORT);
    assert!(run.success, "the child exited 0 — that is the whole point");

    let err = crate::audit::require_rendered_report_carries_synthesis(&run)
        .expect_err("a report with no written analysis must not pass as a successful audit");
    let msg = err.to_string();
    assert!(
        msg.contains("trusty-review") && msg.contains("predates"),
        "the message must name the stale renderer as the cause: {msg}"
    );
    assert!(
        msg.contains("tctl install trusty-review"),
        "the message must name the upgrade that fixes it: {msg}"
    );

    // The rule itself, over both narrative-free shapes: 0.14's degraded object,
    // and a report carrying no `synthesis` key at all.
    use crate::audit::review::json_carries_synthesis;
    assert_eq!(json_carries_synthesis(DEGRADED_0_14_REPORT), Some(false));
    assert_eq!(json_carries_synthesis(r#"{"title": "Acme"}"#), Some(false));
}

/// The guard must not stand between an operator and a report that DID get its
/// narrative written — including the one arm 0.15 still allows through, where the
/// numeric guardrail rejected the executive summary on its own and the
/// deterministic composition (#5374) fills §2 while the top-risk rows survive.
#[test]
fn a_synthesized_report_passes_the_check() {
    use crate::audit::review::json_carries_synthesis;

    let dir = tempfile::tempdir().expect("tempdir");
    let full = r#"{
      "title": "Acme",
      "synthesis": {
        "executive_summary": "Two of three applications carry RED findings.",
        "top_risks": [{"description": "No tests", "severity": "RED", "cost": "high", "apps": "web"}],
        "findings": [],
        "notes": []
      }
    }"#;
    crate::audit::require_rendered_report_carries_synthesis(&successful_run_over(dir.path(), full))
        .expect("a synthesized report passes");

    // Guardrail rejected the summary; rows survived. Still a synthesized report.
    assert_eq!(
        json_carries_synthesis(
            r#"{"synthesis": {"top_risks": [{"description": "x"}], "findings": [], "notes": ["synthesis: rejected (unverified figure)"]}}"#
        ),
        Some(true)
    );
    // Only finding prose survived.
    assert_eq!(
        json_carries_synthesis(r#"{"synthesis": {"top_risks": [], "findings": [{"title": "x"}]}}"#),
        Some(true)
    );
    // A blank summary is not prose.
    assert_eq!(
        json_carries_synthesis(r#"{"synthesis": {"executive_summary": "   "}}"#),
        Some(false)
    );
}

/// A check that cannot be performed must fail, not pass — passing on "I could not
/// look" reopens the hole the guard closes. Covers both ways the artifact can go
/// missing: no `.json` path printed, and a path that is not JSON.
#[test]
fn an_uncheckable_report_fails_rather_than_passes() {
    use crate::audit::review::json_carries_synthesis;

    let no_json = crate::audit::ReviewRun {
        success: true,
        code: Some(0),
        stdout: "/o/report.md\n".to_string(),
        stderr: String::new(),
        artifacts: vec![std::path::PathBuf::from("/o/report.md")],
    };
    let err = crate::audit::require_rendered_report_carries_synthesis(&no_json)
        .expect_err("no .json artifact means nothing can be asserted about the report");
    assert!(err.to_string().contains("could not be checked"), "{err}");

    let dir = tempfile::tempdir().expect("tempdir");
    let err = crate::audit::require_rendered_report_carries_synthesis(&successful_run_over(
        dir.path(),
        "not json at all",
    ))
    .expect_err("an unparseable report cannot be claimed to carry a narrative");
    assert!(err.to_string().contains("could not be checked"), "{err}");

    assert_eq!(json_carries_synthesis("not json at all"), None);
}

/// #5454 review. The version skew is knowable before stage 1, and DOC-67 §2 gives
/// the sweep one non-interactive shot — so an operator learning about it only
/// after eight stages have run learns it at the worst moment. Pins the floor, the
/// parse, and the deliberate proceed-on-unreadable behaviour that leaves
/// `require_rendered_report_carries_synthesis` as the thing that actually closes
/// the hole.
#[test]
fn stale_renderer_is_rejected_before_the_sweep() {
    use crate::audit::review::{parse_review_version, version_verdict};
    use crate::audit::MIN_REVIEW_VERSION;

    assert_eq!(MIN_REVIEW_VERSION, (0, 15, 0));

    // The version actually on PATH when this defect was found. The message names
    // the version found, the floor, and the upgrade that fixes it.
    let err = version_verdict("trusty-review", "trusty-review 0.14.1\n")
        .expect_err("a pre-0.15 renderer must not clear the preflight");
    let msg = err.to_string();
    for needle in ["0.14.1", "0.15.0", "tctl install trusty-review", "exits 0"] {
        assert!(msg.contains(needle), "missing {needle:?}: {msg}");
    }

    for ok in ["trusty-review 0.15.0", "trusty-review 0.15.1", "tr v1.0.0"] {
        version_verdict("trusty-review", ok).unwrap_or_else(|e| panic!("{ok} must pass: {e}"));
    }
    // Pre-release and build suffixes read as their release core.
    assert_eq!(
        parse_review_version("trusty-review 0.15.0-rc.1+build.7"),
        Some((0, 15, 0))
    );

    // Unreadable → the caller proceeds; the delivered-artifact check is what
    // closes the hole, not this.
    for unreadable in ["", "\n\n", "trusty-review", "trusty-review unknown"] {
        assert_eq!(parse_review_version(unreadable), None, "{unreadable:?}");
        version_verdict("trusty-review", unreadable)
            .unwrap_or_else(|e| panic!("{unreadable:?} must proceed, not fail: {e}"));
    }
}