orchestratectl 0.1.5

Rust CLI for orchestrating AI-agent workflows on a developer's machine.
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
//! The deterministic floor gates (design.md §4) — pure functions returning a
//! structured verdict.
//!
//! Each `gate_*` function is a **pure** function of already-collected snapshots
//! and diffs: it makes no LLM call and no judgment, only mechanical
//! set/inequality checks. That is the whole point of the floor — a ground-truth
//! oracle the autonomous loop can trust *below* the advisory LLM verify layer
//! (design.md §0.1, §4). Capture (running tests/clippy/git) is impure and lives
//! in [`super::runner`]/[`super::git`]; the gates never do I/O.
//!
//! The gates enforced (design.md §4):
//! 1. [`gate_checks_pass`] — the relevant checks pass.
//! 2. [`gate_no_regression`] — no test that passed at baseline is now failing.
//! 3. [`gate_no_new_clippy`] — no new clippy warnings vs baseline.
//! 4. [`gate_no_test_gaming`] — test count didn't drop; none newly ignored;
//!    no baseline test vanished (rename-to-no-op); assertion density didn't
//!    regress in touched files.
//! 5. [`gate_enumeration_superset`] — the enumerated test-*target* set did not
//!    shrink vs baseline (`floor-capture-hardening-round-2` F7): a
//!    narrowed/empty test-binary set fails closed instead of passing vacuously.
//! 6. [`gate_file_scope`] — changed files stay within `files_touched[]` + slack.
//!
//! [`evaluate_floor`] runs all six over a [`FloorInputs`] and returns a
//! [`FloorVerdict`] the supervisor (at T5) will branch on.

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

use super::snapshot::{CheckRun, ClippySnapshot, ClippyWarning, RunSnapshot, TestId, TestSnapshot};

/// Which floor gate a [`GateOutcome`] / [`Violation`] belongs to.
///
/// `#[non_exhaustive]`: this is serialized into audit logs / node.report assets
/// that external consumers (spec-nodes, the front-end rollup) read, so adding a
/// gate later must not be a breaking change for them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum GateKind {
    /// The chunk/feature checks all pass.
    ChecksPass,
    /// No baseline-passing test now fails.
    NoRegression,
    /// No new clippy warning vs baseline.
    NoNewClippy,
    /// The test suite was not gamed (count/ignore/rename/assertion-density).
    NoTestGaming,
    /// The enumerated test-target set did not shrink vs baseline (F7).
    EnumerationIntegrity,
    /// Changed files stay within declared scope + slack.
    FileScope,
}

impl GateKind {
    /// Stable human label for logs/reports.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            GateKind::ChecksPass => "checks-pass",
            GateKind::NoRegression => "no-regression",
            GateKind::NoNewClippy => "no-new-clippy",
            GateKind::NoTestGaming => "no-test-gaming",
            GateKind::EnumerationIntegrity => "enumeration-integrity",
            GateKind::FileScope => "file-scope",
        }
    }
}

/// One specific, mechanical reason a gate failed. Serde-tagged so a supervisor
/// can record and route the exact violation (design.md §8 findings→action),
/// never a free-text blob.
///
/// `#[non_exhaustive]`: serialized for external consumers (audit logs, the
/// post-merge rollup), so a new violation kind must not break their deserializers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Violation {
    /// A required check did not pass.
    CheckFailed {
        /// The check's description.
        desc: String,
        /// The command that failed.
        run: String,
        /// Its exit code, if it ran to completion.
        exit_code: Option<i32>,
    },
    /// A test that passed at baseline now fails.
    TestRegressed {
        /// The regressed, target-qualified test id.
        test: TestId,
    },
    /// A clippy warning present now but not at baseline.
    NewClippyWarning {
        /// The new warning's structured identity (lint + package + file + message).
        warning: ClippyWarning,
    },
    /// The total test count dropped vs baseline.
    TestCountDropped {
        /// Distinct tests at baseline.
        baseline: usize,
        /// Distinct tests now.
        current: usize,
    },
    /// A test that passed at baseline is now `#[ignore]`d/skipped.
    NewlyIgnoredTest {
        /// The now-ignored, target-qualified test id.
        test: TestId,
    },
    /// A test present at baseline is entirely absent now (deleted or
    /// renamed-to-no-op) — the crude rename/removal signal.
    MissingBaselineTest {
        /// The vanished, target-qualified test id.
        test: TestId,
    },
    /// Assertion density in a touched file dropped vs baseline.
    AssertionDensityRegressed {
        /// The file whose assertion count dropped.
        file: PathBuf,
        /// `assert*!` occurrences at baseline.
        baseline: usize,
        /// `assert*!` occurrences now.
        current: usize,
    },
    /// A changed file lies outside the declared `files_touched[]` scope.
    OutOfScopeFile {
        /// The out-of-scope path.
        file: PathBuf,
    },
    /// A test **target** enumerated at baseline is absent from the tip's
    /// enumeration (F7) — a narrowed/empty test-binary set (a workspace-narrowing
    /// alias, `--exclude`, `harness = false`, or a build that produced fewer test
    /// harnesses) that would otherwise capture a smaller snapshot and pass
    /// vacuously.
    EnumerationShrank {
        /// The canonical `package/target_kind/target` that vanished from the
        /// enumeration.
        target: String,
    },
}

/// The outcome of one gate: pass/fail, a one-line summary, and the specific
/// violations when it failed (empty on pass).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GateOutcome {
    /// Which gate this is.
    pub gate: GateKind,
    /// Whether the gate passed.
    pub passed: bool,
    /// One-line human summary (the "reason", pass or fail).
    pub summary: String,
    /// Specific violations; empty iff `passed`.
    pub violations: Vec<Violation>,
}

impl GateOutcome {
    fn pass(gate: GateKind, summary: impl Into<String>) -> Self {
        Self {
            gate,
            passed: true,
            summary: summary.into(),
            violations: Vec::new(),
        }
    }

    fn fail(gate: GateKind, summary: impl Into<String>, violations: Vec<Violation>) -> Self {
        Self {
            gate,
            passed: false,
            summary: summary.into(),
            violations,
        }
    }
}

/// The aggregate verdict across every floor gate.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FloorVerdict {
    /// Per-gate outcomes, in [`GateKind`] declaration order.
    pub gates: Vec<GateOutcome>,
}

impl FloorVerdict {
    /// The floor passes iff **every** gate passes (design.md §4: a merge is
    /// blocked unless all hold).
    #[must_use]
    pub fn passed(&self) -> bool {
        self.gates.iter().all(|g| g.passed)
    }

    /// Every violation across all failed gates.
    pub fn violations(&self) -> impl Iterator<Item = &Violation> {
        self.gates.iter().flat_map(|g| g.violations.iter())
    }

    /// The gates that failed.
    pub fn failed_gates(&self) -> impl Iterator<Item = &GateOutcome> {
        self.gates.iter().filter(|g| !g.passed)
    }
}

/// Everything [`evaluate_floor`] needs, all pre-collected by the impure capture
/// layer. Borrowed so the caller keeps ownership of the snapshots it persists.
#[derive(Debug, Clone, Copy)]
pub struct FloorInputs<'a> {
    /// Snapshot at the `feat/<slug>` fork.
    pub baseline: &'a RunSnapshot,
    /// Snapshot at the current feature/chunk tip.
    pub current: &'a RunSnapshot,
    /// Results of running the relevant `checks` (design.md §4 point 1).
    pub check_results: &'a [CheckRun],
    /// Declared `files_touched[]` for the chunk/feature.
    pub declared_files: &'a [PathBuf],
    /// Files actually changed (`git diff --name-only <base>..<tip>`).
    pub changed_files: &'a [PathBuf],
    /// `assert*!` counts per touched file at baseline.
    pub baseline_assertions: &'a BTreeMap<PathBuf, usize>,
    /// `assert*!` counts per touched file now.
    pub current_assertions: &'a BTreeMap<PathBuf, usize>,
    /// How many out-of-scope files to tolerate before failing file-scope.
    pub file_scope_slack: usize,
}

/// Run every floor gate over `inputs` and collect a [`FloorVerdict`]. Pure:
/// deterministic in its inputs, no I/O, no judgment.
#[must_use]
pub fn evaluate_floor(inputs: &FloorInputs) -> FloorVerdict {
    FloorVerdict {
        gates: vec![
            gate_checks_pass(inputs.check_results),
            gate_no_regression(&inputs.baseline.tests, &inputs.current.tests),
            gate_no_new_clippy(&inputs.baseline.clippy, &inputs.current.clippy),
            gate_no_test_gaming(
                &inputs.baseline.tests,
                &inputs.current.tests,
                inputs.baseline_assertions,
                inputs.current_assertions,
            ),
            gate_enumeration_superset(&inputs.baseline.tests, &inputs.current.tests),
            gate_file_scope(
                inputs.declared_files,
                inputs.changed_files,
                inputs.file_scope_slack,
            ),
        ],
    }
}

/// Gate 1 — every relevant check passed (design.md §4 point 1).
#[must_use]
pub fn gate_checks_pass(results: &[CheckRun]) -> GateOutcome {
    let failed: Vec<Violation> = results
        .iter()
        .filter(|r| !r.passed)
        .map(|r| Violation::CheckFailed {
            desc: r.desc.clone(),
            run: r.run.clone(),
            exit_code: r.exit_code,
        })
        .collect();
    if failed.is_empty() {
        GateOutcome::pass(
            GateKind::ChecksPass,
            format!("all {} check(s) passed", results.len()),
        )
    } else {
        GateOutcome::fail(
            GateKind::ChecksPass,
            format!("{} of {} check(s) failed", failed.len(), results.len()),
            failed,
        )
    }
}

/// Gate 2 — no test that passed at baseline is now failing (design.md §4
/// point 2). A baseline-passing test that *vanished* is not a regression here
/// (it can't "fail" if it doesn't run); [`gate_no_test_gaming`] catches removal.
#[must_use]
pub fn gate_no_regression(baseline: &TestSnapshot, current: &TestSnapshot) -> GateOutcome {
    let regressed: Vec<Violation> = baseline
        .passed
        .intersection(&current.failed)
        .map(|t| Violation::TestRegressed { test: t.clone() })
        .collect();
    if regressed.is_empty() {
        GateOutcome::pass(GateKind::NoRegression, "no baseline-passing test now fails")
    } else {
        GateOutcome::fail(
            GateKind::NoRegression,
            format!("{} baseline-passing test(s) now fail", regressed.len()),
            regressed,
        )
    }
}

/// Gate 3 — no clippy warning present now that was absent at baseline
/// (design.md §4 point 3). Fixing a baseline warning is fine; introducing one
/// is not.
#[must_use]
pub fn gate_no_new_clippy(baseline: &ClippySnapshot, current: &ClippySnapshot) -> GateOutcome {
    let new: Vec<Violation> = current
        .warnings
        .difference(&baseline.warnings)
        .map(|w| Violation::NewClippyWarning { warning: w.clone() })
        .collect();
    if new.is_empty() {
        GateOutcome::pass(GateKind::NoNewClippy, "no new clippy warnings vs baseline")
    } else {
        GateOutcome::fail(
            GateKind::NoNewClippy,
            format!("{} new clippy warning(s) vs baseline", new.len()),
            new,
        )
    }
}

/// Gate 4 — the test suite was not gamed (design.md §4 point 4). Four crude,
/// mechanical signals, all reported together:
/// - **count dropped**: fewer distinct tests than baseline;
/// - **newly ignored**: a test that ran at baseline (passed or failed) is now `#[ignore]`d/skipped;
/// - **vanished**: a baseline test id is entirely absent now (delete / rename-to-no-op);
/// - **assertion density regressed**: a touched file has fewer `assert*!` than baseline.
#[must_use]
pub fn gate_no_test_gaming(
    baseline: &TestSnapshot,
    current: &TestSnapshot,
    baseline_assertions: &BTreeMap<PathBuf, usize>,
    current_assertions: &BTreeMap<PathBuf, usize>,
) -> GateOutcome {
    let mut violations = Vec::new();

    // Test count must not drop.
    let (base_total, cur_total) = (baseline.total(), current.total());
    if cur_total < base_total {
        violations.push(Violation::TestCountDropped {
            baseline: base_total,
            current: cur_total,
        });
    }

    // A test known at baseline (passing OR failing) that is now
    // `#[ignore]`d/skipped = gaming: skipping a passing test drops coverage, and
    // skipping a failing test hides an unresolved failure. A test already
    // ignored at baseline, and a brand-new test that happens to be ignored, are
    // both fine — only a *newly* ignored, previously-run test is flagged.
    let baseline_run: BTreeSet<&TestId> = baseline.passed.union(&baseline.failed).collect();
    for test in current.ignored.difference(&baseline.ignored) {
        if baseline_run.contains(test) {
            violations.push(Violation::NewlyIgnoredTest { test: test.clone() });
        }
    }

    // A baseline test id entirely absent now — deleted or renamed to a no-op.
    let current_ids = current.all_ids();
    for test in &baseline.all_ids() {
        if !current_ids.contains(test) {
            violations.push(Violation::MissingBaselineTest { test: test.clone() });
        }
    }

    // Assertion density must not regress in a file present at both refs. A file
    // only in the current map (newly created) has no baseline to regress from.
    for (file, &base_count) in baseline_assertions {
        let cur_count = current_assertions.get(file).copied().unwrap_or(0);
        if cur_count < base_count {
            violations.push(Violation::AssertionDensityRegressed {
                file: file.clone(),
                baseline: base_count,
                current: cur_count,
            });
        }
    }

    if violations.is_empty() {
        GateOutcome::pass(
            GateKind::NoTestGaming,
            format!("no gaming signal ({cur_total} tests, assertion density held)"),
        )
    } else {
        GateOutcome::fail(
            GateKind::NoTestGaming,
            format!("{} test-gaming signal(s)", violations.len()),
            violations,
        )
    }
}

/// Gate 5 — enumeration integrity (`floor-capture-hardening-round-2` item 2 /
/// F7). The set of enumerated test **targets** at the tip must be a **superset**
/// of the baseline's: every `(package, target_kind, target)` that produced a test
/// harness at the fork must still produce one now. A *shrink* — a target that
/// vanished — is a fail-closed violation, because a narrowed or empty test-binary
/// set (a workspace-narrowing alias, `--exclude`, an undeclared `harness = false`,
/// or a build that simply produced fewer harnesses) otherwise captures a smaller
/// snapshot whose missing tests can never regress, count-drop, or vanish in the
/// other gates — the whole point of those gates is defeated when the tests are
/// not enumerated at all. New targets are fine (superset holds); only a
/// disappearance blocks.
///
/// This complements [`gate_no_test_gaming`]'s per-*test* signals with a
/// per-*target* one: the former catches a single test deleted from a still-built
/// harness; this catches the whole harness disappearing (where the former's
/// baseline-test-ids also vanish, but this names the structural cause).
#[must_use]
pub fn gate_enumeration_superset(baseline: &TestSnapshot, current: &TestSnapshot) -> GateOutcome {
    let missing: Vec<Violation> = baseline
        .targets
        .difference(&current.targets)
        .map(|t| Violation::EnumerationShrank { target: t.clone() })
        .collect();
    if missing.is_empty() {
        GateOutcome::pass(
            GateKind::EnumerationIntegrity,
            format!(
                "enumerated target set held ({} target(s), tip ⊇ baseline)",
                current.targets.len()
            ),
        )
    } else {
        GateOutcome::fail(
            GateKind::EnumerationIntegrity,
            format!(
                "{} enumerated test target(s) vanished vs baseline",
                missing.len()
            ),
            missing,
        )
    }
}

/// Gate 6 — file-scope (design.md §4: "File-scope is a merge-time
/// constraint"). Any changed file not in `declared` is out of scope; the gate
/// fails when the out-of-scope count exceeds `slack`. Out-of-scope files are
/// reported as violations only when the gate fails (within-slack drift is noted
/// in the summary, not raised as a violation).
///
/// `changed` is de-duplicated into a set first, so a path that appears twice in
/// the input cannot consume the slack budget twice. Paths are compared verbatim
/// (already-canonical repo-relative paths — the plan validator's
/// `is_safe_repo_relative` rejects `.`/`..`/`//` components at authoring time,
/// so both sides are normal forms). This is a lexical guard; symlink resolution
/// and byte-exact-vs-normalized path equivalence are out of scope (as `plan.rs`
/// documents) and hardening is tracked in `floor-capture-trust-model`.
#[must_use]
pub fn gate_file_scope(declared: &[PathBuf], changed: &[PathBuf], slack: usize) -> GateOutcome {
    let declared_set: BTreeSet<&PathBuf> = declared.iter().collect();
    // De-duplicate `changed` so a repeated path is one out-of-scope file, not N.
    let changed_set: BTreeSet<&PathBuf> = changed.iter().collect();
    let out_of_scope: Vec<PathBuf> = changed_set
        .into_iter()
        .filter(|f| !declared_set.contains(*f))
        .cloned()
        .collect();

    if out_of_scope.len() <= slack {
        GateOutcome::pass(
            GateKind::FileScope,
            format!(
                "{} changed file(s), {} out-of-scope within slack {}",
                changed.len(),
                out_of_scope.len(),
                slack
            ),
        )
    } else {
        let n = out_of_scope.len();
        GateOutcome::fail(
            GateKind::FileScope,
            format!("{n} out-of-scope file(s) exceed slack {slack}"),
            out_of_scope
                .into_iter()
                .map(|file| Violation::OutOfScopeFile { file })
                .collect(),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Target-qualified test set from bare names (all in one synthetic target),
    /// so the existing gate-logic tests read the same as before.
    fn tset(items: &[&str]) -> BTreeSet<TestId> {
        items.iter().map(|n| tid(n)).collect()
    }

    fn tid(name: &str) -> TestId {
        TestId::new("pkg", "lib", "pkg", name)
    }

    /// Clippy warning set from bare identity strings (lint code = the string).
    fn cset(items: &[&str]) -> BTreeSet<ClippyWarning> {
        items.iter().map(|s| cw(s)).collect()
    }

    fn cw(lint: &str) -> ClippyWarning {
        ClippyWarning {
            lint: lint.to_string(),
            package: "pkg".into(),
            file: "src/a.rs".into(),
            message: "m".into(),
        }
    }

    fn check(desc: &str, run: &str, passed: bool, exit: Option<i32>) -> CheckRun {
        CheckRun {
            desc: desc.to_string(),
            run: run.to_string(),
            cwd: None,
            passed,
            exit_code: exit,
            stdout: String::new(),
            stderr: String::new(),
        }
    }

    fn paths(items: &[&str]) -> Vec<PathBuf> {
        items.iter().map(PathBuf::from).collect()
    }

    // --- gate 1: checks pass ---

    #[test]
    fn checks_pass_when_all_green() {
        let g = gate_checks_pass(&[
            check("a", "cargo test a", true, Some(0)),
            check("b", "cargo test b", true, Some(0)),
        ]);
        assert!(g.passed);
        assert!(g.violations.is_empty());
    }

    #[test]
    fn checks_fail_reports_each_failure() {
        let g = gate_checks_pass(&[
            check("a", "cargo test a", true, Some(0)),
            check("b", "cargo test b", false, Some(101)),
        ]);
        assert!(!g.passed);
        assert_eq!(g.violations.len(), 1);
        assert_eq!(
            g.violations[0],
            Violation::CheckFailed {
                desc: "b".into(),
                run: "cargo test b".into(),
                exit_code: Some(101),
            }
        );
    }

    #[test]
    fn empty_checks_pass_vacuously() {
        // No checks defined ⇒ nothing to fail. (The plan validator, not the
        // floor, enforces "≥1 check per chunk"; the gate reports what it's given.)
        assert!(gate_checks_pass(&[]).passed);
    }

    // --- gate 2: regression ---

    #[test]
    fn no_regression_on_clean_pass() {
        let base = TestSnapshot {
            passed: tset(&["a", "b"]),
            ..Default::default()
        };
        let cur = TestSnapshot {
            passed: tset(&["a", "b"]),
            ..Default::default()
        };
        assert!(gate_no_regression(&base, &cur).passed);
    }

    #[test]
    fn regression_when_baseline_pass_now_fails() {
        let base = TestSnapshot {
            passed: tset(&["a", "b"]),
            ..Default::default()
        };
        let cur = TestSnapshot {
            passed: tset(&["a"]),
            failed: tset(&["b"]),
            ..Default::default()
        };
        let g = gate_no_regression(&base, &cur);
        assert!(!g.passed);
        assert_eq!(
            g.violations,
            vec![Violation::TestRegressed { test: tid("b") }]
        );
    }

    #[test]
    fn new_test_failing_is_not_a_regression() {
        // `c` never passed at baseline, so its failure is not a *regression*.
        let base = TestSnapshot {
            passed: tset(&["a"]),
            ..Default::default()
        };
        let cur = TestSnapshot {
            passed: tset(&["a"]),
            failed: tset(&["c"]),
            ..Default::default()
        };
        assert!(gate_no_regression(&base, &cur).passed);
    }

    // --- gate 3: clippy ---

    #[test]
    fn no_new_clippy_when_subset() {
        let base = ClippySnapshot {
            warnings: cset(&["w1", "w2"]),
        };
        let cur = ClippySnapshot {
            warnings: cset(&["w1"]), // fixed one, added none
        };
        assert!(gate_no_new_clippy(&base, &cur).passed);
    }

    #[test]
    fn new_clippy_warning_fails() {
        let base = ClippySnapshot {
            warnings: cset(&["w1"]),
        };
        let cur = ClippySnapshot {
            warnings: cset(&["w1", "w2"]),
        };
        let g = gate_no_new_clippy(&base, &cur);
        assert!(!g.passed);
        assert_eq!(
            g.violations,
            vec![Violation::NewClippyWarning { warning: cw("w2") }]
        );
    }

    // --- gate 4: test gaming ---

    #[test]
    fn no_gaming_on_clean_or_expanded_suite() {
        let base = TestSnapshot {
            passed: tset(&["a", "b"]),
            ..Default::default()
        };
        let cur = TestSnapshot {
            passed: tset(&["a", "b", "c"]), // added a test, dropped none
            ..Default::default()
        };
        let mut assertions = BTreeMap::new();
        assertions.insert(PathBuf::from("src/a.rs"), 3);
        let g = gate_no_test_gaming(&base, &cur, &assertions, &assertions);
        assert!(g.passed, "{:?}", g.violations);
    }

    #[test]
    fn detects_count_drop_and_vanished_test() {
        let base = TestSnapshot {
            passed: tset(&["a", "b"]),
            ..Default::default()
        };
        let cur = TestSnapshot {
            passed: tset(&["a"]), // b removed
            ..Default::default()
        };
        let g = gate_no_test_gaming(&base, &cur, &BTreeMap::new(), &BTreeMap::new());
        assert!(!g.passed);
        assert!(g.violations.contains(&Violation::TestCountDropped {
            baseline: 2,
            current: 1
        }));
        assert!(g
            .violations
            .contains(&Violation::MissingBaselineTest { test: tid("b") }));
    }

    #[test]
    fn detects_newly_ignored_baseline_pass() {
        let base = TestSnapshot {
            passed: tset(&["a", "b"]),
            ..Default::default()
        };
        let cur = TestSnapshot {
            passed: tset(&["a"]),
            ignored: tset(&["b"]), // b was passing, now ignored
            ..Default::default()
        };
        let g = gate_no_test_gaming(&base, &cur, &BTreeMap::new(), &BTreeMap::new());
        assert!(!g.passed);
        assert!(g
            .violations
            .contains(&Violation::NewlyIgnoredTest { test: tid("b") }));
        // Count did not drop (b still counted, just ignored), and b is still
        // present, so neither of those signals fire.
        assert!(!g
            .violations
            .iter()
            .any(|v| matches!(v, Violation::TestCountDropped { .. })));
        assert!(!g
            .violations
            .iter()
            .any(|v| matches!(v, Violation::MissingBaselineTest { .. })));
    }

    #[test]
    fn detects_was_failing_now_ignored() {
        // A failing test turned into an ignored test hides an unresolved
        // failure — that is also "newly ignored".
        let base = TestSnapshot {
            failed: tset(&["flaky"]),
            ..Default::default()
        };
        let cur = TestSnapshot {
            ignored: tset(&["flaky"]),
            ..Default::default()
        };
        let g = gate_no_test_gaming(&base, &cur, &BTreeMap::new(), &BTreeMap::new());
        assert!(g
            .violations
            .contains(&Violation::NewlyIgnoredTest { test: tid("flaky") }));
    }

    #[test]
    fn brand_new_ignored_test_is_not_gaming() {
        // A test that never existed at baseline and is added as ignored is not
        // a gaming signal (nothing was hidden).
        let base = TestSnapshot {
            passed: tset(&["a"]),
            ..Default::default()
        };
        let cur = TestSnapshot {
            passed: tset(&["a"]),
            ignored: tset(&["new_wip"]),
            ..Default::default()
        };
        let g = gate_no_test_gaming(&base, &cur, &BTreeMap::new(), &BTreeMap::new());
        assert!(!g
            .violations
            .iter()
            .any(|v| matches!(v, Violation::NewlyIgnoredTest { .. })));
    }

    #[test]
    fn detects_assertion_density_regression() {
        let ts = TestSnapshot {
            passed: tset(&["a"]),
            ..Default::default()
        };
        let mut base = BTreeMap::new();
        base.insert(PathBuf::from("src/a.rs"), 5);
        let mut cur = BTreeMap::new();
        cur.insert(PathBuf::from("src/a.rs"), 2); // gutted assertions
        let g = gate_no_test_gaming(&ts, &ts, &base, &cur);
        assert!(!g.passed);
        assert!(g
            .violations
            .contains(&Violation::AssertionDensityRegressed {
                file: PathBuf::from("src/a.rs"),
                baseline: 5,
                current: 2,
            }));
    }

    #[test]
    fn added_assertions_and_new_files_do_not_regress() {
        let ts = TestSnapshot {
            passed: tset(&["a"]),
            ..Default::default()
        };
        let mut base = BTreeMap::new();
        base.insert(PathBuf::from("src/a.rs"), 2);
        let mut cur = BTreeMap::new();
        cur.insert(PathBuf::from("src/a.rs"), 4); // more assertions
        cur.insert(PathBuf::from("src/new.rs"), 1); // brand-new file
        assert!(gate_no_test_gaming(&ts, &ts, &base, &cur).passed);
    }

    // --- gate 5: file scope ---

    #[test]
    fn file_scope_passes_within_declared() {
        let declared = paths(&["src/a.rs", "src/a_test.rs"]);
        let changed = paths(&["src/a.rs"]);
        assert!(gate_file_scope(&declared, &changed, 0).passed);
    }

    #[test]
    fn file_scope_fails_out_of_scope_beyond_slack() {
        let declared = paths(&["src/a.rs"]);
        let changed = paths(&["src/a.rs", "src/secret.rs", "Cargo.toml"]);
        let g = gate_file_scope(&declared, &changed, 0);
        assert!(!g.passed);
        assert_eq!(g.violations.len(), 2);
        assert!(g.violations.contains(&Violation::OutOfScopeFile {
            file: PathBuf::from("src/secret.rs")
        }));
        assert!(g.violations.contains(&Violation::OutOfScopeFile {
            file: PathBuf::from("Cargo.toml")
        }));
    }

    #[test]
    fn file_scope_dedups_repeated_paths() {
        // The same out-of-scope path listed twice is one violation, and does not
        // consume the slack budget twice.
        let declared = paths(&["src/a.rs"]);
        let changed = paths(&["src/dup.rs", "src/dup.rs"]);
        let g = gate_file_scope(&declared, &changed, 1);
        assert!(g.passed, "one distinct out-of-scope file fits slack 1");
        assert!(g.violations.is_empty());
    }

    #[test]
    fn file_scope_tolerates_within_slack() {
        let declared = paths(&["src/a.rs"]);
        let changed = paths(&["src/a.rs", "src/extra.rs"]);
        // One out-of-scope file, slack 1 ⇒ pass, no violations raised.
        let g = gate_file_scope(&declared, &changed, 1);
        assert!(g.passed);
        assert!(g.violations.is_empty());
    }

    // --- gate 5: enumeration integrity (F7) ---

    /// A `TestSnapshot` carrying only an enumerated-target set (canonical
    /// `package/target_kind/target` strings), no per-test outcomes.
    fn tsnap_targets(items: &[&str]) -> TestSnapshot {
        TestSnapshot {
            targets: items.iter().map(ToString::to_string).collect(),
            ..Default::default()
        }
    }

    #[test]
    fn enumeration_superset_passes_when_targets_held_or_grew() {
        let base = tsnap_targets(&["p/lib/p", "p/test/e2e"]);
        // Same set → superset (equal) holds.
        assert!(gate_enumeration_superset(&base, &base).passed);
        // A new target added at the tip is fine (superset still holds).
        let grew = tsnap_targets(&["p/lib/p", "p/test/e2e", "p/test/new"]);
        let g = gate_enumeration_superset(&base, &grew);
        assert!(g.passed, "{g:#?}");
        assert!(g.violations.is_empty());
    }

    #[test]
    fn enumeration_shrink_fails_closed() {
        // The fork enumerated two harnesses; the tip enumerates only one — the
        // integration-test binary vanished (a narrowing alias / --exclude /
        // harness=false / empty build). That must fail closed: the missing
        // target's tests can no longer regress or count-drop, so the other gates
        // are blind to them.
        let base = tsnap_targets(&["p/lib/p", "p/test/e2e"]);
        let tip = tsnap_targets(&["p/lib/p"]);
        let g = gate_enumeration_superset(&base, &tip);
        assert!(!g.passed);
        assert_eq!(
            g.violations,
            vec![Violation::EnumerationShrank {
                target: "p/test/e2e".to_string()
            }]
        );
        // And it fails the aggregate floor even when every other gate is green.
        let base_run = RunSnapshot {
            tests: base,
            ..Default::default()
        };
        let tip_run = RunSnapshot {
            tests: tip,
            ..Default::default()
        };
        let declared = paths(&["src/a.rs"]);
        let assertions = BTreeMap::new();
        let inputs = FloorInputs {
            baseline: &base_run,
            current: &tip_run,
            check_results: &[check("c", "cargo test", true, Some(0))],
            declared_files: &declared,
            changed_files: &declared,
            baseline_assertions: &assertions,
            current_assertions: &assertions,
            file_scope_slack: 0,
        };
        let verdict = evaluate_floor(&inputs);
        assert!(!verdict.passed());
        assert!(verdict
            .failed_gates()
            .any(|g| g.gate == GateKind::EnumerationIntegrity));
    }

    // --- aggregate ---

    #[test]
    fn evaluate_floor_is_green_on_a_clean_run() {
        let base = RunSnapshot {
            tests: TestSnapshot {
                passed: tset(&["a"]),
                ..Default::default()
            },
            clippy: ClippySnapshot {
                warnings: cset(&["w1"]),
            },
            coverage: None,
        };
        let cur = base.clone();
        let declared = paths(&["src/a.rs"]);
        let changed = paths(&["src/a.rs"]);
        let assertions = BTreeMap::new();
        let inputs = FloorInputs {
            baseline: &base,
            current: &cur,
            check_results: &[check("c", "cargo test", true, Some(0))],
            declared_files: &declared,
            changed_files: &changed,
            baseline_assertions: &assertions,
            current_assertions: &assertions,
            file_scope_slack: 0,
        };
        let verdict = evaluate_floor(&inputs);
        assert!(verdict.passed(), "{verdict:#?}");
        assert_eq!(verdict.gates.len(), 6);
        assert_eq!(verdict.violations().count(), 0);
    }

    #[test]
    fn evaluate_floor_aggregates_multiple_gate_failures() {
        let base = RunSnapshot {
            tests: TestSnapshot {
                passed: tset(&["a", "b"]),
                ..Default::default()
            },
            clippy: ClippySnapshot::default(),
            coverage: None,
        };
        let cur = RunSnapshot {
            tests: TestSnapshot {
                passed: tset(&["a"]),
                failed: tset(&["b"]), // regression
                ..Default::default()
            },
            clippy: ClippySnapshot {
                warnings: cset(&["new-warn"]), // new clippy
            },
            coverage: None,
        };
        let declared = paths(&["src/a.rs"]);
        let changed = paths(&["src/a.rs", "src/out.rs"]); // out of scope
        let assertions = BTreeMap::new();
        let inputs = FloorInputs {
            baseline: &base,
            current: &cur,
            check_results: &[check("c", "cargo test", false, Some(101))], // check fail
            declared_files: &declared,
            changed_files: &changed,
            baseline_assertions: &assertions,
            current_assertions: &assertions,
            file_scope_slack: 0,
        };
        let verdict = evaluate_floor(&inputs);
        assert!(!verdict.passed());
        // checks, regression, clippy, file-scope all fail (4 gates).
        assert_eq!(verdict.failed_gates().count(), 4);
        // no-test-gaming still passes: b failing still counts + is present.
        assert!(
            verdict
                .gates
                .iter()
                .find(|g| g.gate == GateKind::NoTestGaming)
                .unwrap()
                .passed
        );
    }
}