Skip to main content

ftui_widgets/
receipt_verifier_panel.rs

1#![forbid(unsafe_code)]
2
3//! Receipt verifier panel widget (bd-cixqu.1.8 / Track A.7.1).
4//!
5//! Renders the operator-facing verifier verdict for a signed decision receipt,
6//! mirroring `runbooks/scripts/verify_receipt.sh` inside the TUI. The panel
7//! takes a parsed [`ReceiptVerdict`](crate::receipt_verifier_panel::ReceiptVerdict) —
8//! built from the verifier's JSON output, or programmatically — and displays:
9//!
10//! - the overall verdict (receipt id + PASS/FAIL + failure_class on failure);
11//! - the three verification layers (signature / transparency / attestation)
12//!   each as PASS/FAIL with its `error_code`;
13//! - optional posterior path the receipt binds (`show_posterior_path`);
14//! - optional transparency-log inclusion + signature evidence chain
15//!   (`show_evidence_chain`);
16//! - warnings; and a triage block keyed off the `failure_class`.
17//!
18//! The panel intentionally keeps its data model self-contained (no engine
19//! dependency) so callers can construct it from any source — the verifier's
20//! `UnifiedReceiptVerificationVerdict` JSON, fixtures, mocks for previews,
21//! etc. The `verify_receipt.sh` verdict shape maps field-for-field onto the
22//! types defined here.
23
24use crate::borders::{BorderSet, BorderType};
25use crate::{Widget, apply_style, clear_text_area, draw_text_span};
26use ftui_core::geometry::Rect;
27use ftui_render::cell::{Cell, PackedRgba};
28use ftui_render::frame::Frame;
29use ftui_style::Style;
30
31// ---------------------------------------------------------------------------
32// Colour palette (mirrors decision_card)
33// ---------------------------------------------------------------------------
34
35const PASS_FG: PackedRgba = PackedRgba::rgb(0, 200, 0);
36const PASS_BG: PackedRgba = PackedRgba::rgb(0, 60, 0);
37const FAIL_FG: PackedRgba = PackedRgba::rgb(220, 50, 50);
38const FAIL_BG: PackedRgba = PackedRgba::rgb(60, 10, 10);
39const WARN_FG: PackedRgba = PackedRgba::rgb(220, 200, 0);
40const HEADER_FG: PackedRgba = PackedRgba::rgb(140, 160, 180);
41const DIM_FG: PackedRgba = PackedRgba::rgb(120, 120, 120);
42const DETAIL_FG: PackedRgba = PackedRgba::rgb(160, 180, 200);
43
44// ---------------------------------------------------------------------------
45// Data model — mirrors the verifier verdict JSON shape
46// ---------------------------------------------------------------------------
47
48/// Outcome of a single layer-internal check.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum CheckOutcome {
51    Pass,
52    Fail,
53    Warn,
54}
55
56impl CheckOutcome {
57    /// Parse an `outcome` string as emitted by the verifier (`pass`/`fail`/`warn`).
58    /// Unknown values are treated as `Warn` so they remain visible.
59    #[must_use]
60    pub fn parse(s: &str) -> Self {
61        match s {
62            "pass" | "PASS" => Self::Pass,
63            "fail" | "FAIL" => Self::Fail,
64            _ => Self::Warn,
65        }
66    }
67
68    /// Short label suitable for rendering (`PASS` / `FAIL` / `WARN`).
69    #[must_use]
70    pub fn label(self) -> &'static str {
71        match self {
72            Self::Pass => "PASS",
73            Self::Fail => "FAIL",
74            Self::Warn => "WARN",
75        }
76    }
77}
78
79/// One layer-internal check (signature/transparency/attestation sub-check).
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct CheckEntry {
82    pub check: String,
83    pub outcome: CheckOutcome,
84    pub error_code: Option<String>,
85    pub detail: String,
86}
87
88/// Verdict for one of the three verification layers.
89#[derive(Debug, Clone, PartialEq, Eq, Default)]
90pub struct LayerVerdict {
91    pub passed: bool,
92    pub error_code: Option<String>,
93    pub checks: Vec<CheckEntry>,
94}
95
96/// Failure classification when `passed == false`.
97///
98/// Matches the verifier's `failure_class` field — `None` means the receipt
99/// verified.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum FailureClass {
102    Signature,
103    Transparency,
104    Attestation,
105    StaleData,
106}
107
108impl FailureClass {
109    /// Parse the JSON failure_class string. Returns `None` for null/missing.
110    #[must_use]
111    pub fn parse(s: &str) -> Option<Self> {
112        match s {
113            "Signature" => Some(Self::Signature),
114            "Transparency" => Some(Self::Transparency),
115            "Attestation" => Some(Self::Attestation),
116            "StaleData" => Some(Self::StaleData),
117            _ => None,
118        }
119    }
120
121    #[must_use]
122    pub fn label(self) -> &'static str {
123        match self {
124            Self::Signature => "Signature",
125            Self::Transparency => "Transparency",
126            Self::Attestation => "Attestation",
127            Self::StaleData => "StaleData",
128        }
129    }
130}
131
132/// Optional posterior snapshot the receipt binds (from the input JSON).
133#[derive(Debug, Clone, PartialEq, Default)]
134pub struct PosteriorSnapshot {
135    pub point_estimate: Option<f64>,
136    pub ci_lower: Option<f64>,
137    pub ci_upper: Option<f64>,
138}
139
140/// A parsed verifier verdict ready for the panel to render.
141///
142/// Maps onto the `UnifiedReceiptVerificationVerdict` shape that
143/// `frankenctl verify receipt --output` emits.
144#[derive(Debug, Clone, PartialEq)]
145pub struct ReceiptVerdict {
146    pub receipt_id: String,
147    pub trace_id: String,
148    pub decision_id: String,
149    pub policy_id: String,
150    pub verification_timestamp_ns: u64,
151    pub passed: bool,
152    pub failure_class: Option<FailureClass>,
153    pub exit_code: i32,
154    pub signature: LayerVerdict,
155    pub transparency: LayerVerdict,
156    pub attestation: LayerVerdict,
157    pub warnings: Vec<String>,
158    /// Optional — populated from the verifier input JSON when available.
159    pub posterior_snapshot: Option<PosteriorSnapshot>,
160}
161
162impl ReceiptVerdict {
163    /// Build a minimal verdict skeleton (mostly for tests / previews).
164    #[must_use]
165    pub fn skeleton(receipt_id: impl Into<String>, passed: bool) -> Self {
166        Self {
167            receipt_id: receipt_id.into(),
168            trace_id: String::new(),
169            decision_id: String::new(),
170            policy_id: String::new(),
171            verification_timestamp_ns: 0,
172            passed,
173            failure_class: None,
174            exit_code: if passed { 0 } else { 2 },
175            signature: LayerVerdict::default(),
176            transparency: LayerVerdict::default(),
177            attestation: LayerVerdict::default(),
178            warnings: Vec::new(),
179            posterior_snapshot: None,
180        }
181    }
182}
183
184// ---------------------------------------------------------------------------
185// Panel widget
186// ---------------------------------------------------------------------------
187
188/// Receipt verifier panel — renders a [`ReceiptVerdict`] inside a bordered
189/// frame.
190///
191/// # Usage
192///
193/// ```
194/// use ftui_core::geometry::Rect;
195/// use ftui_render::{frame::Frame, grapheme_pool::GraphemePool};
196/// use ftui_widgets::Widget;
197/// use ftui_widgets::receipt_verifier_panel::{ReceiptVerifierPanel, ReceiptVerdict};
198///
199/// let mut pool = GraphemePool::new();
200/// let mut frame = Frame::new(80, 24, &mut pool);
201/// let area = Rect::new(0, 0, 80, 24);
202/// let verdict = ReceiptVerdict::skeleton("rcpt-001", true);
203/// let panel = ReceiptVerifierPanel::new(&verdict)
204///     .show_posterior_path(true)
205///     .show_evidence_chain(true);
206/// panel.render(area, &mut frame);
207/// ```
208#[derive(Debug, Clone)]
209pub struct ReceiptVerifierPanel<'a> {
210    verdict: &'a ReceiptVerdict,
211    border_type: BorderType,
212    style: Style,
213    title_style: Style,
214    show_posterior_path: bool,
215    show_evidence_chain: bool,
216    show_triage: bool,
217}
218
219impl<'a> ReceiptVerifierPanel<'a> {
220    /// Create a new panel for the given verdict.
221    ///
222    /// Defaults: rounded border, posterior path and evidence chain hidden,
223    /// triage block shown on failure.
224    #[must_use]
225    pub fn new(verdict: &'a ReceiptVerdict) -> Self {
226        Self {
227            verdict,
228            border_type: BorderType::Rounded,
229            style: Style::default(),
230            title_style: Style::default().bold(),
231            show_posterior_path: false,
232            show_evidence_chain: false,
233            show_triage: true,
234        }
235    }
236
237    #[must_use]
238    pub fn border_type(mut self, border_type: BorderType) -> Self {
239        self.border_type = border_type;
240        self
241    }
242
243    #[must_use]
244    pub fn style(mut self, style: Style) -> Self {
245        self.style = style;
246        self
247    }
248
249    #[must_use]
250    pub fn title_style(mut self, style: Style) -> Self {
251        self.title_style = style;
252        self
253    }
254
255    /// Show the decision posterior snapshot the receipt binds, when available
256    /// in [`ReceiptVerdict::posterior_snapshot`].
257    #[must_use]
258    pub fn show_posterior_path(mut self, show: bool) -> Self {
259        self.show_posterior_path = show;
260        self
261    }
262
263    /// Show the transparency-log + signature evidence-chain checks.
264    #[must_use]
265    pub fn show_evidence_chain(mut self, show: bool) -> Self {
266        self.show_evidence_chain = show;
267        self
268    }
269
270    /// Show the failure-class triage block on failure. On by default.
271    #[must_use]
272    pub fn show_triage(mut self, show: bool) -> Self {
273        self.show_triage = show;
274        self
275    }
276
277    /// Minimum height needed to render the panel given the current options.
278    #[must_use]
279    pub fn min_height(&self) -> u16 {
280        // Border top + verdict row + provenance row + 3 layer rows + border bottom = 7.
281        let mut h: u16 = 7;
282        if self.show_posterior_path
283            && let Some(snapshot) = self.verdict.posterior_snapshot.as_ref()
284        {
285            // header + up to 3 numeric rows
286            h += 1 + posterior_visible_rows(snapshot);
287        }
288        if self.show_evidence_chain {
289            // header + per-layer line + each check line for signature+transparency
290            h += 1 + 2; // headers for transparency + signature blocks
291            h += self.verdict.transparency.checks.len() as u16;
292            h += self.verdict.signature.checks.len() as u16;
293        }
294        if !self.verdict.warnings.is_empty() {
295            h += 1 + self.verdict.warnings.len() as u16; // header + per-warning
296        }
297        if self.show_triage
298            && let Some(fc) = self.verdict.failure_class
299        {
300            h += triage_height(fc);
301        }
302        h
303    }
304
305    fn border_style_for_status(passed: bool) -> Style {
306        if passed {
307            Style::new().fg(PASS_FG)
308        } else {
309            Style::new().fg(FAIL_FG)
310        }
311    }
312
313    fn render_border(&self, area: Rect, frame: &mut Frame, border_style: Style) {
314        let deg = frame.buffer.degradation;
315        let set = if deg.use_unicode_borders() {
316            self.border_type.to_border_set()
317        } else {
318            BorderSet::ASCII
319        };
320
321        let border_cell = |c: char| -> Cell {
322            let mut cell = Cell::from_char(c);
323            apply_style(&mut cell, border_style);
324            cell
325        };
326
327        for x in area.x..area.right() {
328            frame
329                .buffer
330                .set_fast(x, area.y, border_cell(set.horizontal));
331        }
332        let bottom_y = area.bottom().saturating_sub(1);
333        for x in area.x..area.right() {
334            frame
335                .buffer
336                .set_fast(x, bottom_y, border_cell(set.horizontal));
337        }
338        for y in area.y..area.bottom() {
339            frame.buffer.set_fast(area.x, y, border_cell(set.vertical));
340        }
341        let right_x = area.right().saturating_sub(1);
342        for y in area.y..area.bottom() {
343            frame.buffer.set_fast(right_x, y, border_cell(set.vertical));
344        }
345        frame
346            .buffer
347            .set_fast(area.x, area.y, border_cell(set.top_left));
348        frame
349            .buffer
350            .set_fast(right_x, area.y, border_cell(set.top_right));
351        frame
352            .buffer
353            .set_fast(area.x, bottom_y, border_cell(set.bottom_left));
354        frame
355            .buffer
356            .set_fast(right_x, bottom_y, border_cell(set.bottom_right));
357    }
358
359    fn verdict_badge_style(passed: bool, apply_styling: bool) -> Style {
360        if !apply_styling {
361            return Style::default();
362        }
363        if passed {
364            Style::new().fg(PASS_FG).bg(PASS_BG).bold()
365        } else {
366            Style::new().fg(FAIL_FG).bg(FAIL_BG).bold()
367        }
368    }
369
370    fn render_verdict_row(&self, x: u16, y: u16, max_x: u16, frame: &mut Frame) {
371        let apply_styling = frame.buffer.degradation.apply_styling();
372        let badge_text = if self.verdict.passed {
373            " VERIFIED "
374        } else {
375            " FAILED "
376        };
377        let badge_style = Self::verdict_badge_style(self.verdict.passed, apply_styling);
378        let title_style = if apply_styling {
379            self.title_style
380        } else {
381            Style::default()
382        };
383
384        let mut cx = draw_text_span(frame, x, y, badge_text, badge_style, max_x);
385        if cx < max_x {
386            cx = draw_text_span(frame, cx, y, " ", Style::default(), max_x);
387        }
388        let id_text = format!("receipt {}", self.verdict.receipt_id);
389        cx = draw_text_span(frame, cx, y, &id_text, title_style, max_x);
390
391        if !self.verdict.passed
392            && let Some(fc) = self.verdict.failure_class
393        {
394            let detail_style = if apply_styling {
395                Style::new().fg(FAIL_FG)
396            } else {
397                Style::default()
398            };
399            let trail = format!(
400                "   failure_class={}  exit_code={}",
401                fc.label(),
402                self.verdict.exit_code
403            );
404            let _ = draw_text_span(frame, cx, y, &trail, detail_style, max_x);
405        }
406    }
407
408    fn render_provenance_row(&self, x: u16, y: u16, max_x: u16, frame: &mut Frame) {
409        let style = if frame.buffer.degradation.apply_styling() {
410            Style::new().fg(DETAIL_FG)
411        } else {
412            Style::default()
413        };
414        let line = format!(
415            "trace={}  decision={}  policy={}",
416            display_or_dash(&self.verdict.trace_id),
417            display_or_dash(&self.verdict.decision_id),
418            display_or_dash(&self.verdict.policy_id),
419        );
420        draw_text_span(frame, x, y, &line, style, max_x);
421    }
422
423    fn render_layer_row(
424        x: u16,
425        y: u16,
426        max_x: u16,
427        frame: &mut Frame,
428        name: &str,
429        layer: &LayerVerdict,
430    ) {
431        let apply_styling = frame.buffer.degradation.apply_styling();
432        let label = format!("  {name:<13} ");
433        let label_style = if apply_styling {
434            Style::new().fg(HEADER_FG)
435        } else {
436            Style::default()
437        };
438        let mut cx = draw_text_span(frame, x, y, &label, label_style, max_x);
439
440        let outcome_label = if layer.passed { "PASS" } else { "FAIL" };
441        let outcome_style = if !apply_styling {
442            Style::default()
443        } else if layer.passed {
444            Style::new().fg(PASS_FG).bold()
445        } else {
446            Style::new().fg(FAIL_FG).bold()
447        };
448        cx = draw_text_span(frame, cx, y, outcome_label, outcome_style, max_x);
449
450        let trail_style = if apply_styling {
451            Style::new().fg(DIM_FG)
452        } else {
453            Style::default()
454        };
455        let trail = format!(
456            "   error_code={}",
457            layer.error_code.as_deref().unwrap_or("-")
458        );
459        let _ = draw_text_span(frame, cx, y, &trail, trail_style, max_x);
460    }
461
462    fn render_posterior_path(&self, x: u16, mut y: u16, max_x: u16, frame: &mut Frame) -> u16 {
463        let Some(snapshot) = self.verdict.posterior_snapshot.as_ref() else {
464            return y;
465        };
466        let apply_styling = frame.buffer.degradation.apply_styling();
467        let header_style = if apply_styling {
468            Style::new().fg(HEADER_FG).bold()
469        } else {
470            Style::default()
471        };
472        let detail_style = if apply_styling {
473            Style::new().fg(DETAIL_FG)
474        } else {
475            Style::default()
476        };
477
478        draw_text_span(frame, x, y, "posterior path:", header_style, max_x);
479        y += 1;
480        if let Some(p) = snapshot.point_estimate {
481            draw_text_span(
482                frame,
483                x,
484                y,
485                &format!("  point_estimate = {p}"),
486                detail_style,
487                max_x,
488            );
489            y += 1;
490        }
491        if let Some(lo) = snapshot.ci_lower {
492            draw_text_span(
493                frame,
494                x,
495                y,
496                &format!("  confidence_interval_95_lower = {lo}"),
497                detail_style,
498                max_x,
499            );
500            y += 1;
501        }
502        if let Some(hi) = snapshot.ci_upper {
503            draw_text_span(
504                frame,
505                x,
506                y,
507                &format!("  confidence_interval_95_upper = {hi}"),
508                detail_style,
509                max_x,
510            );
511            y += 1;
512        }
513        y
514    }
515
516    fn render_evidence_chain(&self, x: u16, mut y: u16, max_x: u16, frame: &mut Frame) -> u16 {
517        let apply_styling = frame.buffer.degradation.apply_styling();
518        let header_style = if apply_styling {
519            Style::new().fg(HEADER_FG).bold()
520        } else {
521            Style::default()
522        };
523
524        draw_text_span(frame, x, y, "evidence chain:", header_style, max_x);
525        y += 1;
526        y = render_layer_checks(
527            x,
528            y,
529            max_x,
530            frame,
531            "transparency",
532            &self.verdict.transparency,
533        );
534        y = render_layer_checks(x, y, max_x, frame, "signature", &self.verdict.signature);
535        y
536    }
537
538    fn render_warnings(&self, x: u16, mut y: u16, max_x: u16, frame: &mut Frame) -> u16 {
539        if self.verdict.warnings.is_empty() {
540            return y;
541        }
542        let apply_styling = frame.buffer.degradation.apply_styling();
543        let header_style = if apply_styling {
544            Style::new().fg(WARN_FG).bold()
545        } else {
546            Style::default()
547        };
548        let line_style = if apply_styling {
549            Style::new().fg(WARN_FG)
550        } else {
551            Style::default()
552        };
553        draw_text_span(frame, x, y, "warnings:", header_style, max_x);
554        y += 1;
555        for w in &self.verdict.warnings {
556            draw_text_span(frame, x, y, &format!("  ! {w}"), line_style, max_x);
557            y += 1;
558        }
559        y
560    }
561
562    fn render_triage(&self, x: u16, mut y: u16, max_x: u16, frame: &mut Frame) -> u16 {
563        if !self.show_triage {
564            return y;
565        }
566        let Some(fc) = self.verdict.failure_class else {
567            return y;
568        };
569        let apply_styling = frame.buffer.degradation.apply_styling();
570        let header_style = if apply_styling {
571            Style::new().fg(FAIL_FG).bold()
572        } else {
573            Style::default()
574        };
575        let body_style = if apply_styling {
576            Style::new().fg(DETAIL_FG)
577        } else {
578            Style::default()
579        };
580
581        draw_text_span(
582            frame,
583            x,
584            y,
585            &format!("incident triage (failure_class={}):", fc.label()),
586            header_style,
587            max_x,
588        );
589        y += 1;
590        for line in triage_lines(fc) {
591            draw_text_span(frame, x, y, line, body_style, max_x);
592            y += 1;
593        }
594        y
595    }
596}
597
598impl Widget for ReceiptVerifierPanel<'_> {
599    fn render(&self, area: Rect, frame: &mut Frame) {
600        if area.is_empty() {
601            return;
602        }
603        if area.width < 4 || area.height < 3 {
604            clear_text_area(frame, area, Style::default());
605            return;
606        }
607
608        let deg = frame.buffer.degradation;
609        if !deg.render_content() {
610            clear_text_area(frame, area, Style::default());
611            return;
612        }
613
614        let base_style = if deg.apply_styling() {
615            self.style
616        } else {
617            Style::default()
618        };
619        clear_text_area(frame, area, base_style);
620
621        let border_style = Self::border_style_for_status(self.verdict.passed);
622        let border_style = if deg.apply_styling() {
623            border_style
624        } else {
625            Style::default()
626        };
627        if deg.render_decorative() {
628            self.render_border(area, frame, border_style);
629        }
630
631        let inner_x = area.x.saturating_add(1);
632        let inner_max_x = area.right().saturating_sub(1);
633        let mut y = area.y.saturating_add(1);
634        let max_y = area.bottom().saturating_sub(1);
635
636        if y >= max_y || inner_x >= inner_max_x {
637            return;
638        }
639
640        // 1. Verdict row.
641        self.render_verdict_row(inner_x, y, inner_max_x, frame);
642        y += 1;
643        if y >= max_y {
644            return;
645        }
646
647        // 2. Provenance row.
648        self.render_provenance_row(inner_x, y, inner_max_x, frame);
649        y += 1;
650        if y >= max_y {
651            return;
652        }
653
654        // 3. Three-layer status block.
655        for (name, layer) in [
656            ("signature", &self.verdict.signature),
657            ("transparency", &self.verdict.transparency),
658            ("attestation", &self.verdict.attestation),
659        ] {
660            if y >= max_y {
661                return;
662            }
663            Self::render_layer_row(inner_x, y, inner_max_x, frame, name, layer);
664            y += 1;
665        }
666
667        // 4. Optional posterior path.
668        if self.show_posterior_path && self.verdict.posterior_snapshot.is_some() && y < max_y {
669            y = self.render_posterior_path(inner_x, y, inner_max_x, frame);
670        }
671
672        // 5. Optional evidence chain.
673        if self.show_evidence_chain && y < max_y {
674            y = self.render_evidence_chain(inner_x, y, inner_max_x, frame);
675        }
676
677        // 6. Warnings.
678        if y < max_y {
679            y = self.render_warnings(inner_x, y, inner_max_x, frame);
680        }
681
682        // 7. Triage.
683        if y < max_y {
684            let _ = self.render_triage(inner_x, y, inner_max_x, frame);
685        }
686    }
687
688    fn is_essential(&self) -> bool {
689        false
690    }
691}
692
693// ---------------------------------------------------------------------------
694// Helpers
695// ---------------------------------------------------------------------------
696
697fn display_or_dash(s: &str) -> &str {
698    if s.is_empty() { "-" } else { s }
699}
700
701fn render_layer_checks(
702    x: u16,
703    mut y: u16,
704    max_x: u16,
705    frame: &mut Frame,
706    name: &str,
707    layer: &LayerVerdict,
708) -> u16 {
709    let apply_styling = frame.buffer.degradation.apply_styling();
710    let header_style = if apply_styling {
711        Style::new().fg(HEADER_FG)
712    } else {
713        Style::default()
714    };
715    let verdict = if layer.passed { "PASS" } else { "FAIL" };
716    draw_text_span(
717        frame,
718        x,
719        y,
720        &format!("  {name} layer ({verdict}):"),
721        header_style,
722        max_x,
723    );
724    y += 1;
725    for check in &layer.checks {
726        let outcome_style = if !apply_styling {
727            Style::default()
728        } else {
729            match check.outcome {
730                CheckOutcome::Pass => Style::new().fg(PASS_FG),
731                CheckOutcome::Fail => Style::new().fg(FAIL_FG),
732                CheckOutcome::Warn => Style::new().fg(WARN_FG),
733            }
734        };
735        let line = format!(
736            "    [{}] {} — {}",
737            check.outcome.label(),
738            check.check,
739            check.detail
740        );
741        draw_text_span(frame, x, y, &line, outcome_style, max_x);
742        y += 1;
743    }
744    y
745}
746
747fn posterior_visible_rows(snapshot: &PosteriorSnapshot) -> u16 {
748    let mut n: u16 = 0;
749    if snapshot.point_estimate.is_some() {
750        n += 1;
751    }
752    if snapshot.ci_lower.is_some() {
753        n += 1;
754    }
755    if snapshot.ci_upper.is_some() {
756        n += 1;
757    }
758    n
759}
760
761/// Operator-facing triage lines per failure class. Mirrors the prose emitted
762/// by `verify_receipt.sh print_triage`.
763fn triage_lines(fc: FailureClass) -> &'static [&'static str] {
764    match fc {
765        FailureClass::Signature => &[
766            "  The receipt's threshold signature did not validate.",
767            "  -> Confirm the verifier has the correct signer verification keys.",
768            "  -> A genuine mismatch means the receipt was not produced by the",
769            "     attested signing quorum: treat the decision as UNTRUSTED.",
770        ],
771        FailureClass::Transparency => &[
772            "  The transparency-log inclusion and/or consistency proof failed.",
773            "  -> --show-evidence-chain shows which MMR proof check failed.",
774            "  -> Inclusion fail: the receipt is not in the published log",
775            "     (possible equivocation/omission). Consistency fail: the log was",
776            "     forked or rewritten between checkpoints. Escalate to log-operator.",
777        ],
778        FailureClass::Attestation => &[
779            "  The TEE attestation quote could not be validated.",
780            "  -> Runtime has degraded to SAFE-MODE: it continues only under the",
781            "     restricted capability posture (no attested-only operations),",
782            "     because it can no longer prove it runs in a trusted enclave.",
783            "  -> Check tee_attestation_policy freshness/measurement; a stale or",
784            "     mismatched measurement is the usual cause. Re-attest before",
785            "     promoting any decision that requires a trusted enclave.",
786        ],
787        FailureClass::StaleData => &[
788            "  Verifier input is stale (timestamp/epoch outside accepted window).",
789            "  -> Re-export a fresh verifier_input.json for this receipt and re-run.",
790        ],
791    }
792}
793
794fn triage_height(fc: FailureClass) -> u16 {
795    1 + triage_lines(fc).len() as u16
796}
797
798// ===========================================================================
799// Tests
800// ===========================================================================
801
802#[cfg(test)]
803mod tests {
804    use super::*;
805    use ftui_render::frame::Frame;
806    use ftui_render::grapheme_pool::GraphemePool;
807
808    fn make_pass() -> ReceiptVerdict {
809        let mut v = ReceiptVerdict::skeleton("rcpt-001", true);
810        v.trace_id = "trace-aaa".into();
811        v.decision_id = "dec-bbb".into();
812        v.policy_id = "pol-ccc".into();
813        v.signature = LayerVerdict {
814            passed: true,
815            error_code: None,
816            checks: vec![CheckEntry {
817                check: "threshold_signature".into(),
818                outcome: CheckOutcome::Pass,
819                error_code: None,
820                detail: "3/3 signers".into(),
821            }],
822        };
823        v.transparency = LayerVerdict {
824            passed: true,
825            error_code: None,
826            checks: vec![
827                CheckEntry {
828                    check: "mmr_inclusion".into(),
829                    outcome: CheckOutcome::Pass,
830                    error_code: None,
831                    detail: "leaf 41 under root r9".into(),
832                },
833                CheckEntry {
834                    check: "mmr_consistency".into(),
835                    outcome: CheckOutcome::Pass,
836                    error_code: None,
837                    detail: "c0->c1 consistent".into(),
838                },
839            ],
840        };
841        v.attestation = LayerVerdict::default();
842        v.attestation.passed = true;
843        v.posterior_snapshot = Some(PosteriorSnapshot {
844            point_estimate: Some(0.873),
845            ci_lower: Some(0.81),
846            ci_upper: Some(0.92),
847        });
848        v
849    }
850
851    fn make_attestation_fail() -> ReceiptVerdict {
852        let mut v = ReceiptVerdict::skeleton("rcpt-001", false);
853        v.trace_id = "trace-aaa".into();
854        v.decision_id = "dec-bbb".into();
855        v.policy_id = "pol-ccc".into();
856        v.failure_class = Some(FailureClass::Attestation);
857        v.exit_code = 2;
858        v.signature = LayerVerdict {
859            passed: true,
860            error_code: None,
861            checks: vec![],
862        };
863        v.transparency = LayerVerdict {
864            passed: true,
865            error_code: None,
866            checks: vec![],
867        };
868        v.attestation = LayerVerdict {
869            passed: false,
870            error_code: Some("ATTEST_STALE".into()),
871            checks: vec![CheckEntry {
872                check: "quote_freshness".into(),
873                outcome: CheckOutcome::Fail,
874                error_code: Some("ATTEST_STALE".into()),
875                detail: "quote older than max age".into(),
876            }],
877        };
878        v.warnings = vec!["attestation degraded; running in safe-mode".into()];
879        v
880    }
881
882    fn extract_row(frame: &Frame, y: u16, width: u16) -> String {
883        let mut row = String::new();
884        for x in 0..width {
885            if let Some(cell) = frame.buffer.get(x, y)
886                && let Some(ch) = cell.content.as_char()
887            {
888                row.push(ch);
889            } else {
890                row.push(' ');
891            }
892        }
893        row
894    }
895
896    fn frame_has_text(frame: &Frame, width: u16, height: u16, needle: &str) -> bool {
897        for y in 0..height {
898            if extract_row(frame, y, width).contains(needle) {
899                return true;
900            }
901        }
902        false
903    }
904
905    #[test]
906    fn check_outcome_parse_round_trip() {
907        assert_eq!(CheckOutcome::parse("pass"), CheckOutcome::Pass);
908        assert_eq!(CheckOutcome::parse("PASS"), CheckOutcome::Pass);
909        assert_eq!(CheckOutcome::parse("fail"), CheckOutcome::Fail);
910        assert_eq!(CheckOutcome::parse("FAIL"), CheckOutcome::Fail);
911        assert_eq!(CheckOutcome::parse("anything-else"), CheckOutcome::Warn);
912        assert_eq!(CheckOutcome::Pass.label(), "PASS");
913        assert_eq!(CheckOutcome::Fail.label(), "FAIL");
914        assert_eq!(CheckOutcome::Warn.label(), "WARN");
915    }
916
917    #[test]
918    fn failure_class_parse_maps_all_known() {
919        assert_eq!(
920            FailureClass::parse("Signature"),
921            Some(FailureClass::Signature)
922        );
923        assert_eq!(
924            FailureClass::parse("Transparency"),
925            Some(FailureClass::Transparency)
926        );
927        assert_eq!(
928            FailureClass::parse("Attestation"),
929            Some(FailureClass::Attestation)
930        );
931        assert_eq!(
932            FailureClass::parse("StaleData"),
933            Some(FailureClass::StaleData)
934        );
935        assert_eq!(FailureClass::parse("null"), None);
936        assert_eq!(FailureClass::parse(""), None);
937    }
938
939    #[test]
940    fn pass_verdict_renders_verified_and_provenance() {
941        let v = make_pass();
942        let mut pool = GraphemePool::new();
943        let mut frame = Frame::new(80, 12, &mut pool);
944        ReceiptVerifierPanel::new(&v).render(Rect::new(0, 0, 80, 12), &mut frame);
945        assert!(frame_has_text(&frame, 80, 12, "VERIFIED"));
946        assert!(frame_has_text(&frame, 80, 12, "receipt rcpt-001"));
947        assert!(frame_has_text(&frame, 80, 12, "trace=trace-aaa"));
948        assert!(frame_has_text(&frame, 80, 12, "signature"));
949        assert!(frame_has_text(&frame, 80, 12, "transparency"));
950        assert!(frame_has_text(&frame, 80, 12, "attestation"));
951    }
952
953    #[test]
954    fn fail_verdict_surfaces_failure_class_in_verdict_row() {
955        let v = make_attestation_fail();
956        let mut pool = GraphemePool::new();
957        let mut frame = Frame::new(80, 18, &mut pool);
958        ReceiptVerifierPanel::new(&v).render(Rect::new(0, 0, 80, 18), &mut frame);
959        assert!(frame_has_text(&frame, 80, 18, "FAILED"));
960        assert!(frame_has_text(&frame, 80, 18, "failure_class=Attestation"));
961        // attestation layer surfaces its error_code on the layer row.
962        assert!(frame_has_text(&frame, 80, 18, "error_code=ATTEST_STALE"));
963    }
964
965    #[test]
966    fn show_posterior_path_renders_point_estimate() {
967        let v = make_pass();
968        let mut pool = GraphemePool::new();
969        let mut frame = Frame::new(80, 18, &mut pool);
970        ReceiptVerifierPanel::new(&v)
971            .show_posterior_path(true)
972            .render(Rect::new(0, 0, 80, 18), &mut frame);
973        assert!(frame_has_text(&frame, 80, 18, "posterior path:"));
974        assert!(frame_has_text(&frame, 80, 18, "point_estimate = 0.873"));
975        assert!(frame_has_text(
976            &frame,
977            80,
978            18,
979            "confidence_interval_95_lower = 0.81"
980        ));
981    }
982
983    #[test]
984    fn show_evidence_chain_renders_layer_checks() {
985        let v = make_pass();
986        let mut pool = GraphemePool::new();
987        let mut frame = Frame::new(80, 18, &mut pool);
988        ReceiptVerifierPanel::new(&v)
989            .show_evidence_chain(true)
990            .render(Rect::new(0, 0, 80, 18), &mut frame);
991        assert!(frame_has_text(&frame, 80, 18, "evidence chain:"));
992        assert!(frame_has_text(&frame, 80, 18, "mmr_inclusion"));
993        assert!(frame_has_text(&frame, 80, 18, "mmr_consistency"));
994        assert!(frame_has_text(&frame, 80, 18, "threshold_signature"));
995    }
996
997    #[test]
998    fn attestation_failure_triage_mentions_safe_mode() {
999        let v = make_attestation_fail();
1000        let mut pool = GraphemePool::new();
1001        let mut frame = Frame::new(80, 24, &mut pool);
1002        ReceiptVerifierPanel::new(&v).render(Rect::new(0, 0, 80, 24), &mut frame);
1003        assert!(frame_has_text(&frame, 80, 24, "incident triage"));
1004        assert!(frame_has_text(&frame, 80, 24, "SAFE-MODE"));
1005    }
1006
1007    #[test]
1008    fn warnings_block_renders_when_present() {
1009        let v = make_attestation_fail();
1010        let mut pool = GraphemePool::new();
1011        let mut frame = Frame::new(80, 24, &mut pool);
1012        ReceiptVerifierPanel::new(&v).render(Rect::new(0, 0, 80, 24), &mut frame);
1013        assert!(frame_has_text(&frame, 80, 24, "warnings:"));
1014        assert!(frame_has_text(&frame, 80, 24, "running in safe-mode"));
1015    }
1016
1017    #[test]
1018    fn empty_receipt_id_still_renders_provenance_dash() {
1019        let v = ReceiptVerdict::skeleton("rcpt-empty", true);
1020        let mut pool = GraphemePool::new();
1021        let mut frame = Frame::new(80, 10, &mut pool);
1022        ReceiptVerifierPanel::new(&v).render(Rect::new(0, 0, 80, 10), &mut frame);
1023        // Empty trace/decision/policy → rendered as `-`.
1024        assert!(frame_has_text(&frame, 80, 10, "trace=-"));
1025        assert!(frame_has_text(&frame, 80, 10, "decision=-"));
1026        assert!(frame_has_text(&frame, 80, 10, "policy=-"));
1027    }
1028
1029    #[test]
1030    fn tiny_area_does_not_panic() {
1031        let v = make_pass();
1032        let mut pool = GraphemePool::new();
1033        let mut frame = Frame::new(3, 2, &mut pool);
1034        ReceiptVerifierPanel::new(&v).render(Rect::new(0, 0, 3, 2), &mut frame);
1035        let mut frame = Frame::new(1, 1, &mut pool);
1036        ReceiptVerifierPanel::new(&v).render(Rect::new(0, 0, 1, 1), &mut frame);
1037    }
1038
1039    #[test]
1040    fn min_height_grows_with_options() {
1041        let v = make_pass();
1042        let base = ReceiptVerifierPanel::new(&v).min_height();
1043        let with_post = ReceiptVerifierPanel::new(&v)
1044            .show_posterior_path(true)
1045            .min_height();
1046        assert!(
1047            with_post > base,
1048            "posterior path should increase min_height"
1049        );
1050        let with_chain = ReceiptVerifierPanel::new(&v)
1051            .show_evidence_chain(true)
1052            .min_height();
1053        assert!(
1054            with_chain > base,
1055            "evidence chain should increase min_height"
1056        );
1057    }
1058
1059    /// Selftest: the canonical verifier output JSON (lifted verbatim from
1060    /// `verify_receipt.sh selftest`) deserialises cleanly into [`ReceiptVerdict`]
1061    /// when the caller plumbs a serde_json pass through the data model.
1062    #[test]
1063    fn canonical_verifier_pass_json_round_trips_through_data_model() {
1064        let pass_json = r#"{
1065            "receipt_id":"rcpt-001","trace_id":"trace-aaa","decision_id":"dec-bbb",
1066            "policy_id":"pol-ccc","verification_timestamp_ns":1716000000000000000,
1067            "passed":true,"failure_class":null,"exit_code":0,
1068            "signature":{"passed":true,"error_code":null,"checks":[
1069                {"check":"threshold_signature","outcome":"pass","error_code":null,"detail":"3/3 signers"}
1070            ]},
1071            "transparency":{"passed":true,"error_code":null,"checks":[
1072                {"check":"mmr_inclusion","outcome":"pass","error_code":null,"detail":"leaf 41 under root r9"},
1073                {"check":"mmr_consistency","outcome":"pass","error_code":null,"detail":"c0->c1 consistent"}
1074            ]},
1075            "attestation":{"passed":true,"error_code":null,"checks":[]},
1076            "warnings":[],"logs":[]
1077        }"#;
1078        let v: serde_json::Value = serde_json::from_str(pass_json).unwrap();
1079        // Hand-marshal the JSON value into our data model — this also
1080        // doubles as the canonical reference adapter for callers.
1081        let verdict = verdict_from_json(&v).expect("canonical JSON should parse");
1082        assert_eq!(verdict.receipt_id, "rcpt-001");
1083        assert!(verdict.passed);
1084        assert_eq!(verdict.failure_class, None);
1085        assert_eq!(verdict.signature.checks.len(), 1);
1086        assert_eq!(verdict.transparency.checks.len(), 2);
1087        assert_eq!(verdict.transparency.checks[1].check, "mmr_consistency");
1088    }
1089
1090    /// Test-only adapter from the verifier's JSON Value into [`ReceiptVerdict`].
1091    /// Kept in tests (not the public API) so the widget stays serde-free; this
1092    /// also doubles as a worked example for downstream callers.
1093    fn verdict_from_json(v: &serde_json::Value) -> Option<ReceiptVerdict> {
1094        fn layer(v: &serde_json::Value) -> LayerVerdict {
1095            let passed = v.get("passed").and_then(|x| x.as_bool()).unwrap_or(false);
1096            let error_code = v
1097                .get("error_code")
1098                .and_then(|x| x.as_str())
1099                .map(String::from);
1100            let checks = v
1101                .get("checks")
1102                .and_then(|x| x.as_array())
1103                .map(|arr| {
1104                    arr.iter()
1105                        .map(|c| CheckEntry {
1106                            check: c
1107                                .get("check")
1108                                .and_then(|x| x.as_str())
1109                                .unwrap_or("")
1110                                .to_string(),
1111                            outcome: CheckOutcome::parse(
1112                                c.get("outcome").and_then(|x| x.as_str()).unwrap_or(""),
1113                            ),
1114                            error_code: c
1115                                .get("error_code")
1116                                .and_then(|x| x.as_str())
1117                                .map(String::from),
1118                            detail: c
1119                                .get("detail")
1120                                .and_then(|x| x.as_str())
1121                                .unwrap_or("")
1122                                .to_string(),
1123                        })
1124                        .collect()
1125                })
1126                .unwrap_or_default();
1127            LayerVerdict {
1128                passed,
1129                error_code,
1130                checks,
1131            }
1132        }
1133        Some(ReceiptVerdict {
1134            receipt_id: v.get("receipt_id")?.as_str()?.to_string(),
1135            trace_id: v
1136                .get("trace_id")
1137                .and_then(|x| x.as_str())
1138                .unwrap_or("")
1139                .to_string(),
1140            decision_id: v
1141                .get("decision_id")
1142                .and_then(|x| x.as_str())
1143                .unwrap_or("")
1144                .to_string(),
1145            policy_id: v
1146                .get("policy_id")
1147                .and_then(|x| x.as_str())
1148                .unwrap_or("")
1149                .to_string(),
1150            verification_timestamp_ns: v
1151                .get("verification_timestamp_ns")
1152                .and_then(|x| x.as_u64())
1153                .unwrap_or(0),
1154            passed: v.get("passed").and_then(|x| x.as_bool()).unwrap_or(false),
1155            failure_class: v
1156                .get("failure_class")
1157                .and_then(|x| x.as_str())
1158                .and_then(FailureClass::parse),
1159            exit_code: v.get("exit_code").and_then(|x| x.as_i64()).unwrap_or(0) as i32,
1160            signature: v.get("signature").map(layer).unwrap_or_default(),
1161            transparency: v.get("transparency").map(layer).unwrap_or_default(),
1162            attestation: v.get("attestation").map(layer).unwrap_or_default(),
1163            warnings: v
1164                .get("warnings")
1165                .and_then(|x| x.as_array())
1166                .map(|arr| {
1167                    arr.iter()
1168                        .filter_map(|w| w.as_str().map(String::from))
1169                        .collect()
1170                })
1171                .unwrap_or_default(),
1172            posterior_snapshot: None,
1173        })
1174    }
1175}