codelore-lib 0.27.3

CodeLore — Behavioral Code Analyzer library
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
//! Engine tests for the change-set engine: the projected code-health half
//! (driven via `change_set::project_health` directly) and the full report
//! assembly (cycle splice, coupling absences, findings, sidecar memoisation)
//! via `change_set::build_change_set_report`. Each test clones its own copy
//! of a bundle fixture because it mutates the working tree.

use std::path::Path;

use codelore_lib::Options;
use codelore_lib::cache::repo_cache_dir;
use codelore_lib::change_set::{build_change_set_report, project_health};
use codelore_lib::facts::FactsDb;
use codelore_lib::repo::{GixRepo, Repo, WorktreeChange, WorktreeChangeKind};
use codelore_lib::test_support::coupling_repo;
use codelore_lib::test_support::differential_repo::{self, DifferentialRepo};

/// A monster function: nested loops + match + boolean conditionals so its
/// cyclomatic / cognitive / nesting / bool-op counts dominate the fixture,
/// pushing whatever file it lands in to the top of every complexity rank.
const MONSTER_FN: &str = r"
fn monster(x: i32) -> i32 {
    let mut acc = 0;
    for a in 0..x {
        if a % 2 == 0 && a % 3 == 0 || a % 5 == 0 {
            for b in 0..a {
                if b > 1 {
                    match b % 4 {
                        0 => { if b > 10 { acc += 1; } else { acc += 2; } }
                        1 => { while acc < 100 { acc += 1; if acc % 7 == 0 { break; } } }
                        2 => { for c in 0..b { if c > 3 && c < 9 || c == 5 { acc += c; } } }
                        _ => { if a > b { acc -= 1; } else { acc += 1; } }
                    }
                }
            }
        }
    }
    acc
}
";

/// Clone the fixture and ingest HEAD facts. Returns the fixture guard (keeps
/// the tempdir alive), an open repo handle, the fact store, and default opts.
fn fresh() -> (DifferentialRepo, GixRepo, FactsDb, Options) {
    let fx = differential_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open repo");
    let db = FactsDb::new_in_memory().expect("open fact store");
    let opts = Options {
        repo_path: fx.dir.path().to_path_buf(),
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");
    (fx, repo, db, opts)
}

fn modified(path: &str) -> WorktreeChange {
    WorktreeChange {
        path: path.to_string(),
        kind: WorktreeChangeKind::Modified,
        rename_from: None,
    }
}

#[test]
fn modified_file_gets_baseline_and_projected_scores() {
    let (fx, repo, db, opts) = fresh();
    let main_path = fx.dir.path().join("src/main.rs");
    let mut content = std::fs::read_to_string(&main_path).expect("read main.rs");
    content.push_str(MONSTER_FN);
    std::fs::write(&main_path, content).expect("write main.rs");

    let projection =
        project_health(&db, &repo, &opts, &[modified("src/main.rs")]).expect("project_health");
    let delta = projection
        .deltas
        .iter()
        .find(|d| d.path == "src/main.rs")
        .expect("src/main.rs has a delta row");

    let baseline = delta.baseline_score.expect("baseline scored");
    let projected = delta.projected_score.expect("projection scored");
    assert!(
        projected < baseline,
        "a deeply-nested high-complexity append must lower the score: \
         baseline {baseline}, projected {projected}",
    );
    assert!(
        delta.delta.expect("delta present") < 0.0,
        "delta must be negative: {:?}",
        delta.delta,
    );
    assert!(
        delta.reason.is_none(),
        "a fully-scored file needs no reason"
    );
}

/// `HealthProjection::baseline_median` — what `[diff] delta_code_health_min`
/// reads on the `codelore gate` / `gate_changes` MCP surface — must derive
/// from `code_health::CodeHealthRow::score` (the composite `code-health`
/// score, `[0, 100]`), NOT from `hotspots::HotspotRow::cognitive_health` (the
/// hotspots analysis's inline structural proxy, `[60, 100]`, which the SAME
/// threshold key instead reads on the `codelore diff` surface — see
/// `diff.rs`'s `median_code_health`). Pinned by independently recomputing
/// both medians over the identical `min_revs = 1`, uncapped population
/// `project_health` scans, and asserting `baseline_median` matches the
/// code-health one and diverges from the hotspots one — so a future
/// unification of the two surfaces is a deliberate edit, not a silent drift.
#[test]
fn baseline_median_reads_code_health_score_not_hotspots_cognitive_health() {
    let (_fx, repo, db, opts) = fresh();

    let projection = project_health(&db, &repo, &opts, &[]).expect("project_health");
    let baseline_median = projection
        .baseline_median
        .expect("delivery-scale fixture has scoreable files");

    let opts_scan = {
        let mut o = opts.with_no_row_limit();
        o.min_revs = 1;
        o
    };

    let health_rows = codelore_lib::analyses::code_health::run_code_health(&db, &opts_scan)
        .expect("run_code_health");
    let code_health_median = median_of(health_rows.iter().map(|r| r.score));
    assert!(
        (baseline_median - code_health_median).abs() < 1e-9,
        "baseline_median must equal the code-health composite score median: \
         baseline_median={baseline_median}, code_health_median={code_health_median}"
    );

    let hotspot_rows =
        codelore_lib::analyses::hotspots::run_hotspots(&db, &opts_scan).expect("run_hotspots");
    let hotspots_median = median_of(hotspot_rows.iter().map(|r| r.cognitive_health));
    assert!(
        (baseline_median - hotspots_median).abs() > 1e-6,
        "baseline_median must NOT equal the hotspots cognitive_health median — \
         the two are different metrics on different scales, and coincidental \
         equality here would hide a future accidental field swap: \
         baseline_median={baseline_median}, hotspots_median={hotspots_median}"
    );
}

/// Plain median over an f64 iterator, mirroring `change_set::median`'s
/// even/odd handling — kept local to the test so it does not depend on the
/// crate's private helper.
fn median_of(values: impl Iterator<Item = f64>) -> f64 {
    let mut v: Vec<f64> = values.collect();
    v.sort_by(|a, b| a.partial_cmp(b).expect("no NaNs in health scores"));
    let mid = v.len() / 2;
    if v.len() % 2 == 1 {
        v[mid]
    } else {
        f64::midpoint(v[mid - 1], v[mid])
    }
}

#[test]
fn unchanged_repo_projects_zero_delta() {
    let (fx, repo, db, opts) = fresh();
    // Write the HEAD blob back so the working-tree bytes equal HEAD exactly.
    // Byte-identical bytes re-parse to byte-identical rows, which rank
    // identically, which yields a delta of exactly 0.0.
    let head_bytes = repo
        .read_blob_at_head("src/main.rs")
        .expect("read blob")
        .expect("main.rs tracked at HEAD");
    std::fs::write(fx.dir.path().join("src/main.rs"), &head_bytes).expect("restore main.rs");

    let projection =
        project_health(&db, &repo, &opts, &[modified("src/main.rs")]).expect("project_health");
    let delta = projection
        .deltas
        .iter()
        .find(|d| d.path == "src/main.rs")
        .expect("src/main.rs has a delta row");

    assert_eq!(
        delta.delta,
        Some(0.0),
        "an identical re-parse must project exactly zero delta",
    );
}

#[test]
fn added_file_reports_no_history_baseline() {
    let (fx, repo, db, opts) = fresh();
    std::fs::write(
        fx.dir.path().join("src/added_new.rs"),
        "pub fn helper(a: i32) -> i32 { a + 1 }\n",
    )
    .expect("write added file");

    let change = WorktreeChange {
        path: "src/added_new.rs".to_string(),
        kind: WorktreeChangeKind::Added,
        rename_from: None,
    };
    let projection = project_health(&db, &repo, &opts, &[change]).expect("project_health");
    let delta = projection
        .deltas
        .iter()
        .find(|d| d.path == "src/added_new.rs")
        .expect("added file has a delta row");

    assert_eq!(
        delta.reason.as_deref(),
        Some("new file (no history baseline)")
    );
    assert!(
        delta.baseline_score.is_none(),
        "an added file has no baseline"
    );
    assert!(delta.delta.is_none(), "an added file has no delta");
}

#[test]
fn non_tier1_file_reports_reason() {
    let (fx, repo, db, opts) = fresh();
    std::fs::write(fx.dir.path().join("README.md"), "# changed heading\n").expect("edit README");

    let projection =
        project_health(&db, &repo, &opts, &[modified("README.md")]).expect("project_health");
    let delta = projection
        .deltas
        .iter()
        .find(|d| d.path == "README.md")
        .expect("README.md has a delta row");

    assert_eq!(delta.reason.as_deref(), Some("not a Tier-1 source file"));
    assert!(delta.delta.is_none(), "a non-source file has no delta");
}

#[test]
fn deleted_red_file_is_handled_honestly() {
    // spec §8: "delete a red-band file → assert improvement reporting."
    // Commit a monster-complexity version of src/main.rs first so its HEAD
    // baseline is genuinely red, then delete it (uncommitted, working-tree
    // only) and assert deterministic, honest-absence handling: no crash, the
    // `REASON_DELETED` reason, no synthetic projected score or delta, and the
    // baseline score preserved so the deletion's context isn't lost. This is
    // the "assert improvement reporting" spec bullet read literally per
    // `REASON_DELETED`'s doc comment: there is no safe, fixed-direction
    // per-file "improvement" number for a file that no longer exists to
    // score (verified below — the whole-repo median does not move in a
    // single guaranteed direction, because the projection also re-sources
    // clone/duplication counts from the working tree, which can shift OTHER
    // files' scores too), so the report stays honest rather than inventing
    // one.
    let fx = differential_repo::build();
    let main_path = fx.dir.path().join("src/main.rs");
    append(&main_path, MONSTER_FN);
    // Cross-platform: a fresh clone carries no committer identity, so every
    // `commit` call must supply one explicitly.
    let git = |args: &[&str]| {
        std::process::Command::new("git")
            .arg("-C")
            .arg(fx.dir.path())
            .args(["-c", "user.email=codelore-test@example.com"])
            .args(["-c", "user.name=CodeLore Test"])
            .args(args)
            .status()
            .expect("spawn git")
    };
    assert!(
        git(&["commit", "-aqm", "worsen main.rs"]).success(),
        "commit must succeed"
    );

    let repo = GixRepo::open(fx.dir.path()).expect("open repo");
    let db = FactsDb::new_in_memory().expect("open fact store");
    let opts = Options {
        repo_path: fx.dir.path().to_path_buf(),
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");

    // Confirm the committed baseline is genuinely red before deleting it.
    let baseline_probe =
        project_health(&db, &repo, &opts, &[modified("src/main.rs")]).expect("baseline probe");
    let baseline_delta = baseline_probe
        .deltas
        .iter()
        .find(|d| d.path == "src/main.rs")
        .expect("src/main.rs has a delta row");
    let baseline_score = baseline_delta
        .baseline_score
        .expect("committed main.rs is scored");
    assert_eq!(
        baseline_delta.baseline_band.as_deref(),
        Some("red"),
        "the monster-fn commit must make src/main.rs red at HEAD: {baseline_delta:?}",
    );

    // Now delete it (uncommitted) and project the change set. Must not
    // panic, and must resolve to the honest-absence shape.
    std::fs::remove_file(&main_path).expect("delete main.rs");
    let deletion = WorktreeChange {
        path: "src/main.rs".to_string(),
        kind: WorktreeChangeKind::Deleted,
        rename_from: None,
    };
    let projection = project_health(&db, &repo, &opts, &[deletion]).expect("project deletion");
    let delta = projection
        .deltas
        .iter()
        .find(|d| d.path == "src/main.rs")
        .expect("a deleted file still gets a delta row");

    assert_eq!(delta.reason.as_deref(), Some("deleted at gate time"));
    assert_eq!(
        delta.projected_score, None,
        "a deleted file has no projected score"
    );
    assert_eq!(
        delta.delta, None,
        "a deleted file reports no numeric per-file delta — excluded from \
         delta_code_health_min_per_file and new_file_health_min by construction"
    );
    assert_eq!(
        delta.baseline_score,
        Some(baseline_score),
        "the baseline score is preserved even though the file left the projection"
    );
    assert!(
        projection.baseline_median.is_some() && projection.projected_median.is_some(),
        "the whole-repo medians must still resolve deterministically around a deletion: {projection:?}",
    );
}

#[test]
fn project_health_leaves_the_fact_tables_untouched() {
    // Scoring isolation: the engine writes only session-scoped temp tables. The
    // persistent `complexity_metrics` row count and the set of permanent tables
    // must be identical before and after a projection.
    let (fx, repo, db, opts) = fresh();
    let main_path = fx.dir.path().join("src/main.rs");
    let mut content = std::fs::read_to_string(&main_path).expect("read main.rs");
    content.push_str(MONSTER_FN);
    std::fs::write(&main_path, content).expect("write main.rs");

    let cm_before = complexity_metrics_count(&db);
    let perm_before = permanent_table_count(&db);

    let _ = project_health(&db, &repo, &opts, &[modified("src/main.rs")]).expect("project_health");

    assert_eq!(
        complexity_metrics_count(&db),
        cm_before,
        "complexity_metrics row count must be unchanged",
    );
    assert_eq!(
        permanent_table_count(&db),
        perm_before,
        "no new permanent tables may be created",
    );
}

/// Append `text` to the file at `path`.
fn append(path: &Path, text: &str) {
    let mut content = std::fs::read_to_string(path).expect("read file");
    content.push_str(text);
    std::fs::write(path, content).expect("write file");
}

/// Count the `.json` sidecar entries in `dir` (0 when the dir doesn't exist).
fn sidecar_count(dir: &Path) -> usize {
    std::fs::read_dir(dir).map_or(0, |entries| {
        entries
            .flatten()
            .filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some("json"))
            .count()
    })
}

#[test]
fn newly_cyclic_detected_when_edit_introduces_cycle() {
    let (fx, repo, db, opts) = fresh();
    // A working-tree edit that makes src/main.rs and src/lib.rs import each
    // other via the `crate::` form the Rust resolver maps to `src/<name>.rs`.
    // Neither file imports the other at HEAD, so the pair is a NEW cycle.
    append(&fx.dir.path().join("src/main.rs"), "use crate::lib;\n");
    append(&fx.dir.path().join("src/lib.rs"), "use crate::main;\n");
    let cache_root = tempfile::tempdir().expect("cache root");

    let report = build_change_set_report(&db, &repo, &opts, cache_root.path()).expect("report");

    assert_eq!(
        report.newly_cyclic_paths,
        vec!["src/lib.rs".to_string(), "src/main.rs".to_string()],
        "the edit-introduced cycle members must be newly cyclic, sorted",
    );
    for path in ["src/lib.rs", "src/main.rs"] {
        assert!(
            report
                .findings
                .iter()
                .any(|f| f.kind == "newly-cyclic" && f.path == path),
            "a newly-cyclic finding must name {path}: {:?}",
            report.findings,
        );
    }
}

#[test]
fn unchanged_tree_projects_zero_delta_with_clones_present() {
    // Dual-source DRY must not perturb the exact-0.0 invariant when clones
    // actually exist at HEAD: with `min_clone_node_count: 0` the HEAD `clones`
    // table is populated, so this exercises the baseline's HEAD-table counts
    // against the projection's working-tree walk on identical content. A
    // content-identical re-parse must still project exactly 0.0.
    let fx = differential_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open repo");
    let db = FactsDb::new_in_memory().expect("open fact store");
    let opts = Options {
        repo_path: fx.dir.path().to_path_buf(),
        min_clone_node_count: 0,
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");
    // Write the HEAD blob back so the working-tree bytes equal HEAD exactly,
    // then force the (content-identical) change into the projection.
    let head_bytes = repo
        .read_blob_at_head("src/main.rs")
        .expect("read blob")
        .expect("main.rs tracked at HEAD");
    std::fs::write(fx.dir.path().join("src/main.rs"), &head_bytes).expect("restore main.rs");

    let projection =
        project_health(&db, &repo, &opts, &[modified("src/main.rs")]).expect("project_health");
    let delta = projection
        .deltas
        .iter()
        .find(|d| d.path == "src/main.rs")
        .expect("src/main.rs has a delta row");
    assert_eq!(
        delta.delta,
        Some(0.0),
        "an unchanged tree must project exactly zero delta even with clones present",
    );
}

#[test]
fn worktree_clone_introduction_surfaces_a_finding() {
    // Dual-source DRY: the baseline reads HEAD-faithful clone counts from the
    // ingested `clones` table while the projection walks the working tree, so a
    // duplicate introduced only in the working tree can no longer cancel to
    // zero between the two runs. `min_clone_node_count: 0` lets the small
    // fixture functions register as a clone family.
    let fx = differential_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open repo");
    let db = FactsDb::new_in_memory().expect("open fact store");
    let opts = Options {
        repo_path: fx.dir.path().to_path_buf(),
        min_clone_node_count: 0,
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");

    // Two structurally-identical (Type-2) functions absent at HEAD: they form a
    // new clone family in the working tree only, so src/main.rs gains clone
    // members the HEAD baseline does not carry.
    append(
        &fx.dir.path().join("src/main.rs"),
        "\nfn dup_alpha(a: i32) -> i32 { let p = a + 1; let q = p * 2; let r = q - 3; r + p + q }\n\
         fn dup_beta(b: i32) -> i32 { let s = b + 1; let t = s * 2; let u = t - 3; u + s + t }\n",
    );
    let cache_root = tempfile::tempdir().expect("cache root");

    let report = build_change_set_report(&db, &repo, &opts, cache_root.path()).expect("report");

    assert!(
        report
            .findings
            .iter()
            .any(|f| f.kind == "clone-introduction" && f.path == "src/main.rs"),
        "a working-tree-introduced duplicate must raise a clone-introduction finding: {:?}",
        report.findings,
    );
    // The projection must never read the introduced clone as an improvement.
    if let Some(delta) = report
        .health
        .deltas
        .iter()
        .find(|d| d.path == "src/main.rs")
        .and_then(|d| d.delta)
    {
        assert!(
            delta <= 0.0,
            "an introduced duplicate must not raise the projected health: {delta}",
        );
    }
}

#[test]
fn absence_fires_for_historical_partner() {
    // The coupling fixture's src/alpha/svc.rs and src/beta/svc.rs co-change in
    // 7 of 19 commits (each has 9 revisions) — a Fisher-significant pair well
    // above the shared-revisions floor. Touching only one side must flag the
    // other as an absent historical partner.
    let fx = coupling_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open repo");
    let db = FactsDb::new_in_memory().expect("open fact store");
    let opts = Options {
        repo_path: fx.dir.path().to_path_buf(),
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");
    append(
        &fx.dir.path().join("src/alpha/svc.rs"),
        "\npub fn gate_probe() {}\n",
    );
    let cache_root = tempfile::tempdir().expect("cache root");

    let report = build_change_set_report(&db, &repo, &opts, cache_root.path()).expect("report");

    let absence = report
        .coupling_absences
        .iter()
        .find(|a| a.touched_file == "src/alpha/svc.rs" && a.expected_partner == "src/beta/svc.rs")
        .expect("the historically-coupled partner must be flagged absent");
    assert!(
        absence.historical_shared_revs >= 5,
        "the pair's shared revisions carry the signal strength: {absence:?}",
    );
    assert!(
        report
            .findings
            .iter()
            .any(|f| f.kind == "coupling-absence" && f.path == "src/alpha/svc.rs"),
        "a coupling-absence finding must name the touched file: {:?}",
        report.findings,
    );
}

#[test]
fn report_is_memoised_by_content() {
    let (fx, repo, db, opts) = fresh();
    let main_path = fx.dir.path().join("src/main.rs");
    append(&main_path, MONSTER_FN);
    let cache_root = tempfile::tempdir().expect("cache root");
    let sidecar_dir = repo_cache_dir(cache_root.path(), fx.dir.path()).join("change-set");

    let first = build_change_set_report(&db, &repo, &opts, cache_root.path()).expect("first");
    assert_eq!(
        sidecar_count(&sidecar_dir),
        1,
        "first build writes a sidecar"
    );
    let second = build_change_set_report(&db, &repo, &opts, cache_root.path()).expect("second");
    assert_eq!(first, second, "a warm rebuild must return the same report");
    assert_eq!(
        sidecar_count(&sidecar_dir),
        1,
        "unchanged content must hit the same sidecar entry",
    );

    append(&main_path, "\n// content flip\n");
    let _third = build_change_set_report(&db, &repo, &opts, cache_root.path()).expect("third");
    assert_eq!(
        sidecar_count(&sidecar_dir),
        2,
        "flipped content must produce a different cache key",
    );
}

#[test]
fn report_key_folds_in_defect_calibration() {
    // `--defect-calibration` substitutes smell weights inside the scoring
    // engine, so it changes the MEASURED scores in the report — not just the
    // verdict. A calibrated and an uncalibrated run on the same worktree and
    // HEAD must not share a cache entry, and the key must track the artifact's
    // CONTENT so editing it in place is visible.
    let fx = differential_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open repo");
    let head_sha = repo.head_sha().expect("head sha");
    let root = fx.dir.path();
    let changes = [modified("src/main.rs")];

    let calib_a = root.join("a.calib.json");
    std::fs::write(&calib_a, br#"{"weights":"a"}"#).expect("write calib a");
    let calib_b = root.join("b.calib.json");
    std::fs::write(&calib_b, br#"{"weights":"b"}"#).expect("write calib b");

    let key = |cal: Option<std::path::PathBuf>| {
        let opts = Options {
            repo_path: root.to_path_buf(),
            defect_calibration: cal,
            ..Options::default()
        };
        codelore_lib::change_set::cache::report_key(&head_sha, &changes, &opts).expect("report_key")
    };

    let uncalibrated = key(None);
    let calibrated_a = key(Some(calib_a.clone()));
    let calibrated_a_again = key(Some(calib_a));
    let calibrated_b = key(Some(calib_b));

    assert_ne!(
        uncalibrated, calibrated_a,
        "calibrated and uncalibrated runs must not share a cache key",
    );
    assert_eq!(
        calibrated_a, calibrated_a_again,
        "identical artifact content must yield a stable key",
    );
    assert_ne!(
        calibrated_a, calibrated_b,
        "different artifact content must yield different keys",
    );
}

#[test]
fn report_key_folds_in_min_revs() {
    // Regression: `report_key` used to cover only head_sha + change-set
    // content + defect-calibration digest — every other report-affecting
    // `Options` knob was invisible to the cache key. `min_revs` reaches
    // `run_coupling(db, opts)` inside `build_change_set_report` (the ORIGINAL
    // `opts`, not the health projection's `min_revs = 1` override), so two
    // runs differing only in `min_revs` can legitimately produce different
    // coupling-absence findings and must not share a cache entry.
    let fx = differential_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open repo");
    let head_sha = repo.head_sha().expect("head sha");
    let changes = [modified("src/main.rs")];

    let opts_a = Options {
        repo_path: fx.dir.path().to_path_buf(),
        min_revs: 1,
        ..Options::default()
    };
    let opts_b = Options {
        min_revs: 7,
        ..opts_a.clone()
    };
    let opts_a_again = opts_a.clone();

    let key_a = codelore_lib::change_set::cache::report_key(&head_sha, &changes, &opts_a)
        .expect("report_key a");
    let key_b = codelore_lib::change_set::cache::report_key(&head_sha, &changes, &opts_b)
        .expect("report_key b");
    let key_a_again =
        codelore_lib::change_set::cache::report_key(&head_sha, &changes, &opts_a_again)
            .expect("report_key a again");

    assert_ne!(
        key_a, key_b,
        "differing only in min_revs must yield different cache keys",
    );
    assert_eq!(
        key_a, key_a_again,
        "identical Options must yield an identical cache key",
    );
}

#[test]
fn report_key_folds_in_rows_limit() {
    // Regression: `canonical_json` deliberately drops `rows_limit` as
    // cosmetic for the ingest cache, but `build_change_set_report`'s
    // `run_coupling(db, opts)` call truncates to it BEFORE the
    // coupling-absence filter runs — not cosmetic for this report. Folded in
    // explicitly alongside the canonical digest.
    let fx = differential_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open repo");
    let head_sha = repo.head_sha().expect("head sha");
    let changes = [modified("src/main.rs")];

    let opts_a = Options {
        repo_path: fx.dir.path().to_path_buf(),
        rows_limit: None,
        ..Options::default()
    };
    let opts_b = Options {
        rows_limit: Some(5),
        ..opts_a.clone()
    };

    let key_a = codelore_lib::change_set::cache::report_key(&head_sha, &changes, &opts_a)
        .expect("report_key a");
    let key_b = codelore_lib::change_set::cache::report_key(&head_sha, &changes, &opts_b)
        .expect("report_key b");

    assert_ne!(
        key_a, key_b,
        "differing only in rows_limit must yield different cache keys",
    );
}

#[test]
fn finding_ids_stable_across_runs() {
    let (fx, repo, db, opts) = fresh();
    append(&fx.dir.path().join("src/main.rs"), MONSTER_FN);
    // Distinct cache roots so the second build recomputes rather than being
    // served from the first build's sidecar.
    let cache_a = tempfile::tempdir().expect("cache a");
    let cache_b = tempfile::tempdir().expect("cache b");

    let first = build_change_set_report(&db, &repo, &opts, cache_a.path()).expect("first");
    let second = build_change_set_report(&db, &repo, &opts, cache_b.path()).expect("second");

    assert!(
        !first.findings.is_empty(),
        "the monster append must produce at least a health-drop finding",
    );
    let ids_a: Vec<&str> = first.findings.iter().map(|f| f.id.as_str()).collect();
    let ids_b: Vec<&str> = second.findings.iter().map(|f| f.id.as_str()).collect();
    assert_eq!(ids_a, ids_b, "finding ids must be stable across runs");
    for f in &first.findings {
        assert_eq!(
            f.id.len(),
            12,
            "finding id is a 12-hex digest prefix: {f:?}"
        );
        assert!(
            f.id.chars().all(|c| c.is_ascii_hexdigit()),
            "finding id must be hex: {f:?}",
        );
    }
}

#[test]
fn report_renders_byte_identical_across_two_builds() {
    // Full determinism: two independent ingests of the same mutated clone,
    // each with its own cold cache, must serialize to byte-identical JSON.
    let fx = differential_repo::build();
    let repo = GixRepo::open(fx.dir.path()).expect("open repo");
    let opts = Options {
        repo_path: fx.dir.path().to_path_buf(),
        ..Options::default()
    };
    append(&fx.dir.path().join("src/main.rs"), MONSTER_FN);

    let mut jsons = Vec::new();
    for label in ["a", "b"] {
        let db = FactsDb::new_in_memory().expect("open fact store");
        db.ingest(&repo, &opts).expect("ingest");
        let cache_root = tempfile::tempdir().expect("cache root");
        let report = build_change_set_report(&db, &repo, &opts, cache_root.path()).expect("report");
        jsons.push(serde_json::to_string(&report).unwrap_or_else(|e| panic!("json {label}: {e}")));
    }
    assert_eq!(jsons[0], jsons[1], "rendered report must be byte-identical");
}

fn complexity_metrics_count(db: &FactsDb) -> i64 {
    db.query_row("SELECT COUNT(*) FROM complexity_metrics", [], |r| r.get(0))
        .expect("count complexity_metrics")
}

fn permanent_table_count(db: &FactsDb) -> i64 {
    db.query_row(
        "SELECT COUNT(*) FROM duckdb_tables() WHERE temporary = false",
        [],
        |r| r.get(0),
    )
    .expect("count permanent tables")
}