codelore 0.27.3

CodeLore — Behavioral Code Analyzer CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
//! `codelore check` — repository quality-gate evaluation.
//!
//! Loads the configured thresholds, runs the gate-relevant analyses against the
//! repository HEAD, evaluates every configured gate, records each verdict in the
//! gate-run ledger, optionally emits a SARIF document, and exits 0 (pass) or 1
//! (fail). Also serves `--history` (print the ledger without evaluating) and
//! `--ratchet` (compare against the stored regression snapshot).

use anyhow::{Context, Result};

use crate::args::{self, CheckFormat};
use crate::{
    CORPUS_PERCENTILE_SKIP_REASON, new_code_skip_reason, notice_corpus_lens_absent,
    vacuous_pass_notice, write_github_output,
};

/// Quality-gate check. Loads thresholds, runs the hotspots analysis
/// against the repo, evaluates each row against the gates, and
/// exits 0 (pass) or 1 (fail). Writes `result=pass|fail` to
/// `$GITHUB_OUTPUT` for direct GitHub Actions step-output
/// consumption.
#[allow(clippy::too_many_lines)]
pub(crate) fn run_check_cmd(args: &args::CheckArgs) -> Result<()> {
    use codelore_lib::cli_api::Options;
    use codelore_lib::cli_api::cache::default_cache_root;
    use codelore_lib::cli_api::facts::FactsDb;
    use codelore_lib::cli_api::quality_gates::Thresholds;
    use codelore_lib::cli_api::quality_gates::ledger::{
        GateRunRecord, append_gate_runs, format_history, now_utc_ts, read_gate_runs,
    };
    use codelore_lib::cli_api::quality_gates::ratchet::{
        RatchetMetrics, RatchetOutcome, evaluate_ratchet, format_ratchet_outcome, read_snapshot,
        snapshot_from_metrics, write_snapshot,
    };
    use codelore_lib::cli_api::repo::{GixRepo, Repo as _};

    let cache_root = args.cache_dir.clone().unwrap_or_else(default_cache_root);

    // --history: print ledger without running any gate evaluations. Write the
    // (potentially many-row) table through a propagating `write!` rather than
    // `print!` so a reader closing the pipe early (`codelore check --history |
    // head`) routes the BrokenPipe up to `main`'s quiet-exit arm, not a panic.
    if args.history {
        use std::io::Write as _;
        let records = read_gate_runs(&cache_root, &args.repo).context("read gate-run ledger")?;
        let mut out = std::io::stdout().lock();
        write!(out, "{}", format_history(&records, 20)).context("write gate-run history")?;
        return Ok(());
    }

    let thresholds = if let Some(path) = &args.thresholds_file {
        Thresholds::from_path(path).context("load thresholds file")?
    } else {
        Thresholds::discover(&args.repo).context("discover thresholds file")?
    };

    if thresholds.is_empty() && !args.ratchet {
        if !args.quiet {
            eprintln!("{}", vacuous_pass_notice("check"));
        }
        write_github_output("result", "pass");
        // Every other exit path writes both keys; a vacuous pass had been
        // writing only `result`, so a workflow reading `outputs.violations`
        // got an empty string instead of a count.
        write_github_output("violations", "0");
        // A vacuous pass under `--format sarif` must still emit a valid
        // zero-result SARIF document to stdout — the documented upload-sarif
        // pipeline (docs/advanced-usage.md §11.8) breaks if a run prints
        // nothing. Reuse the check emitter with an empty violation set.
        if matches!(args.format, CheckFormat::Sarif) {
            let repo = GixRepo::open(&args.repo).context("open repo")?;
            let head_sha = repo.head_sha().context("get HEAD sha")?;
            emit_check_sarif(
                &args.repo,
                &head_sha,
                &[],
                &std::collections::HashMap::new(),
            )?;
        }
        return Ok(());
    }

    // Mirrors `quality_gates::resolve_defect_calibration`, but reuses the
    // `thresholds` value already loaded above instead of re-discovering
    // (and re-parsing) the thresholds file.
    let resolved_defect_calibration = args.defect_calibration.clone().or_else(|| {
        thresholds.calibration.defect_artifact.clone().map(|p| {
            if p.is_absolute() {
                p
            } else {
                args.repo.join(p)
            }
        })
    });

    let opts = Options {
        repo_path: args.repo.clone(),
        calibration: args.calibration.clone(),
        defect_calibration: resolved_defect_calibration,
        allow_foreign_calibration: args.allow_foreign_calibration,
        temp_dir: args.temp_dir.clone(),
        ..Options::default()
    };
    opts.validate().context("validate options")?;
    let repo = GixRepo::open(&args.repo).context("open repo")?;
    let head_sha = repo.head_sha().context("get HEAD sha")?;
    let db =
        FactsDb::open_or_ingest_with_cache_root(&opts, &repo, &cache_root).context("ingest")?;
    // Witness the ingest before any gate runs: a real HEAD over an empty commit
    // store is the truncated-checkout signature (a shallow merge-tip fetch under
    // the default merge filter ingests zero history), on which every gate would
    // pass over no data. Turn that silent green into a hard, distinct error.
    db.ensure_ingest_witnessed(&head_sha)?;
    // Defence in depth: a shallow checkout that DID ingest a commit or two still
    // carries only partial history, which quietly weakens every behavioral gate.
    // Warn loudly and name the cause; SARIF mode keeps stdout a clean document.
    // The same signal discriminates the `new_code` skip disclosure below (a
    // truncated checkout reads identically to a young repository at that query).
    let shallow_checkout = repo.is_shallow();
    if shallow_checkout {
        let warning = "⚠ codelore check: shallow checkout detected (.git/shallow present) — \
             history is truncated by fetch-depth, so the behavioral gates (hotspots, \
             effort-exposure, new-code) evaluate only partial history. Re-run against full \
             history (fetch-depth: 0) for an authoritative verdict.";
        if matches!(args.format, CheckFormat::Sarif) {
            eprintln!("{warning}");
        } else {
            println!("{warning}");
        }
    }
    let ts = now_utc_ts();

    // Open the external-findings sidecar without creating it, only when it
    // holds findings. `None` when absent OR present-but-empty — both mean "no
    // external findings to evaluate", and the gate is skipped gracefully inside
    // evaluate_all_gates.
    let external_store = if thresholds.gates.max_findings_in_hot_files.is_some() {
        codelore_lib::cli_api::external::ExternalStore::open_nonempty(&cache_root, &args.repo)
            .context("open external store")?
    } else {
        None
    };

    let (mut violations, mut ledger_records, hotspot_count, code_health) = evaluate_all_gates(
        &thresholds,
        &db,
        &repo,
        &opts,
        &head_sha,
        &ts,
        external_store.as_ref(),
    )
    .context("evaluate gates")?;

    // ── Per-gate notices (stderr) ────────────────────────────────────────────
    // Rendered from the ledger records the evaluator already produced, so the
    // compute layer prints nothing itself. Emitted before the ratchet/report
    // branches so both paths surface them; stderr keeps stdout a clean SARIF
    // document in --format sarif; suppressed under --quiet.
    if !args.quiet {
        emit_gate_notices(&ledger_records, shallow_checkout);
    }
    // One-per-run hint when the corpus lens is inactive — the check path always
    // computes code-health rows, which carry no corpus_percentile without an
    // artifact. Suppressed under --quiet (handled inside).
    notice_corpus_lens_absent(&opts, args.quiet);

    // ── Ratchet ───────────────────────────────────────────────────────────────
    if args.ratchet {
        // Build ratchet metrics from already-computed gate outputs.
        //
        // Every metric is tracked only when its gate is configured — the
        // README states this, and it is what makes the ratchet a tightening
        // of bounds the user chose rather than a new bound they did not.
        // `red_effort_pct` and `dependency_cycles` get it for free by reading
        // ledger records, which exist only if their gate ran. Code health does
        // not: `run_code_health` runs unconditionally (other gates consume its
        // rows), so reading the worst score straight off the scan recorded a
        // floor for a gate that was never configured — and a later benign
        // refactor that nudged that score down by recomputation noise failed
        // the run against a bound the user never set.
        let worst_health = if thresholds.gates.code_health_min.is_some() {
            code_health
                .iter()
                .map(|r| r.score)
                .fold(f64::INFINITY, f64::min)
        } else {
            f64::INFINITY
        };
        // red_effort_pct: read from the effort-exposure ledger record if present.
        let red_effort_pct = ledger_records
            .iter()
            .find(|r| r.gate == "max_red_effort_pct")
            .map(|r| r.value);
        // dependency_cycles: read from the arch ledger record if present.
        let dep_cycles = ledger_records
            .iter()
            .find(|r| r.gate == "max_dependency_cycles")
            .map(|r| r.value);
        let metrics = RatchetMetrics {
            code_health_min_observed: if worst_health.is_infinite() {
                None
            } else {
                Some(worst_health)
            },
            red_effort_pct_observed: red_effort_pct,
            dependency_cycles_observed: dep_cycles,
        };

        match read_snapshot(&args.repo).context("read ratchet snapshot")? {
            None => {
                // First run: initialize.
                let snap = snapshot_from_metrics(&metrics);
                write_snapshot(&args.repo, &snap).context("write ratchet snapshot")?;
                let tracked: Vec<&str> = [
                    metrics
                        .code_health_min_observed
                        .map(|_| "code_health_min_observed"),
                    metrics
                        .red_effort_pct_observed
                        .map(|_| "red_effort_pct_observed"),
                    metrics
                        .dependency_cycles_observed
                        .map(|_| "dependency_cycles_observed"),
                ]
                .into_iter()
                .flatten()
                .collect();
                emit_ratchet_message(
                    args,
                    &format!(
                        "✅ ratchet initialized — tracking {} metric(s): {}. \
                         Configure max_red_effort_pct / max_dependency_cycles gates to ratchet \
                         effort and cycles. Commit `.codelore-ratchet.toml` to enable regression detection.\n",
                        tracked.len(),
                        if tracked.is_empty() {
                            "(none)".to_owned()
                        } else {
                            tracked.join(", ")
                        },
                    ),
                );
                ledger_records.push(GateRunRecord {
                    ts: ts.clone(),
                    head_sha: head_sha.clone(),
                    gate: "ratchet".into(),
                    threshold: 0.0,
                    value: 0.0,
                    verdict: "initialized".into(),
                    mode: "ratchet".into(),
                });
                append_gate_runs(&cache_root, &args.repo, &ledger_records);
                // `--format sarif` must still yield a valid document on the
                // ratchet exit paths, exactly like the non-ratchet path — the
                // gates already ran, so emit their violations before returning.
                emit_check_sarif_when_requested(args, &db, &opts, &head_sha, &violations)?;
                return Ok(());
            }
            Some(snap) => {
                let outcome = evaluate_ratchet(&snap, &metrics);
                emit_ratchet_message(args, &format_ratchet_outcome(&outcome));
                let (verdict, ratchet_failed) = match &outcome {
                    RatchetOutcome::Improved { .. } => ("improved", false),
                    RatchetOutcome::Regressed { .. } => ("regressed", true),
                };
                ledger_records.push(GateRunRecord {
                    ts: ts.clone(),
                    head_sha: head_sha.clone(),
                    gate: "ratchet".into(),
                    threshold: 0.0,
                    value: 0.0,
                    verdict: verdict.into(),
                    mode: "ratchet".into(),
                });
                append_gate_runs(&cache_root, &args.repo, &ledger_records);
                // Emit the standard check SARIF on both ratchet outcomes before
                // returning/bailing, so `--format sarif` always yields a valid
                // document. Exit code is unchanged: a regression still bails.
                emit_check_sarif_when_requested(args, &db, &opts, &head_sha, &violations)?;
                if ratchet_failed {
                    anyhow::bail!("ratchet: regression detected — see above");
                }
                // Tighten: rewrite snapshot with improved values.
                let tightened = snapshot_from_metrics(&metrics);
                write_snapshot(&args.repo, &tightened).context("tighten ratchet snapshot")?;
                return Ok(());
            }
        }
    }

    // ── Ledger write (IO errors warn, never alter exit code) ─────────────────
    append_gate_runs(&cache_root, &args.repo, &ledger_records);

    // ── fail_on_skipped policy ───────────────────────────────────────────────
    // A gate recorded "skipped" becomes a violation so the run fails rather than
    // greening on a gate that never evaluated. The ledger write above keeps the
    // honest "skipped" verdict; only the exit-facing set gains rows. Placed
    // after the ratchet block (whose exit is regression-driven) so the policy
    // scopes to the normal check exit path.
    violations.extend(crate::skipped_gate_violations(
        &ledger_records,
        thresholds.gates.fail_on_skipped,
    ));

    // ── SARIF emission (when --format sarif) ─────────────────────────────────
    emit_check_sarif_when_requested(args, &db, &opts, &head_sha, &violations)?;

    // ── Report ────────────────────────────────────────────────────────────────
    let degraded_count = ledger_records
        .iter()
        .filter(|r| r.verdict == "degraded")
        .count();

    if violations.is_empty() {
        if degraded_count > 0 {
            let warning = format!(
                "⚠ codelore check: WARNING — {degraded_count} gate(s) degraded (non-degraded gates pass)"
            );
            // SARIF mode keeps stdout a clean SARIF document, so the warning
            // goes to stderr; text mode prints it to stdout with the report.
            if matches!(args.format, CheckFormat::Sarif) {
                eprintln!("{warning}");
            } else {
                println!("{warning}");
            }
        } else if matches!(args.format, CheckFormat::Text) {
            println!("✅ codelore check: PASS ({hotspot_count} files evaluated)");
        }
        write_github_output("result", "pass");
        write_github_output("violations", "0");
        Ok(())
    } else {
        eprintln!(
            "❌ codelore check: FAIL — {} violation(s)",
            violations.len()
        );
        if !args.quiet && matches!(args.format, CheckFormat::Text) {
            for v in &violations {
                eprintln!(
                    "  - {gate}: {path} — actual {actual} vs threshold {threshold}",
                    gate = v.gate,
                    path = v.path,
                    actual = v.actual,
                    threshold = v.threshold,
                );
            }
        }
        write_github_output("result", "fail");
        write_github_output("violations", &violations.len().to_string());
        // Inside GitHub Actions, emit each violation as an inline `::error`
        // annotation so the failing gate shows up against the file in the
        // PR's Files-changed view — not just as a red check.
        if std::env::var("GITHUB_ACTIONS").as_deref() == Ok("true")
            && matches!(args.format, CheckFormat::Text)
        {
            let mut stdout = std::io::stdout();
            codelore_lib::cli_api::output::gha::write_gate_violations_gha(&violations, &mut stdout)
                .context("emit gate annotations")?;
        }
        // Plain anyhow::bail carries no CodeLoreError, so main()'s chain-walk
        // falls through to the default exit code 1. Gate failure exits 1 by
        // design; typed CodeLoreError variants are reserved for repo/output
        // failures (exit codes 3, 4, 5).
        anyhow::bail!("{} gate violation(s) — see above", violations.len());
    }
}

/// Emit the per-gate skip / degraded notices to stderr, derived from the
/// ledger records the evaluator produced. Keeping this out of the compute layer
/// means `evaluate_all_gates` stays print-free and the notice wording lives
/// beside the rest of `run_check_cmd`'s reporting.
fn emit_gate_notices(
    ledger_records: &[codelore_lib::cli_api::quality_gates::ledger::GateRunRecord],
    shallow_checkout: bool,
) {
    for r in ledger_records {
        match (r.gate.as_str(), r.verdict.as_str()) {
            ("max_findings_in_hot_files", "skipped") => eprintln!(
                "  ⚠ max_findings_in_hot_files: skipped — run `codelore ingest-sarif` first"
            ),
            ("corpus_percentile_max", "skipped") => {
                eprintln!("  ⚠ corpus_percentile_max: skipped — {CORPUS_PERCENTILE_SKIP_REASON}");
            }
            ("hotspot_anchored_max", "skipped") => eprintln!(
                "  ⚠ hotspot_anchored_max: skipped — no anchored hotspot data (no calibration artifact active, or no analyzed file's language is covered by the corpus)"
            ),
            ("code_health_min", "degraded") => eprintln!(
                "  ⚠ code_health_min: degraded — health scan returned no rows on a non-empty repo"
            ),
            ("new_code", "skipped") => eprintln!(
                "  ⚠ new_code: skipped — {}",
                new_code_skip_reason(r.threshold, shallow_checkout)
            ),
            _ => {}
        }
    }
}

/// Gate result bundle: violations + ledger records from one gate group.
type GateGroupResult = (
    Vec<codelore_lib::cli_api::quality_gates::GateViolation>,
    Vec<codelore_lib::cli_api::quality_gates::ledger::GateRunRecord>,
);

/// Build one ledger record for a simple scalar gate.
fn make_rec(
    gate: &str,
    threshold: f64,
    value: f64,
    failed: bool,
    ts: &str,
    head_sha: &str,
) -> codelore_lib::cli_api::quality_gates::ledger::GateRunRecord {
    use codelore_lib::cli_api::quality_gates::ledger::GateRunRecord;
    GateRunRecord {
        ts: ts.to_owned(),
        head_sha: head_sha.to_owned(),
        gate: gate.to_owned(),
        threshold,
        value,
        verdict: if failed { "failed" } else { "passed" }.to_owned(),
        mode: "check".to_owned(),
    }
}

/// Evaluate hotspot-based gates (`cognitive_max`, `hotspot_score_max`).
/// Returns the gate result bundle and the hotspot rows (reused by
/// `run_finding_hotspot_overlap_with` to avoid a second hotspot query).
fn eval_hotspot_gates(
    thresholds: &codelore_lib::cli_api::quality_gates::Thresholds,
    db: &codelore_lib::cli_api::facts::FactsDb,
    opts: &codelore_lib::cli_api::Options,
    ts: &str,
    head_sha: &str,
) -> Result<(
    GateGroupResult,
    Vec<codelore_lib::cli_api::analyses::hotspots::HotspotRow>,
)> {
    use codelore_lib::cli_api::analyses::hotspots::run_hotspots_anchored;
    use codelore_lib::cli_api::quality_gates::evaluate_full_tree;
    // The gate must see the whole population — a `--rows` display cap must
    // never change which files the gate evaluates. `with_no_row_limit` is a
    // no-op when no cap is set, so the gate outcome is unaffected today and
    // stays correct if a row cap is ever threaded into this path.
    //
    // `run_hotspots_anchored` also fills `hotspot_score_anchored` so the
    // `hotspot_anchored_max` gate (evaluated in `evaluate_all_gates`) reads it
    // off these same rows; the always-on `cognitive_max` / `hotspot_score_max`
    // gates below are unaffected by the additive field.
    let hotspots = run_hotspots_anchored(db, &opts.with_no_row_limit()).context("run hotspots")?;
    let hs_violations = evaluate_full_tree(thresholds, &hotspots);
    let g = &thresholds.gates;
    let mut recs = Vec::new();
    if let Some(max) = g.cognitive_max {
        let failed = hs_violations.iter().any(|v| v.gate == "cognitive_max");
        let value = hotspots
            .iter()
            .map(|r| r.cognitive)
            .fold(f64::NAN, f64::max);
        recs.push(make_rec(
            "cognitive_max",
            max,
            if value.is_nan() { 0.0 } else { value },
            failed,
            ts,
            head_sha,
        ));
    }
    if let Some(max) = g.hotspot_score_max {
        let failed = hs_violations.iter().any(|v| v.gate == "hotspot_score_max");
        let value = hotspots
            .iter()
            .map(|r| r.hotspot_score)
            .fold(f64::NAN, f64::max);
        recs.push(make_rec(
            "hotspot_score_max",
            max,
            if value.is_nan() { 0.0 } else { value },
            failed,
            ts,
            head_sha,
        ));
    }
    Ok(((hs_violations, recs), hotspots))
}

/// Evaluate `code_health_min` gate with degraded-detection.
/// Returns the gate result bundle + the raw `CodeHealthRow` vec (reused by ratchet).
fn eval_code_health_gate(
    thresholds: &codelore_lib::cli_api::quality_gates::Thresholds,
    db: &codelore_lib::cli_api::facts::FactsDb,
    repo: &impl codelore_lib::cli_api::repo::Repo,
    opts: &codelore_lib::cli_api::Options,
    ts: &str,
    head_sha: &str,
) -> Result<(
    GateGroupResult,
    Vec<codelore_lib::cli_api::analyses::code_health::CodeHealthRow>,
)> {
    use codelore_lib::cli_api::quality_gates::ledger::GateRunRecord;
    use codelore_lib::cli_api::quality_gates::{GateViolation, evaluate_code_health_gate};
    // Gate over the whole population — a `--rows` display cap must not change
    // which files the gate evaluates (no-op today; correct if a cap is ever
    // threaded in).
    let code_health = codelore_lib::cli_api::analyses::code_health::run_code_health(
        db,
        &opts.with_no_row_limit(),
    )
    .context("run code-health")?;
    let g = &thresholds.gates;
    let Some(min) = g.code_health_min else {
        return Ok(((Vec::new(), Vec::new()), code_health));
    };
    let ch_violations = evaluate_code_health_gate(thresholds, &code_health);
    // Degraded: the health scan returned nothing, yet the repository actually
    // carries analyzable source. The witness reads the HEAD tree directly rather
    // than counting `complexity_metrics`, which derives from the same
    // changes⋈commits join as the (empty) health set and so empties in lockstep
    // — it cannot witness an ingest that went blind. A source-less tree (docs or
    // config only) legitimately yields no rows and stays a vacuous pass. The `&&`
    // short-circuit keeps the tree walk off every healthy run.
    let degraded = code_health.is_empty()
        && codelore_lib::cli_api::quality_gates::head_has_scorable_source(repo, opts);
    let worst = code_health
        .iter()
        .map(|r| r.score)
        .fold(f64::INFINITY, f64::min);
    let verdict = if degraded {
        "degraded"
    } else if ch_violations.is_empty() {
        "passed"
    } else {
        "failed"
    };
    let rec = GateRunRecord {
        ts: ts.to_owned(),
        head_sha: head_sha.to_owned(),
        gate: "code_health_min".into(),
        threshold: min,
        value: if worst.is_infinite() { 0.0 } else { worst },
        verdict: verdict.to_owned(),
        mode: "check".into(),
    };
    let mut violations = Vec::new();
    if degraded && g.fail_on_degraded {
        violations.push(GateViolation {
            gate: "code_health_min".into(),
            path: "(degraded)".into(),
            actual: "no-data".into(),
            threshold: format!("{min:.1}"),
        });
    } else {
        violations.extend(ch_violations);
    }
    Ok(((violations, vec![rec]), code_health))
}

/// Evaluate architecture gates (`max_dependency_cycles`, `max_propagation_cost`).
fn eval_arch_gates(
    thresholds: &codelore_lib::cli_api::quality_gates::Thresholds,
    db: &codelore_lib::cli_api::facts::FactsDb,
    ts: &str,
    head_sha: &str,
) -> Result<GateGroupResult> {
    let (arch_v, measured) =
        codelore_lib::cli_api::quality_gates::evaluate_architecture_gate_measured(thresholds, db)
            .context("evaluate architecture gate")?;
    let g = &thresholds.gates;
    let mut recs = Vec::new();
    if let (Some(max), Some(m)) = (g.max_dependency_cycles, measured) {
        let failed = arch_v.iter().any(|v| v.gate == "max_dependency_cycles");
        recs.push(make_rec(
            "max_dependency_cycles",
            f64::from(max),
            f64::from(m.cycle_count),
            failed,
            ts,
            head_sha,
        ));
    }
    if let (Some(max), Some(m)) = (g.max_propagation_cost, measured) {
        let failed = arch_v.iter().any(|v| v.gate == "max_propagation_cost");
        recs.push(make_rec(
            "max_propagation_cost",
            max,
            m.propagation_cost,
            failed,
            ts,
            head_sha,
        ));
    }
    Ok((arch_v, recs))
}

/// Evaluate all configured gates and build ledger records for this run.
///
/// Returns `(violations, ledger_records, hotspot_count, code_health_rows)`.
/// `code_health_rows` is returned so callers (e.g. `--ratchet`) can extract
/// ratchet metrics without re-running the analysis.
///
/// `external_store` is the pre-opened sidecar for the
/// `max_findings_in_hot_files` gate. Pass `Some(store)` when the sidecar exists
/// and holds findings; `None` when absent or empty (gate skipped, no sidecar
/// created).
///
/// This is a pure compute layer: it records each gate's verdict in the returned
/// ledger records (including `"skipped"` and `"degraded"`) and prints nothing.
/// `run_check_cmd` renders the skip/degraded notices from those records.
#[allow(clippy::type_complexity, clippy::too_many_lines)]
fn evaluate_all_gates(
    thresholds: &codelore_lib::cli_api::quality_gates::Thresholds,
    db: &codelore_lib::cli_api::facts::FactsDb,
    repo: &impl codelore_lib::cli_api::repo::Repo,
    opts: &codelore_lib::cli_api::Options,
    head_sha: &str,
    ts: &str,
    external_store: Option<&codelore_lib::cli_api::external::ExternalStore>,
) -> Result<(
    Vec<codelore_lib::cli_api::quality_gates::GateViolation>,
    Vec<codelore_lib::cli_api::quality_gates::ledger::GateRunRecord>,
    usize,
    Vec<codelore_lib::cli_api::analyses::code_health::CodeHealthRow>,
)> {
    use codelore_lib::cli_api::quality_gates::ledger::GateRunRecord;

    let mut violations = Vec::new();
    let mut recs = Vec::new();
    let g = &thresholds.gates;

    let ((hs_v, hs_r), hotspot_rows) = eval_hotspot_gates(thresholds, db, opts, ts, head_sha)?;
    let hotspot_count = hotspot_rows.len();
    violations.extend(hs_v);
    recs.extend(hs_r);

    let ((ch_v, ch_r), code_health) =
        eval_code_health_gate(thresholds, db, repo, opts, ts, head_sha)?;
    violations.extend(ch_v);
    recs.extend(ch_r);

    if g.disallow_clone_type_1 {
        let clone_v = codelore_lib::cli_api::quality_gates::evaluate_clone_gate(thresholds, db)
            .context("evaluate clone gate")?;
        let count = clone_v
            .first()
            .and_then(|v| v.actual.parse::<f64>().ok())
            .unwrap_or(0.0);
        recs.push(make_rec(
            "disallow_clone_type_1",
            0.0,
            count,
            !clone_v.is_empty(),
            ts,
            head_sha,
        ));
        violations.extend(clone_v);
    }

    let (arch_v, arch_r) = eval_arch_gates(thresholds, db, ts, head_sha)?;
    violations.extend(arch_v);
    recs.extend(arch_r);

    if let Some(max) = g.max_red_effort_pct {
        // Reuse the code-health rows already computed for `code_health_min` —
        // effort-exposure's band table derives from the same HEAD scan, and
        // the measured red-band churn share must be recorded on passing runs
        // too (the ratchet and `--history` read it from the ledger).
        //
        // With the improving-churn exemption on, decompose the red band's
        // window churn (a scoped window-start parse of the red files only, via
        // the repo) so the gate compares the DEGRADING share; otherwise stay on
        // the base SQL rows — no extra scan on the default path.
        use codelore_lib::cli_api::analyses::effort_exposure;
        let exempt = g.red_effort_exempt_improving;
        let no_limit = opts.with_no_row_limit();
        let rows = if exempt {
            effort_exposure::run_effort_exposure_decomposed(db, repo, &no_limit, &code_health)
        } else {
            effort_exposure::run_effort_exposure_with_health(db, &no_limit, &code_health)
        }
        .context("run effort-exposure for gate")?;
        // The recorded value is the effective gated number: the degrading share
        // when exempting (falling back to the total red share if the split is
        // unavailable), else the full red share.
        let red = rows.iter().find(|r| r.band == "red");
        let value = if exempt {
            red.and_then(|r| r.churn_share_degrading_pct)
                .or_else(|| red.map(|r| r.churn_share_pct))
                .unwrap_or(0.0)
        } else {
            red.map_or(0.0, |r| r.churn_share_pct)
        };
        let effort_v = codelore_lib::cli_api::quality_gates::evaluate_effort_exposure_rows_exempt(
            max, exempt, &rows,
        );
        recs.push(make_rec(
            "max_red_effort_pct",
            max,
            value,
            !effort_v.is_empty(),
            ts,
            head_sha,
        ));
        violations.extend(effort_v);
    }

    // ── [new_code] two-band period gate ──────────────────────────────────────
    if let Some(nc) = &thresholds.new_code {
        // Reuse the HEAD code-health rows already computed for `code_health_min`
        // (the born band's scores + the live-source universe) and the
        // effort-exposure window-start machinery (the touched band's net
        // movement) — no second health scan on this path.
        use codelore_lib::cli_api::analyses::new_code;
        let scope = new_code::run_new_code_scope(db, repo, opts, nc.window_days, &code_health)
            .context("run new-code scope for gate")?;
        if scope.window_start_present {
            let nc_v = codelore_lib::cli_api::quality_gates::evaluate_new_code_rows(nc, &scope);
            // Per-band ledger records so `--history` shows each obligation. The
            // ratchet reads its own typed metrics, not these, so new gate names
            // are display-only here.
            if let Some(floor) = nc.born_health_min {
                let worst = scope
                    .born
                    .iter()
                    .map(|(_, s)| *s)
                    .fold(f64::INFINITY, f64::min);
                recs.push(make_rec(
                    "born_health_min",
                    floor,
                    if worst.is_finite() { worst } else { 0.0 },
                    nc_v.iter().any(|v| v.gate == "born_health_min"),
                    ts,
                    head_sha,
                ));
            }
            if nc.touched_no_degradation {
                let worst = scope
                    .touched
                    .iter()
                    .map(|(_, n)| *n)
                    .fold(f64::INFINITY, f64::min);
                recs.push(make_rec(
                    "touched_no_degradation",
                    0.0,
                    if worst.is_finite() { worst } else { 0.0 },
                    nc_v.iter().any(|v| v.gate == "touched_no_degradation"),
                    ts,
                    head_sha,
                ));
            }
            violations.extend(nc_v);
        } else {
            // History shallower than the window ⇒ no legacy baseline to contrast
            // the working set against. Skip with disclosure, mirroring the
            // corpus_percentile_max / hotspot_anchored_max skip convention.
            recs.push(GateRunRecord {
                ts: ts.to_owned(),
                head_sha: head_sha.to_owned(),
                gate: "new_code".into(),
                threshold: f64::from(nc.window_days),
                value: 0.0,
                verdict: "skipped".into(),
                mode: "check".into(),
            });
        }
    }

    if let Some(min) = g.code_familiarity_min {
        let rows =
            codelore_lib::cli_api::analyses::code_familiarity::run_code_familiarity(db, opts)
                .context("run code-familiarity for gate")?;
        // Measured familiarity is recorded pass or fail; an empty row set
        // (no recognized source files) records 0.0 with a vacuous pass.
        // Unlike `code_health_min` this gate has no degraded sentinel: an
        // empty result IS the documented no-source-files contract, not a
        // scan failure.
        let value = rows.first().map_or(0.0, |r| r.familiarity_pct);
        let fam_v = codelore_lib::cli_api::quality_gates::evaluate_familiarity_rows(min, &rows);
        recs.push(make_rec(
            "code_familiarity_min",
            min,
            value,
            !fam_v.is_empty(),
            ts,
            head_sha,
        ));
        violations.extend(fam_v);
    }

    // ── max_findings_in_hot_files gate ───────────────────────────────────────
    if let Some(threshold) = g.max_findings_in_hot_files {
        // The gate is skipped (not failed) when the sidecar is absent OR present
        // but empty — both mean "no external findings to evaluate yet".
        // `external_store` already collapses those two states to `None` (via
        // `open_nonempty`), mirroring the MCP overlap tool. The `"skipped"`
        // verdict recorded here is what run_check_cmd renders the notice from.
        match external_store {
            None => {
                recs.push(GateRunRecord {
                    ts: ts.to_owned(),
                    head_sha: head_sha.to_owned(),
                    gate: "max_findings_in_hot_files".into(),
                    threshold: f64::from(threshold),
                    value: 0.0,
                    verdict: "skipped".into(),
                    mode: "check".into(),
                });
            }
            Some(store) => {
                // Reuse already-computed hotspot and code-health rows so we
                // don't re-run those analyses a second time (mirrors how
                // max_red_effort_pct reuses code_health above).
                let overlap_rows = codelore_lib::cli_api::analyses::finding_hotspot_overlap::run_finding_hotspot_overlap_with(
                    store,
                    &hotspot_rows,
                    &code_health,
                )
                .context("run finding-hotspot-overlap for gate")?;
                let act_now_count = overlap_rows
                    .iter()
                    .filter(|r| r.priority == "act-now")
                    .count();
                let overlap_v = codelore_lib::cli_api::quality_gates::evaluate_finding_overlap_rows(
                    threshold,
                    &overlap_rows,
                );
                #[allow(clippy::cast_precision_loss)]
                // act_now_count is a repo-scale count; precision loss negligible
                let act_now_f64 = act_now_count as f64;
                recs.push(GateRunRecord {
                    ts: ts.to_owned(),
                    head_sha: head_sha.to_owned(),
                    gate: "max_findings_in_hot_files".into(),
                    threshold: f64::from(threshold),
                    value: act_now_f64,
                    verdict: if overlap_v.is_empty() {
                        "passed"
                    } else {
                        "failed"
                    }
                    .into(),
                    mode: "check".into(),
                });
                violations.extend(overlap_v);
            }
        }
    }

    // ── corpus_percentile_max gate ───────────────────────────────────────────
    if let Some(max) = g.corpus_percentile_max {
        // Reuse the already-computed code-health rows. The lens is active only
        // when a calibration artifact is (`--calibration` or an embedded world
        // corpus); without one every row carries `corpus_percentile = None`.
        // That is a SKIP (not a pass, not a fail) — there is no reference corpus
        // to compare against — mirroring the max_findings sidecar-absent skip.
        let has_calibration = code_health.iter().any(|r| r.corpus_percentile.is_some());
        if has_calibration {
            let corpus_v = codelore_lib::cli_api::quality_gates::evaluate_corpus_percentile_rows(
                max,
                &code_health,
            );
            let value = code_health
                .iter()
                .filter_map(|r| r.corpus_percentile)
                .fold(0.0, f64::max);
            recs.push(make_rec(
                "corpus_percentile_max",
                max,
                value,
                !corpus_v.is_empty(),
                ts,
                head_sha,
            ));
            violations.extend(corpus_v);
        } else {
            recs.push(GateRunRecord {
                ts: ts.to_owned(),
                head_sha: head_sha.to_owned(),
                gate: "corpus_percentile_max".into(),
                threshold: max,
                value: 0.0,
                verdict: "skipped".into(),
                mode: "check".into(),
            });
        }
    }

    // ── hotspot_anchored_max gate ────────────────────────────────────────────
    if let Some(max) = g.hotspot_anchored_max {
        // Reuse the hotspot rows already computed for the hotspot gates —
        // `eval_hotspot_gates` runs them through `run_hotspots_anchored`, so the
        // anchor is populated exactly when a calibration artifact is active
        // (`--calibration` or the embedded world corpus). Without one every row
        // carries `hotspot_score_anchored = None`, which is a SKIP (not a pass,
        // not a fail): there is no reference corpus to compare against. Mirrors
        // the corpus_percentile_max skip above.
        let has_anchor = hotspot_rows
            .iter()
            .any(|r| r.hotspot_score_anchored.is_some());
        if has_anchor {
            let anchored_v = codelore_lib::cli_api::quality_gates::evaluate_hotspot_anchored_rows(
                max,
                &hotspot_rows,
            );
            let value = hotspot_rows
                .iter()
                .filter_map(|r| r.hotspot_score_anchored)
                .fold(0.0, f64::max);
            recs.push(make_rec(
                "hotspot_anchored_max",
                max,
                value,
                !anchored_v.is_empty(),
                ts,
                head_sha,
            ));
            violations.extend(anchored_v);
        } else {
            recs.push(GateRunRecord {
                ts: ts.to_owned(),
                head_sha: head_sha.to_owned(),
                gate: "hotspot_anchored_max".into(),
                threshold: max,
                value: 0.0,
                verdict: "skipped".into(),
                mode: "check".into(),
            });
        }
    }

    Ok((violations, recs, hotspot_count, code_health))
}

/// Emit a check SARIF document for `violations` (with their `evidence` chains)
/// to stdout. Canonicalizes `repo` for the artifact-URI prefix, falling back to
/// the path as-given when canonicalization fails (e.g. the path does not exist
/// on disk). Shared by the vacuous-pass path (empty violations + evidence) and
/// the violation path so the canonicalize + stdout + writer wiring lives once.
/// Write a ratchet status message to the right stream for the output format.
///
/// Under `--format sarif` the message goes to stderr so stdout stays a clean
/// SARIF document (mirroring the report path, which routes verdict lines to
/// stderr in SARIF mode); in text mode it goes to stdout with the rest of the
/// report. `msg` is written verbatim, so the caller supplies any trailing
/// newline.
fn emit_ratchet_message(args: &args::CheckArgs, msg: &str) {
    if matches!(args.format, CheckFormat::Sarif) {
        eprint!("{msg}");
    } else {
        print!("{msg}");
    }
}

/// Emit the check SARIF document to stdout when `--format sarif` is set;
/// no-op otherwise.
///
/// Collects a commit evidence chain for each violated per-file path and hands
/// the violations + evidence to [`emit_check_sarif`]. Shared by the normal
/// check path and every `--ratchet` exit path so the flag combination always
/// yields a valid document rather than silently emitting nothing.
fn emit_check_sarif_when_requested(
    args: &args::CheckArgs,
    db: &codelore_lib::cli_api::facts::FactsDb,
    opts: &codelore_lib::cli_api::Options,
    head_sha: &str,
    violations: &[codelore_lib::cli_api::quality_gates::GateViolation],
) -> Result<()> {
    use codelore_lib::cli_api::quality_gates::evidence::{EvidenceCommit, evidence_for_path};
    use std::collections::HashMap;

    if !matches!(args.format, CheckFormat::Sarif) {
        return Ok(());
    }

    // Collect evidence only for violated per-file paths (not repo-wide). A
    // failed lookup degrades that result to chainless (empty evidence) rather
    // than failing the SARIF emission; the failure is systemic and repeats per
    // path, so warn at most once per run via the ⚠-prefixed stderr convention.
    let mut evidence_map: HashMap<String, Vec<EvidenceCommit>> = HashMap::new();
    let mut evidence_warned = false;
    for v in violations {
        // Evidence is a per-file commit chain, so it is meaningless for a
        // pseudo-path. Same canonical predicate the emitters use, rather than
        // a third copy of the literal list.
        if !codelore_lib::cli_api::quality_gates::evaluators::is_pseudo_path(&v.path) {
            evidence_map.entry(v.path.clone()).or_insert_with(|| {
                evidence_for_path(db, opts, &v.path, 5).unwrap_or_else(|e| {
                    if !evidence_warned {
                        evidence_warned = true;
                        eprintln!(
                            "  ⚠ check: evidence lookup failed ({e}); SARIF results will be emitted without commit chains"
                        );
                    }
                    Vec::new()
                })
            });
        }
    }

    emit_check_sarif(&args.repo, head_sha, violations, &evidence_map)
}

fn emit_check_sarif(
    repo: &std::path::Path,
    head_sha: &str,
    violations: &[codelore_lib::cli_api::quality_gates::GateViolation],
    evidence: &std::collections::HashMap<
        String,
        Vec<codelore_lib::cli_api::quality_gates::evidence::EvidenceCommit>,
    >,
) -> Result<()> {
    let repo_root = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
    let mut stdout = std::io::stdout();
    codelore_lib::cli_api::output::sarif::write_check_sarif(
        violations,
        evidence,
        &repo_root,
        head_sha,
        &mut stdout,
    )
    .context("emit check SARIF")
}