monochromatic-git-policy-cli 0.1.0

Repository-owned Git policy wrapper: forwards Git commands and checks commits against configured policies.
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
//! What:
//!  Stage order,
//!  trigger and filter skipping,
//!  severities,
//!  stopping,
//!  and the three ways
//!       a pass can fail to decide.
//! Why:
//!  Each rule here is a way a policy could silently not run or a blocked command could
//!      be let through:
//!  a wrong trigger set,
//!  an ignored severity,
//!  a swallowed failure.
//!
//! In TS you'd write (pseudocode):
//! ```ts
//! // expect((await runPolicyStage({ ... })).events.map(e => e.policyId)).toEqual(['require-root']);
//! ```

/// The stage under test and the types it reads and produces.
use super::{
    BLOCKED_EXIT_CODE, PolicyChecks, PolicyFinding, PolicyOutcome, StageEnd, StageRequest,
    StageResult, Unavailable, any_policy_applies, pass_exit_code, run_policy_stage,
};
use crate::config_schema::PolicyConfig;
use crate::diagnostics::EngineFailureCode;
/// The event form of a pathname.
use crate::event_path::EventPath;
use crate::policy_events::{FindingEvent, FindingLocation, PolicyEvent};
use crate::policy_registry::{POLICY_REGISTRY, PolicyId, Severity, policy_descriptor};
use crate::policy_trigger::Trigger;
use crate::wrapper_controls::{Controls, no_controls};

/// A provider that answers from a script and records every check it was asked for.
struct Scripted {
    /// Outcomes by policy;
    ///  a policy without an entry finds nothing.
    outcomes: Vec<(PolicyId, PolicyOutcome)>,
    /// Every check in call order.
    calls: Vec<(PolicyId, Trigger)>,
}

impl PolicyChecks for Scripted {
    fn check(&mut self, policy: PolicyId, trigger: Trigger) -> PolicyOutcome {
        self.calls.push((policy, trigger));
        for (scripted, outcome) in &self.outcomes {
            if *scripted == policy {
                return outcome.clone();
            }
        }
        return PolicyOutcome::Findings(Vec::<PolicyFinding>::new());
    }
}

/// A provider with the given script and no calls yet.
fn scripted(outcomes: Vec<(PolicyId, PolicyOutcome)>) -> Scripted {
    return Scripted {
        outcomes,
        calls: Vec::<(PolicyId, Trigger)>::new(),
    };
}

/// One finding with only its required fields.
fn finding(code: &'static str) -> PolicyFinding {
    return PolicyFinding {
        code,
        message: format!("message of {code}"),
        path: None,
        location: None,
        fix_available: false,
    };
}

/// The outcome "found exactly this one thing".
fn found(code: &'static str) -> PolicyOutcome {
    return PolicyOutcome::Findings(vec![finding(code)]);
}

/// Every shipped policy in registry order.
fn every_policy() -> Vec<PolicyId> {
    let mut ids: Vec<PolicyId> = Vec::<PolicyId>::new();
    for descriptor in POLICY_REGISTRY {
        ids.push(descriptor.id);
    }
    return ids;
}

/// The settings of a repository whose configuration names all four optional policies at
/// the severity the incumbent declares as their default.
fn all_listed() -> PolicyConfig {
    let mut config: PolicyConfig = PolicyConfig::defaults();
    for setting in &mut config.settings {
        setting.severity = policy_descriptor(setting.id).default_severity;
    }
    return config;
}

/// A copy of `config` with one policy's severity replaced.
fn with_severity(config: &PolicyConfig, policy: PolicyId, severity: Severity) -> PolicyConfig {
    let mut changed: PolicyConfig = config.clone();
    for setting in &mut changed.settings {
        if setting.id == policy {
            setting.severity = severity;
        }
    }
    return changed;
}

/// Run every shipped policy for one trigger and return the result with the recorded calls.
fn run(
    trigger: Trigger,
    config: &PolicyConfig,
    controls: &Controls,
    selected: &[PolicyId],
    outcomes: Vec<(PolicyId, PolicyOutcome)>,
) -> (StageResult, Vec<PolicyId>) {
    let mut checks: Scripted = scripted(outcomes);
    let request: StageRequest = StageRequest {
        trigger,
        config: config.clone(),
        controls: controls.clone(),
        selected: selected.to_vec(),
    };
    let result: StageResult = run_policy_stage(&request, every_policy().as_slice(), &mut checks);
    let mut called: Vec<PolicyId> = Vec::<PolicyId>::new();
    for (policy, asked) in &checks.calls {
        assert_eq!(*asked, trigger, "a check is asked for the stage's trigger");
        called.push(*policy);
    }
    return (result, called);
}

/// The finding event the stage must build from `finding(code)`.
fn event(
    trigger: Trigger,
    policy: PolicyId,
    severity: Severity,
    code: &'static str,
) -> PolicyEvent {
    return PolicyEvent::Finding(FindingEvent {
        trigger,
        policy,
        severity,
        code,
        message: format!("message of {code}"),
        path: None,
        location: None,
        fix_available: false,
    });
}

/// A policy runs only for the triggers it declares,
///  in the order it was given.
#[test]
fn policies_run_in_order_for_their_triggers() {
    let configured: PolicyConfig = all_listed();
    let none: Controls = no_controls();
    let (pre_forward, called) = run(Trigger::PreForward, &configured, &none, &[], vec![]);
    assert_eq!(called, every_policy());
    assert_eq!(pre_forward.end, StageEnd::Completed);
    assert_eq!(pre_forward.events, Vec::<PolicyEvent>::new());
    let (_, direct_check) = run(Trigger::DirectCheck, &configured, &none, &[], vec![]);
    assert_eq!(
        direct_check,
        [
            PolicyId::RequireRoot,
            PolicyId::FinalNewline,
            PolicyId::MarkdownAutofix,
            PolicyId::ForbiddenRootContext,
            PolicyId::DependentVersionBump,
            PolicyId::ForbiddenStrings,
        ]
    );
    let (_, direct_fix) = run(Trigger::DirectFix, &configured, &none, &[], vec![]);
    assert_eq!(
        direct_fix,
        [
            PolicyId::FinalNewline,
            PolicyId::MarkdownAutofix,
            PolicyId::DependentVersionBump,
        ]
    );
    // The order is the caller's list, not the registry's.
    let mut checks: Scripted = scripted(vec![]);
    let request: StageRequest = StageRequest {
        trigger: Trigger::PreForward,
        config: configured,
        controls: none,
        selected: Vec::<PolicyId>::new(),
    };
    run_policy_stage(
        &request,
        &[PolicyId::AddExplicit, PolicyId::RequireRoot],
        &mut checks,
    );
    assert_eq!(
        checks.calls,
        [
            (PolicyId::AddExplicit, Trigger::PreForward),
            (PolicyId::RequireRoot, Trigger::PreForward)
        ]
    );
}

/// A policy that is off,
///  escaped or outside the direct-command filter is never asked.
#[test]
fn off_escaped_and_unselected_policies_are_skipped() {
    let none: Controls = no_controls();
    // Until the configuration names them, the four optional policies are off.
    let (_, unlisted) = run(
        Trigger::PreForward,
        &PolicyConfig::defaults(),
        &none,
        &[],
        vec![],
    );
    assert_eq!(
        unlisted,
        [
            PolicyId::RequireRoot,
            PolicyId::LinkedWorktreeOnly,
            PolicyId::BranchWorktreeOnly,
            PolicyId::AddExplicit,
            PolicyId::FinalNewline,
        ]
    );
    let off: PolicyConfig = with_severity(
        &PolicyConfig::defaults(),
        PolicyId::RequireRoot,
        Severity::Off,
    );
    let (_, without_root) = run(Trigger::PreForward, &off, &none, &[], vec![]);
    assert_eq!(without_root.first(), Some(&PolicyId::LinkedWorktreeOnly));
    assert_eq!(without_root.len(), 4);
    let mut escaped: Controls = no_controls();
    escaped.escaped = vec![PolicyId::AddExplicit, PolicyId::RequireRoot];
    let (_, after_escape) = run(
        Trigger::PreForward,
        &PolicyConfig::defaults(),
        &escaped,
        &[],
        vec![],
    );
    assert_eq!(
        after_escape,
        [
            PolicyId::LinkedWorktreeOnly,
            PolicyId::BranchWorktreeOnly,
            PolicyId::FinalNewline,
        ]
    );
    let (_, selected) = run(
        Trigger::DirectCheck,
        &all_listed(),
        &none,
        &[PolicyId::ForbiddenStrings, PolicyId::RequireRoot],
        vec![],
    );
    assert_eq!(
        selected,
        [PolicyId::RequireRoot, PolicyId::ForbiddenStrings]
    );
    // A selected policy that does not declare the trigger is still skipped.
    let (_, wrong_trigger) = run(
        Trigger::DirectFix,
        &all_listed(),
        &none,
        &[PolicyId::RequireRoot],
        vec![],
    );
    assert_eq!(wrong_trigger, Vec::<PolicyId>::new());
}

/// Without keep-going the first error finding ends the pass;
///  with it,
///  later policies still run.
#[test]
fn first_error_stops_unless_keep_going() {
    let config: PolicyConfig = PolicyConfig::defaults();
    let script: Vec<(PolicyId, PolicyOutcome)> = vec![
        (PolicyId::RequireRoot, found("not-at-root")),
        (PolicyId::BranchWorktreeOnly, found("creates")),
    ];
    let (stopped, called) = run(
        Trigger::PreForward,
        &config,
        &no_controls(),
        &[],
        script.clone(),
    );
    assert_eq!(stopped.end, StageEnd::Stopped);
    assert_eq!(called, [PolicyId::RequireRoot]);
    assert_eq!(
        stopped.events,
        [event(
            Trigger::PreForward,
            PolicyId::RequireRoot,
            Severity::Error,
            "not-at-root"
        )]
    );
    assert_eq!(
        pass_exit_code(stopped.events.as_slice(), stopped.end),
        BLOCKED_EXIT_CODE
    );
    let mut keep_going: Controls = no_controls();
    keep_going.keep_going = true;
    let (continued, all_called) = run(Trigger::PreForward, &config, &keep_going, &[], script);
    assert_eq!(continued.end, StageEnd::Completed);
    assert_eq!(all_called.len(), 5);
    assert_eq!(
        continued.events,
        [
            event(
                Trigger::PreForward,
                PolicyId::RequireRoot,
                Severity::Error,
                "not-at-root"
            ),
            event(
                Trigger::PreForward,
                PolicyId::BranchWorktreeOnly,
                Severity::Error,
                "creates"
            ),
        ]
    );
    assert_eq!(
        pass_exit_code(continued.events.as_slice(), continued.end),
        BLOCKED_EXIT_CODE
    );
}

/// A warning finding never stops the pass and never blocks;
///  the event carries the configured severity.
#[test]
fn warning_findings_do_not_stop_or_block() {
    let config: PolicyConfig = with_severity(
        &PolicyConfig::defaults(),
        PolicyId::BranchWorktreeOnly,
        Severity::Warn,
    );
    let (result, called) = run(
        Trigger::PreForward,
        &config,
        &no_controls(),
        &[],
        vec![
            (PolicyId::BranchWorktreeOnly, found("creates")),
            (PolicyId::FinalNewline, found("missing")),
        ],
    );
    assert_eq!(result.end, StageEnd::Completed);
    assert_eq!(called.len(), 5);
    // Both policies are warn-safe, so no configuration warning follows their findings.
    assert_eq!(
        result.events,
        [
            event(
                Trigger::PreForward,
                PolicyId::BranchWorktreeOnly,
                Severity::Warn,
                "creates"
            ),
            event(
                Trigger::PreForward,
                PolicyId::FinalNewline,
                Severity::Warn,
                "missing"
            ),
        ]
    );
    assert_eq!(pass_exit_code(result.events.as_slice(), result.end), 0);
}

/// `warn` on a policy it does not protect is reported after that policy's findings,
///  also when it found nothing.
#[test]
fn unsafe_warn_is_reported_even_when_clean() {
    let config: PolicyConfig = with_severity(
        &PolicyConfig::defaults(),
        PolicyId::AddExplicit,
        Severity::Warn,
    );
    let warning: PolicyEvent = PolicyEvent::WarnUnsafe {
        trigger: Trigger::PreForward,
        policy: PolicyId::AddExplicit,
    };
    let (clean, _) = run(Trigger::PreForward, &config, &no_controls(), &[], vec![]);
    assert_eq!(clean.events.as_slice(), std::slice::from_ref(&warning));
    assert_eq!(clean.end, StageEnd::Completed);
    let (dirty, _) = run(
        Trigger::PreForward,
        &config,
        &no_controls(),
        &[],
        vec![(PolicyId::AddExplicit, found("bulk"))],
    );
    assert_eq!(
        dirty.events,
        [
            event(
                Trigger::PreForward,
                PolicyId::AddExplicit,
                Severity::Warn,
                "bulk"
            ),
            warning,
        ]
    );
    assert_eq!(pass_exit_code(dirty.events.as_slice(), dirty.end), 0);
    // At `error` the same policy earns no warning.
    let (error, _) = run(
        Trigger::PreForward,
        &PolicyConfig::defaults(),
        &no_controls(),
        &[],
        vec![],
    );
    assert_eq!(error.events, Vec::<PolicyEvent>::new());
}

/// A finding's optional fields reach its event unchanged.
#[test]
fn finding_details_reach_the_event() {
    let detailed: PolicyFinding = PolicyFinding {
        code: "missing",
        message: String::from("no final newline"),
        path: Some(EventPath::from_git_bytes("a.txt".as_bytes())),
        location: Some(FindingLocation {
            byte_start: 4,
            byte_end: 5,
        }),
        fix_available: true,
    };
    let (result, _) = run(
        Trigger::DirectCheck,
        &PolicyConfig::defaults(),
        &no_controls(),
        &[],
        vec![(
            PolicyId::FinalNewline,
            PolicyOutcome::Findings(vec![detailed, finding("second")]),
        )],
    );
    assert_eq!(
        result.events,
        [
            PolicyEvent::Finding(FindingEvent {
                trigger: Trigger::DirectCheck,
                policy: PolicyId::FinalNewline,
                severity: Severity::Warn,
                code: "missing",
                message: String::from("no final newline"),
                path: Some(EventPath::from_git_bytes("a.txt".as_bytes())),
                location: Some(FindingLocation {
                    byte_start: 4,
                    byte_end: 5,
                }),
                fix_available: true,
            }),
            event(
                Trigger::DirectCheck,
                PolicyId::FinalNewline,
                Severity::Warn,
                "second"
            ),
        ]
    );
}

/// A policy that could not finish ends the pass with one engine failure naming trigger,
/// policy and the outcome's own cause,
///  for either cause.
#[test]
fn failed_check_ends_the_pass_with_an_engine_failure() {
    let mut keep_going: Controls = no_controls();
    keep_going.keep_going = true;
    for code in [
        EngineFailureCode::ContentUnavailable,
        EngineFailureCode::PolicyIncomplete,
    ] {
        let (result, called) = run(
            Trigger::PreForward,
            &PolicyConfig::defaults(),
            &keep_going,
            &[],
            vec![
                (PolicyId::RequireRoot, found("not-at-root")),
                (
                    PolicyId::LinkedWorktreeOnly,
                    PolicyOutcome::Failed {
                        code,
                        message: String::from("git could not be asked"),
                        path: None,
                    },
                ),
            ],
        );
        assert_eq!(result.end, StageEnd::Failed);
        assert_eq!(
            called,
            [PolicyId::RequireRoot, PolicyId::LinkedWorktreeOnly]
        );
        assert_eq!(
            result.events,
            [
                event(
                    Trigger::PreForward,
                    PolicyId::RequireRoot,
                    Severity::Error,
                    "not-at-root"
                ),
                PolicyEvent::EngineFailure {
                    code,
                    message: String::from("git could not be asked"),
                    trigger: Some(Trigger::PreForward),
                    policy: Some(PolicyId::LinkedWorktreeOnly),
                    path: None,
                },
            ]
        );
        // The failure decides the exit code even though an error finding precedes it.
        assert_eq!(pass_exit_code(result.events.as_slice(), result.end), 2);
    }
}

/// A policy that cannot be evaluated ends the pass as unavailable,
///  keeping earlier events and inventing none.
#[test]
fn unavailable_policy_ends_the_pass_without_a_clean_result() {
    let (result, called) = run(
        Trigger::PreForward,
        &with_severity(
            &PolicyConfig::defaults(),
            PolicyId::AddExplicit,
            Severity::Warn,
        ),
        &no_controls(),
        &[],
        vec![(
            PolicyId::FinalNewline,
            PolicyOutcome::Unavailable("candidate content"),
        )],
    );
    assert_eq!(
        result.end,
        StageEnd::Unavailable(Unavailable::Policy {
            policy: PolicyId::FinalNewline,
            needs: "candidate content",
        })
    );
    assert_eq!(called.len(), 5);
    assert_eq!(
        result.events,
        [PolicyEvent::WarnUnsafe {
            trigger: Trigger::PreForward,
            policy: PolicyId::AddExplicit,
        }]
    );
    assert_eq!(pass_exit_code(result.events.as_slice(), result.end), 2);
}

/// A manual-push request over the given settings,
///  controls and filter.
fn manual_push(config: &PolicyConfig, controls: &Controls, selected: &[PolicyId]) -> StageRequest {
    return StageRequest {
        trigger: Trigger::ManualPush,
        config: config.clone(),
        controls: controls.clone(),
        selected: selected.to_vec(),
    };
}

/// Applicability follows the same trigger,
///  filter,
///  escape and severity tests as the stage.
#[test]
fn applicability_matches_the_stage() {
    let built_ins: PolicyConfig = PolicyConfig::defaults();
    let none: Controls = no_controls();
    let all: Vec<PolicyId> = every_policy();
    let request: StageRequest = manual_push(&built_ins, &none, &[]);
    // Only `final-newline` declares manual push among the policies that run unlisted.
    assert!(any_policy_applies(&request, all.as_slice()));
    assert!(!any_policy_applies(
        &request,
        &[PolicyId::RequireRoot, PolicyId::AddExplicit]
    ));
    assert!(!any_policy_applies(&request, &[]));
    let off: PolicyConfig = with_severity(&built_ins, PolicyId::FinalNewline, Severity::Off);
    assert!(!any_policy_applies(
        &manual_push(&off, &none, &[]),
        all.as_slice()
    ));
    let mut escaped: Controls = no_controls();
    escaped.escaped = vec![PolicyId::FinalNewline];
    assert!(!any_policy_applies(
        &manual_push(&built_ins, &escaped, &[]),
        all.as_slice()
    ));
    assert!(!any_policy_applies(
        &manual_push(&built_ins, &none, &[PolicyId::RequireRoot]),
        all.as_slice()
    ));
    // Once listed, the scanner also declares manual push.
    let configured: PolicyConfig =
        with_severity(&all_listed(), PolicyId::FinalNewline, Severity::Off);
    assert!(any_policy_applies(
        &manual_push(&configured, &none, &[]),
        all.as_slice()
    ));
}

/// An error finding of `require-root`.
fn error_event() -> PolicyEvent {
    return event(
        Trigger::PreForward,
        PolicyId::RequireRoot,
        Severity::Error,
        "not-at-root",
    );
}

/// A warning finding of `final-newline`.
fn warning_event() -> PolicyEvent {
    return event(
        Trigger::PreForward,
        PolicyId::FinalNewline,
        Severity::Warn,
        "missing",
    );
}

/// The exit code is 2 for an undecided pass,
///  1 for a blocking event,
///  and 0 otherwise.
#[test]
fn exit_code_follows_ending_then_events() {
    let core: PolicyEvent = PolicyEvent::CoreFinding {
        core_id: "commit-only",
        code: "all-flag",
        message: String::from("m"),
    };
    assert_eq!(BLOCKED_EXIT_CODE, 1);
    assert_eq!(pass_exit_code(&[], StageEnd::Completed), 0);
    assert_eq!(pass_exit_code(&[warning_event()], StageEnd::Completed), 0);
    assert_eq!(
        pass_exit_code(&[warning_event(), error_event()], StageEnd::Completed),
        1
    );
    assert_eq!(pass_exit_code(&[error_event()], StageEnd::Stopped), 1);
    assert_eq!(
        pass_exit_code(&[warning_event(), core], StageEnd::Completed),
        1
    );
    assert_eq!(pass_exit_code(&[error_event()], StageEnd::Failed), 2);
    assert_eq!(
        pass_exit_code(
            &[error_event()],
            StageEnd::Unavailable(Unavailable::Lifecycle(Trigger::PostCommit))
        ),
        2
    );
    // A pending correction blocks even when every event is a warning.
    assert_eq!(pass_exit_code(&[warning_event()], StageEnd::Proposed), 1);
    assert_eq!(pass_exit_code(&[], StageEnd::Proposed), 1);
}

/// The finding `finding(code)` offering a fix.
fn fixable(code: &'static str) -> PolicyFinding {
    let mut offered: PolicyFinding = finding(code);
    offered.fix_available = true;
    return offered;
}

/// A policy that proposes a correction ends the stage after its own findings,
///  whatever
/// its severity and even under keep-going;
///  a finding without a fix does not.
#[test]
fn a_proposed_correction_ends_the_stage() {
    let mut keep_going: Controls = no_controls();
    keep_going.keep_going = true;
    for (severity, controls) in [
        (Severity::Warn, no_controls()),
        (Severity::Error, keep_going.clone()),
    ] {
        let config: PolicyConfig = with_severity(&all_listed(), PolicyId::FinalNewline, severity);
        let (result, called) = run(
            Trigger::DirectFix,
            &config,
            &controls,
            &[],
            vec![(
                PolicyId::FinalNewline,
                PolicyOutcome::Findings(vec![finding("plain"), fixable("fixed")]),
            )],
        );
        assert_eq!(called, vec![PolicyId::FinalNewline], "{severity:?}");
        assert_eq!(result.end, StageEnd::Proposed, "{severity:?}");
        let mut expected_fixed: PolicyEvent = event(
            Trigger::DirectFix,
            PolicyId::FinalNewline,
            severity,
            "fixed",
        );
        if let PolicyEvent::Finding(offered) = &mut expected_fixed {
            offered.fix_available = true;
        }
        assert_eq!(
            result.events,
            vec![
                event(
                    Trigger::DirectFix,
                    PolicyId::FinalNewline,
                    severity,
                    "plain"
                ),
                expected_fixed,
            ]
        );
    }
    // Without a fix the stage goes on to the next policy.
    let (plain, called) = run(
        Trigger::DirectFix,
        &all_listed(),
        &no_controls(),
        &[],
        vec![(PolicyId::FinalNewline, found("plain"))],
    );
    assert_eq!(plain.end, StageEnd::Completed);
    assert!(called.len() > 1, "{called:?}");
}