autumn-cli 0.10.0

CLI tool for the Autumn web framework
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
//! `autumn routes posture` — the review-time gate and the deploy-time proof.
//!
//! [`crate::routes_audit`] (issue #1604) proves *what* an app's security surface
//! is. This module answers the next question: *what did this change do to it,
//! and did a human agree to that?* — plus, at deploy time, *is the manifest in
//! this artifact the one they agreed to?* (issue #1624).
//!
//! Three commands, all pure functions of files on disk:
//!
//! ```text
//! autumn routes posture diff   --base B.json --head H.json   # the PR gate
//! autumn routes posture digest --manifest M.json             # the recorded number
//! autumn routes posture verify --manifest M.json --expect-digest D --repo o/r
//! ```
//!
//! The gate blocks only on *widening*: a new open route, a guard removed or
//! loosened, a classification downgraded. Narrowing and neutral changes
//! annotate and never block, and a pull request that moves nothing renders
//! nothing at all — a gate that cries wolf is a gate that gets turned off.
//!
//! See `docs/guide/posture-gate.md` and `docs/plans/2026-09-03-posture-gate.md`.

pub mod ack;
pub mod ceiling;
pub mod diff;
pub mod model;
pub mod render;
pub mod verify;

use ack::Acknowledgment;
use diff::Finding;
use model::{ManifestError, PostureManifest};
use render::Report;

/// Exit code when a widening posture change is unacknowledged.
pub const EXIT_BLOCKED: i32 = 1;
/// Exit code for a usage or I/O problem — distinct from "the gate blocked" so
/// CI can tell "your PR widens the surface" from "the tool could not run".
pub const EXIT_USAGE: i32 = 2;

/// Options for `autumn routes posture diff`.
#[derive(Debug, Clone)]
pub struct DiffOptions<'a> {
    /// Base (previously accepted) manifest.
    pub base: &'a str,
    /// Head (freshly built) manifest.
    pub head: &'a str,
    /// `markdown` (default), `text`, or `json`.
    pub format: &'a str,
    /// Also write the rendered report here.
    pub output: Option<&'a str>,
    /// Acknowledgment markers passed inline.
    pub acks: &'a [String],
    /// File of harvested pull-request text to scan for acknowledgment markers.
    pub ack_file: Option<&'a str>,
    /// Directory with one file per pull-request comment. The file boundary
    /// is the comment boundary, so no comment text can fake one.
    pub ack_dir: Option<&'a str>,
    /// Treat a missing base manifest as "no baseline yet" instead of an error.
    pub allow_missing_base: bool,
}

/// What a diff run concluded, before it is rendered or turned into an exit code.
#[derive(Debug)]
pub struct Evaluation {
    pub findings: Vec<Finding>,
    /// Digest of the widening findings. A bare marker must carry it.
    pub ack_digest: String,
    /// The text after the phrase in the line to paste.
    pub marker: String,
    /// Posture digest of the head manifest.
    pub head_posture_digest: String,
    /// The acknowledgment that matched, when one did.
    pub acknowledged: Option<Acknowledgment>,
    /// No base manifest was available.
    pub bootstrap: bool,
}

impl Evaluation {
    /// Whether this run blocks the pull request.
    #[must_use]
    pub fn blocked(&self) -> bool {
        !diff::widening(&self.findings).is_empty() && self.acknowledged.is_none()
    }

    /// The process exit code this evaluation implies.
    #[must_use]
    pub fn exit_code(&self) -> i32 {
        i32::from(self.blocked()) * EXIT_BLOCKED
    }

    fn report(&self) -> Report<'_> {
        Report {
            findings: &self.findings,
            ack_digest: self.ack_digest.clone(),
            marker: self.marker.clone(),
            head_posture_digest: self.head_posture_digest.clone(),
            acknowledged: self.acknowledged.clone(),
            bootstrap: self.bootstrap,
        }
    }
}

/// Compare two manifests and resolve any acknowledgment against the result.
///
/// `base` is `None` when the project has no accepted baseline yet: the first
/// run on a repository that just enabled the gate reports the posture it found
/// and blocks nothing, because there is no *change* to widen.
#[must_use]
pub fn evaluate(
    base: Option<&PostureManifest>,
    head: &PostureManifest,
    acks: &[Acknowledgment],
) -> Evaluation {
    let findings = base.map(|b| diff::diff(b, head)).unwrap_or_default();
    let widening = diff::widening(&findings);
    let ack_digest = ack::ack_digest(&widening);
    let cover = ceiling::cover(&widening, head);
    // Only a widening can be acknowledged. Resolving a marker against a clean
    // run would let a stale comment sit on the pull request claiming to have
    // approved something nobody proposed.
    let acknowledged = if widening.is_empty() {
        None
    } else {
        ack::matching(acks, &ack_digest, &cover).cloned()
    };
    let marker = cover.marker(&ack_digest);
    Evaluation {
        findings,
        ack_digest,
        marker,
        head_posture_digest: head.posture_digest(),
        acknowledged,
        bootstrap: base.is_none(),
    }
}

/// Render an evaluation in the requested format.
///
/// Unknown formats are a usage error rather than a silent fallback: a CI job
/// that typos `--format markdwon` must not post a plain-text report and call it
/// a success.
pub fn render(evaluation: &Evaluation, format: &str) -> Result<String, String> {
    let report = evaluation.report();
    match format {
        "markdown" | "md" => Ok(render::markdown(&report)),
        "text" => Ok(render::text(&report)),
        "json" => Ok(render::json(&report)),
        other => Err(format!(
            "unknown --format `{other}` (expected `markdown`, `text`, or `json`)"
        )),
    }
}

/// Collect acknowledgments from `--ack`, `--ack-file` and `--ack-dir`.
fn harvested_acks(opts: &DiffOptions<'_>) -> Result<Vec<Acknowledgment>, String> {
    let mut acks = Vec::new();
    for ack in opts.acks {
        // An inline `--ack <digest>` is the phrase, without the ceremony of
        // typing it: normalize it into a marker line so there is exactly one
        // parser for every entry point.
        acks.extend(ack::parse_comment(&format!(
            "{} {}",
            ack::ACK_PHRASE,
            ack.trim()
        )));
    }
    if let Some(path) = opts.ack_file {
        let harvested = std::fs::read_to_string(path)
            .map_err(|e| format!("cannot read acknowledgment file {path}: {e}"))?;
        acks.extend(ack::parse_acks(&harvested));
    }
    if let Some(dir) = opts.ack_dir {
        let read_error =
            |e: std::io::Error| format!("cannot read acknowledgment directory {dir}: {e}");
        let mut files = Vec::new();
        for entry in std::fs::read_dir(dir).map_err(read_error)? {
            let entry = entry.map_err(read_error)?;
            if entry.file_type().map_err(read_error)?.is_file() {
                files.push(entry.path());
            }
        }
        files.sort();
        for file in files {
            let bytes = std::fs::read(&file)
                .map_err(|e| format!("cannot read acknowledgment file {}: {e}", file.display()))?;
            acks.extend(ack::parse_comment(&String::from_utf8_lossy(&bytes)));
        }
    }
    Ok(acks)
}

/// `autumn routes posture diff`.
#[must_use]
pub fn run_diff(opts: &DiffOptions<'_>) -> i32 {
    let head = match PostureManifest::read(opts.head) {
        Ok(m) => m,
        Err(e) => return fail(&e.to_string()),
    };
    let base = match PostureManifest::read(opts.base) {
        Ok(m) => Some(m),
        // Only a genuinely absent file bootstraps. A base path that exists but
        // cannot be read — a directory, a permissions problem, an interrupted
        // `git show` — is a broken run, and reporting it as the benign
        // "no baseline yet" case would disarm the gate for that run.
        Err(ManifestError::Io { ref source, .. })
            if opts.allow_missing_base && source.kind() == std::io::ErrorKind::NotFound =>
        {
            None
        }
        Err(e) => return fail(&e.to_string()),
    };
    let acks = match harvested_acks(opts) {
        Ok(a) => a,
        Err(e) => return fail(&e),
    };

    // A head manifest with no routes at all, diffed against a base that had
    // some, scores as a clean surface-*reducing* change — so a partial or
    // failed audit that still wrote a well-formed file would sail through.
    // That is a broken run, not a narrowing.
    if let Some(base_manifest) = &base
        && !base_manifest.dimensions.routes.entries.is_empty()
        && head.dimensions.routes.entries.is_empty()
    {
        return fail(&format!(
            "{} lists no routes at all while {} lists {} \u{2014} refusing to score that as a \
             narrowing. Rebuild the manifest with `autumn routes audit --manifest {}` and \
             the build flags of the base manifest.",
            opts.head,
            opts.base,
            base_manifest.dimensions.routes.entries.len(),
            opts.head
        ));
    }

    let evaluation = evaluate(base.as_ref(), &head, &acks);
    let rendered = match render(&evaluation, opts.format) {
        Ok(r) => r,
        Err(e) => return fail(&e),
    };

    if let Some(path) = opts.output
        && let Err(e) = std::fs::write(path, &rendered)
    {
        return fail(&format!("cannot write report to {path}: {e}"));
    }
    if !rendered.is_empty() {
        println!("{rendered}");
    }

    if evaluation.blocked() {
        eprintln!(
            "\n\u{2717} security posture widened and is not acknowledged.\n  \
             Acknowledge it with this line \u{2014} as a pull-request comment, or \
             locally as `--ack '<text after the phrase>'`:\n\n      {} {}\n",
            ack::ACK_PHRASE,
            evaluation.marker
        );
    }
    evaluation.exit_code()
}

/// `autumn routes posture digest`.
#[must_use]
pub fn run_digest(manifest: &str, format: &str) -> i32 {
    let digest = match verify::manifest_digest(manifest) {
        Ok(d) => d,
        Err(e) => return fail(&e.to_string()),
    };
    match format {
        "text" => println!("{digest}"),
        "json" => println!(
            "{}",
            serde_json::json!({ "manifest": manifest, "posture_digest": digest })
        ),
        other => {
            return fail(&format!(
                "unknown --format `{other}` (expected `text` or `json`)"
            ));
        }
    }
    0
}

/// `autumn routes posture verify`.
#[must_use]
pub fn run_verify(opts: &verify::VerifyOptions<'_>) -> i32 {
    let report = match verify::verify_with(opts, &verify::GhAttestationVerifier) {
        Ok(r) => r,
        Err(e) => return fail(&e.to_string()),
    };
    println!("\u{1F342} autumn routes posture verify\n");
    println!("  manifest        {}", report.manifest);
    println!("  posture digest  {}", report.posture_digest);
    for check in &report.checks {
        let mark = if check.waived {
            "\u{26A0}"
        } else if check.passed {
            "\u{2713}"
        } else {
            "\u{2717}"
        };
        println!("  {mark} {:<22} {}", check.name, check.detail);
    }
    if report.passed() { 0 } else { EXIT_BLOCKED }
}

/// Print a usage/I/O failure and hand back the exit code for one.
fn fail(message: &str) -> i32 {
    eprintln!("\u{2717} {message}");
    EXIT_USAGE
}

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

    fn parse(json: &str) -> PostureManifest {
        PostureManifest::parse(json, "test.json").expect("fixture parses")
    }

    /// A manifest document; `build` is spliced in before `dimensions`.
    fn manifest_json(routes: &str, build: &str) -> String {
        format!(
            r#"{{"schema_version":5,{build}"dimensions":{{
                 "routes":{{"provenance":"provable","source":"m","entries":[{routes}]}}
               }},"excluded":[]}}"#
        )
    }

    fn manifest(routes: &str) -> PostureManifest {
        parse(&format!(
            r#"{{"schema_version":3,"dimensions":{{
                 "routes":{{"provenance":"provable","source":"m","entries":[{routes}]}},
                 "csrf":{{"provenance":"declared","source":"c","exempt_paths":[],"entries":[]}},
                 "security_headers":{{"provenance":"declared","source":"c","entries":[]}},
                 "authorization_policies":{{"provenance":"provable","source":"m","runtime_caveat":"x","entries":[]}}
               }},"excluded":[]}}"#
        ))
    }

    fn route(path: &str, classification: &str, roles: &[&str]) -> String {
        let roles = roles
            .iter()
            .map(|r| format!("\"{r}\""))
            .collect::<Vec<_>>()
            .join(",");
        format!(
            r#"{{"path":"{path}","method":"GET","name":"h","classification":"{classification}",
                 "roles":[{roles}],"scopes":[],"policy":false,"source":"user","provenance":"provable"}}"#
        )
    }

    #[test]
    fn an_unchanged_posture_neither_blocks_nor_says_anything() {
        let base = manifest(&route("/admin", "gated", &["admin"]));
        let head = manifest(&route("/admin", "gated", &["admin"]));
        let e = evaluate(Some(&base), &head, &[]);
        assert!(!e.blocked());
        assert_eq!(e.exit_code(), 0);
        assert!(e.findings.is_empty());
        assert_eq!(render(&e, "markdown").unwrap(), "");
    }

    #[test]
    fn a_widening_blocks_until_the_matching_marker_is_present() {
        let base = manifest(&route("/admin", "gated", &["admin"]));
        let head = manifest(&route("/admin", "public", &[]));

        let blocked = evaluate(Some(&base), &head, &[]);
        assert!(blocked.blocked());
        assert_eq!(blocked.exit_code(), EXIT_BLOCKED);

        let comment = format!("{} {}", ack::ACK_PHRASE, ack::short(&blocked.ack_digest));
        let acknowledged = evaluate(Some(&base), &head, &ack::parse_acks(&comment));
        assert!(!acknowledged.blocked());
        assert_eq!(acknowledged.exit_code(), 0);
        assert!(acknowledged.acknowledged.is_some());
    }

    /// The acknowledgment is bound to the widening set, so a *later* widening
    /// re-blocks even though the marker is still sitting on the pull request.
    #[test]
    fn re_widening_after_an_acknowledgment_blocks_again() {
        let base = manifest(&route("/admin", "gated", &["admin"]));
        let first = manifest(&route("/admin", "public", &[]));
        let comment = format!(
            "{} {}",
            ack::ACK_PHRASE,
            ack::short(&evaluate(Some(&base), &first, &[]).ack_digest)
        );
        assert!(!evaluate(Some(&base), &first, &ack::parse_acks(&comment)).blocked());

        let second = manifest(&format!(
            "{},{}",
            route("/admin", "public", &[]),
            route("/internal", "public", &[])
        ));
        assert!(
            evaluate(Some(&base), &second, &ack::parse_acks(&comment)).blocked(),
            "a new widening must not inherit the old acknowledgment"
        );
    }

    /// Pushing commits that do not change the widening set keeps the
    /// acknowledgment valid — otherwise every push would re-ask.
    #[test]
    fn an_unrelated_push_keeps_the_acknowledgment_valid() {
        let base = manifest(&route("/admin", "gated", &["admin"]));
        let first = manifest(&route("/admin", "public", &[]));
        let comment = format!(
            "{} {}",
            ack::ACK_PHRASE,
            ack::short(&evaluate(Some(&base), &first, &[]).ack_digest)
        );

        // A later commit adds a *gated* route: neutral, so the widening set is
        // untouched.
        let later = manifest(&format!(
            "{},{}",
            route("/admin", "public", &[]),
            route("/reports", "gated", &["admin"])
        ));
        let e = evaluate(Some(&base), &later, &ack::parse_acks(&comment));
        assert!(!e.blocked());
        assert!(
            e.acknowledged.is_some(),
            "it passes *because* the acknowledgment still matches, not because \
             the widening stopped being detected"
        );
        assert_eq!(diff::widening(&e.findings).len(), 1);
    }

    #[test]
    fn narrowing_only_changes_never_block() {
        let base = manifest(&route("/admin", "public", &[]));
        let head = manifest(&route("/admin", "gated", &["admin"]));
        let e = evaluate(Some(&base), &head, &[]);
        assert!(!e.blocked());
        assert!(!e.findings.is_empty(), "but they are still reported");
    }

    #[test]
    fn with_no_baseline_nothing_blocks() {
        let head = manifest(&route("/admin", "public", &[]));
        let e = evaluate(None, &head, &[]);
        assert!(e.bootstrap);
        assert!(!e.blocked());
        assert!(e.findings.is_empty());
        assert_eq!(e.exit_code(), 0);
    }

    #[test]
    fn the_head_posture_digest_is_the_manifests_own() {
        let head = manifest(&route("/admin", "gated", &["admin"]));
        let e = evaluate(None, &head, &[]);
        assert_eq!(e.head_posture_digest, head.posture_digest());
    }

    #[test]
    fn an_unknown_format_is_a_usage_error_not_a_silent_fallback() {
        let head = manifest(&route("/a", "gated", &["admin"]));
        let e = evaluate(None, &head, &[]);
        assert!(render(&e, "markdwon").is_err());
    }

    /// A base path that exists but cannot be read is a broken run, not the
    /// benign "no baseline yet" case — reporting it as bootstrap would disarm
    /// the gate for that run, and the scaffolded workflow always passes
    /// `--allow-missing-base`.
    #[test]
    fn an_unreadable_base_is_a_usage_error_even_with_allow_missing_base() {
        let dir = tempfile::tempdir().unwrap();
        let head = dir.path().join("head.json");
        std::fs::write(
            &head,
            serde_json::to_string(&serde_json::json!({
                "schema_version": 3,
                "dimensions": {"routes": {"entries": [
                    {"path": "/a", "method": "GET", "classification": "public"}
                ]}}
            }))
            .unwrap(),
        )
        .unwrap();
        // A directory is present-but-unreadable-as-a-file.
        let base = dir.path().join("base-dir");
        std::fs::create_dir(&base).unwrap();

        let code = run_diff(&DiffOptions {
            base: base.to_str().unwrap(),
            head: head.to_str().unwrap(),
            format: "json",
            output: None,
            acks: &[],
            ack_file: None,
            ack_dir: None,
            allow_missing_base: true,
        });
        assert_eq!(code, EXIT_USAGE, "must not be scored as a clean bootstrap");
    }

    /// A head manifest with no routes at all scores as a pure narrowing, so a
    /// partial or failed audit that still wrote a well-formed file would sail
    /// through. Refuse to score it.
    #[test]
    fn an_empty_head_manifest_against_a_populated_base_is_a_usage_error() {
        let dir = tempfile::tempdir().unwrap();
        let base = dir.path().join("base.json");
        let head = dir.path().join("head.json");
        std::fs::write(
            &base,
            serde_json::to_string(&serde_json::json!({
                "schema_version": 3,
                "dimensions": {"routes": {"entries": [
                    {"path": "/a", "method": "GET", "classification": "gated", "roles": ["admin"]}
                ]}}
            }))
            .unwrap(),
        )
        .unwrap();
        std::fs::write(&head, r#"{"schema_version":3}"#).unwrap();

        let code = run_diff(&DiffOptions {
            base: base.to_str().unwrap(),
            head: head.to_str().unwrap(),
            format: "json",
            output: None,
            acks: &[],
            ack_file: None,
            ack_dir: None,
            allow_missing_base: true,
        });
        assert_eq!(code, EXIT_USAGE);
    }

    /// `--output` is the flag the scaffolded workflow depends on: it must write
    /// the report, and it must write an *empty* file on a clean run so the
    /// workflow's `[ -s … ]` test decides whether to post.
    #[test]
    fn the_output_flag_writes_the_report_and_writes_nothing_when_clean() {
        let dir = tempfile::tempdir().unwrap();
        let base = dir.path().join("base.json");
        let head = dir.path().join("head.json");
        let report = dir.path().join("report.md");
        let write = |path: &std::path::Path, classification: &str, roles: &str| {
            std::fs::write(
                path,
                format!(
                    r#"{{"schema_version":3,"dimensions":{{"routes":{{"entries":[
                       {{"path":"/admin","method":"GET","classification":"{classification}","roles":[{roles}]}}]}}}}}}"#
                ),
            )
            .unwrap();
        };

        write(&base, "gated", "\"admin\"");
        write(&head, "public", "");
        let opts = DiffOptions {
            base: base.to_str().unwrap(),
            head: head.to_str().unwrap(),
            format: "markdown",
            output: Some(report.to_str().unwrap()),
            acks: &[],
            ack_file: None,
            ack_dir: None,
            allow_missing_base: false,
        };
        assert_eq!(run_diff(&opts), EXIT_BLOCKED);
        let written = std::fs::read_to_string(&report).unwrap();
        assert!(written.contains("/admin"), "{written}");
        assert!(written.contains(render::COMMENT_MARKER), "{written}");

        write(&head, "gated", "\"admin\"");
        assert_eq!(run_diff(&opts), 0);
        assert_eq!(
            std::fs::read_to_string(&report).unwrap(),
            "",
            "a clean run leaves nothing for the workflow to post"
        );
    }

    #[test]
    fn an_acknowledgment_for_a_different_digest_does_not_unblock() {
        let base = manifest(&route("/admin", "gated", &["admin"]));
        let head = manifest(&route("/admin", "public", &[]));
        let e = evaluate(
            Some(&base),
            &head,
            &ack::parse_acks("/ack-posture 0000000000000000"),
        );
        assert!(e.blocked());
        assert!(e.acknowledged.is_none());
    }

    /// `--ack-dir` reads one file per comment, so the file boundary is the
    /// comment boundary. No text in a comment can forge it (#2472).
    #[test]
    fn the_ack_dir_parses_each_comment_on_its_own() {
        let dir = tempfile::tempdir().unwrap();
        let base = dir.path().join("base.json");
        let head = dir.path().join("head.json");
        let write = |path: &std::path::Path, classification: &str, roles: &str| {
            std::fs::write(
                path,
                format!(
                    r#"{{"schema_version":3,"dimensions":{{"routes":{{"entries":[
                       {{"path":"/admin","method":"GET","classification":"{classification}","roles":[{roles}]}}]}}}}}}"#
                ),
            )
            .unwrap();
        };
        write(&base, "gated", "\"admin\"");
        write(&head, "public", "");
        let digest = ack::short(
            &evaluate(
                Some(&PostureManifest::read(base.to_str().unwrap()).unwrap()),
                &PostureManifest::read(head.to_str().unwrap()).unwrap(),
                &[],
            )
            .ack_digest,
        );

        let acks = dir.path().join("acks");
        std::fs::create_dir(&acks).unwrap();
        let opts = DiffOptions {
            base: base.to_str().unwrap(),
            head: head.to_str().unwrap(),
            format: "text",
            output: None,
            acks: &[],
            ack_file: None,
            ack_dir: Some(acks.to_str().unwrap()),
            allow_missing_base: false,
        };

        // The old in-band separator inside a fence is inert text now: it
        // must not reset the fence and make the marker after it live.
        std::fs::write(
            acks.join("1.md"),
            format!(
                "```\n{}\n{} {digest}\n```\n",
                ack::SOURCE_SEPARATOR,
                ack::ACK_PHRASE
            ),
        )
        .unwrap();
        assert_eq!(run_diff(&opts), EXIT_BLOCKED);

        // An unclosed fence in one comment does not swallow the next one.
        std::fs::write(acks.join("1.md"), "log:\n```\noops\n").unwrap();
        std::fs::write(acks.join("2.md"), format!("{} {digest}\n", ack::ACK_PHRASE)).unwrap();
        assert_eq!(run_diff(&opts), 0);
    }

    #[test]
    fn a_missing_ack_dir_is_a_usage_error() {
        let dir = tempfile::tempdir().unwrap();
        let head = dir.path().join("head.json");
        std::fs::write(&head, r#"{"schema_version":3}"#).unwrap();
        let missing = dir.path().join("no-such-dir");
        let code = run_diff(&DiffOptions {
            base: head.to_str().unwrap(),
            head: head.to_str().unwrap(),
            format: "text",
            output: None,
            acks: &[],
            ack_file: None,
            ack_dir: Some(missing.to_str().unwrap()),
            allow_missing_base: false,
        });
        assert_eq!(code, EXIT_USAGE);
    }

    /// `--ack-dir` reads only regular files. A marker in a subdirectory is
    /// not a comment the workflow wrote.
    #[test]
    fn the_ack_dir_skips_subdirectories() {
        let dir = tempfile::tempdir().unwrap();
        let base = dir.path().join("base.json");
        let head = dir.path().join("head.json");
        std::fs::write(
            &base,
            manifest_json(&route("/admin", "gated", &["admin"]), ""),
        )
        .unwrap();
        std::fs::write(&head, manifest_json(&route("/admin", "public", &[]), "")).unwrap();
        let digest = ack::short(
            &evaluate(
                Some(&PostureManifest::read(base.to_str().unwrap()).unwrap()),
                &PostureManifest::read(head.to_str().unwrap()).unwrap(),
                &[],
            )
            .ack_digest,
        );
        let acks = dir.path().join("acks");
        std::fs::create_dir_all(acks.join("sub")).unwrap();
        std::fs::write(
            acks.join("sub").join("1.md"),
            format!("{} {digest}\n", ack::ACK_PHRASE),
        )
        .unwrap();
        let code = run_diff(&DiffOptions {
            base: base.to_str().unwrap(),
            head: head.to_str().unwrap(),
            format: "text",
            output: None,
            acks: &[],
            ack_file: None,
            ack_dir: Some(acks.to_str().unwrap()),
            allow_missing_base: false,
        });
        assert_eq!(code, EXIT_BLOCKED);
    }

    /// A build change blocks, a marker for its digest unblocks it, and the
    /// JSON report names it the way `scripts/check-posture-gate.sh` greps.
    #[test]
    fn a_build_change_blocks_until_acknowledged() {
        let r = route("/admin", "gated", &["admin"]);
        let base = parse(&manifest_json(&r, ""));
        let head = parse(&manifest_json(&r, r#""build":{"profile":"release"},"#));

        let blocked = evaluate(Some(&base), &head, &[]);
        assert!(blocked.blocked());
        let json = render(&blocked, "json").unwrap();
        assert!(json.contains(r#""kind": "build_changed""#), "{json}");

        let comment = format!("{} {}", ack::ACK_PHRASE, ack::short(&blocked.ack_digest));
        assert!(!evaluate(Some(&base), &head, &ack::parse_acks(&comment)).blocked());
    }

    // ── ceiling markers (#2497) ─────────────────────────────────────────────

    /// A route with scopes, for the "constraint removed" cases.
    fn scoped(path: &str, classification: &str, scopes: &[&str], policy: bool) -> String {
        let scopes = scopes
            .iter()
            .map(|s| format!("\"{s}\""))
            .collect::<Vec<_>>()
            .join(",");
        format!(
            r#"{{"path":"{path}","method":"GET","name":"h","classification":"{classification}",
                 "roles":[],"scopes":[{scopes}],"policy":{policy},"source":"user","provenance":"provable"}}"#
        )
    }

    /// The line the gate asks a reviewer to paste, as a parsed marker.
    fn pasted(e: &Evaluation) -> Vec<Acknowledgment> {
        ack::parse_acks(&format!("{} {} for launch", ack::ACK_PHRASE, e.marker))
    }

    fn admin_base() -> PostureManifest {
        manifest(&route("/admin", "gated", &["admin"]))
    }

    #[test]
    fn the_printed_marker_carries_a_ceiling_and_acknowledges() {
        let base = admin_base();
        let head = manifest(&scoped("/admin", "public", &["mfa"], false));
        let blocked = evaluate(Some(&base), &head, &[]);
        assert!(blocked.marker.contains("ceiling="), "{}", blocked.marker);
        let e = evaluate(Some(&base), &head, &pasted(&blocked));
        assert!(!e.blocked());
        assert!(e.acknowledged.is_some());
    }

    /// Scenario 2 of #2497: a follow-up narrows the route; nothing got wider.
    #[test]
    fn an_acknowledgment_survives_a_later_narrowing() {
        let base = admin_base();
        let first = manifest(&scoped("/admin", "public", &[], false));
        let acks = pasted(&evaluate(Some(&base), &first, &[]));
        let narrowed = manifest(&scoped("/admin", "public", &[], true));
        let e = evaluate(Some(&base), &narrowed, &acks);
        assert!(!e.blocked(), "a policy check only narrows");
        assert!(e.acknowledged.is_some());
    }

    /// Scenario 1 of #2497: a constraint is dropped after it was acknowledged.
    #[test]
    fn an_acknowledgment_does_not_survive_a_constraint_being_removed() {
        let base = admin_base();
        let first = manifest(&scoped("/admin", "public", &["mfa"], false));
        let acks = pasted(&evaluate(Some(&base), &first, &[]));
        let dropped = manifest(&scoped("/admin", "public", &[], false));
        assert!(evaluate(Some(&base), &dropped, &acks).blocked());
    }

    #[test]
    fn a_policy_check_dropped_after_acknowledgment_re_blocks() {
        let base = manifest(&scoped("/admin", "gated", &[], true));
        let first = manifest(&scoped("/admin", "gated", &[], true));
        assert!(evaluate(Some(&base), &first, &[]).findings.is_empty());
        let wide = manifest(&scoped("/admin", "public", &[], true));
        let acks = pasted(&evaluate(Some(&base), &wide, &[]));
        let dropped = manifest(&scoped("/admin", "public", &[], false));
        assert!(evaluate(Some(&base), &dropped, &acks).blocked());
    }

    #[test]
    fn a_ceiling_marker_does_not_cover_a_new_widening() {
        let base = admin_base();
        let first = manifest(&route("/admin", "public", &[]));
        let acks = pasted(&evaluate(Some(&base), &first, &[]));
        let second = manifest(&format!(
            "{},{}",
            route("/admin", "public", &[]),
            route("/internal", "public", &[])
        ));
        assert!(evaluate(Some(&base), &second, &acks).blocked());
    }

    /// The digest covers the payload. A hand-widened payload with the old digest must
    /// fail. The digest catches mistakes. It is not a secret.
    #[test]
    fn a_hand_widened_ceiling_is_refused() {
        let base = admin_base();
        let head = manifest(&scoped("/admin", "public", &["mfa"], false));
        let strict = evaluate(Some(&base), &head, &[]);
        let loose_head = manifest(&scoped("/admin", "public", &[], false));
        let loose = evaluate(Some(&base), &loose_head, &[]);
        let digest = strict.marker.split_whitespace().next().unwrap().to_owned();
        let loose_payload = loose.marker.split("ceiling=").nth(1).unwrap().to_owned();
        let forged = ack::parse_acks(&format!(
            "{} {digest} ceiling={loose_payload}",
            ack::ACK_PHRASE
        ));
        assert!(evaluate(Some(&base), &loose_head, &forged).blocked());
    }

    /// A bare digest keeps meaning "exactly this": that is the strict option.
    #[test]
    fn a_bare_digest_still_re_asks_after_a_narrowing() {
        let base = admin_base();
        let first = manifest(&scoped("/admin", "public", &[], false));
        let pasted_bare = format!(
            "{} {}",
            ack::ACK_PHRASE,
            ack::short(&evaluate(Some(&base), &first, &[]).ack_digest)
        );
        assert!(!evaluate(Some(&base), &first, &ack::parse_acks(&pasted_bare)).blocked());
        let narrowed = manifest(&scoped("/admin", "public", &[], true));
        assert!(evaluate(Some(&base), &narrowed, &ack::parse_acks(&pasted_bare)).blocked());
    }

    /// A finding that names no route at head has no posture to order, so it
    /// stays bound to the exact digest, ceiling or not.
    #[test]
    fn a_build_change_is_still_bound_exactly() {
        let routes = route("/admin", "gated", &["admin"]);
        let base = parse(&manifest_json(&routes, ""));
        let head = parse(&manifest_json(
            &routes,
            r#""build":{"profile":"release","features":["x"],"default_features":true},"#,
        ));
        let blocked = evaluate(Some(&base), &head, &[]);
        assert!(blocked.blocked(), "{:?}", blocked.findings);
        assert!(
            !blocked.marker.contains("ceiling="),
            "nothing to order: {}",
            blocked.marker
        );
        assert!(!evaluate(Some(&base), &head, &pasted(&blocked)).blocked());
    }

    /// One of two acknowledged routes goes back to its base posture. The set of
    /// findings shrinks, and every route left is within its ceiling.
    #[test]
    fn an_acknowledgment_survives_the_widening_set_shrinking() {
        let base = manifest(&format!(
            "{},{}",
            route("/a", "gated", &["admin"]),
            route("/b", "gated", &["admin"])
        ));
        let both = manifest(&format!(
            "{},{}",
            route("/a", "public", &[]),
            route("/b", "public", &[])
        ));
        let acks = pasted(&evaluate(Some(&base), &both, &[]));
        let one_back = manifest(&format!(
            "{},{}",
            route("/a", "gated", &["admin"]),
            route("/b", "public", &[])
        ));
        assert!(!evaluate(Some(&base), &one_back, &acks).blocked());
    }

    /// Narrowing can change the kind of finding: `roles_cleared` becomes
    /// `roles_widened`. The route is still within its ceiling.
    #[test]
    fn an_acknowledgment_survives_a_narrowing_that_changes_the_finding_kind() {
        let base = manifest(&route("/a", "gated", &["admin"]));
        let cleared = manifest(&route("/a", "gated", &[]));
        let acks = pasted(&evaluate(Some(&base), &cleared, &[]));
        let some = manifest(&route("/a", "gated", &["admin", "editor"]));
        let e = evaluate(Some(&base), &some, &acks);
        assert!(!diff::widening(&e.findings).is_empty());
        assert!(!e.blocked());
    }

    #[test]
    fn the_report_names_the_strict_digest_beside_a_ceiling_marker() {
        let base = admin_base();
        let head = manifest(&route("/admin", "public", &[]));
        let e = evaluate(Some(&base), &head, &[]);
        let md = render(&e, "markdown").unwrap();
        let strict = format!("{} {}", ack::ACK_PHRASE, ack::short(&e.ack_digest));
        assert!(md.contains(&strict), "{md}");
        let strict_acks = ack::parse_acks(&strict);
        assert!(!evaluate(Some(&base), &head, &strict_acks).blocked());
    }
}