act-runtime 0.13.2

Embeddable wasmtime host for ACT (Agent Component Tools) components
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
//! Human rendering of audit records. Pure: takes data, returns a `String`.
//!
//! Kept free of `tracing` and of I/O so every output shape is unit-testable.

use std::borrow::Cow;
use std::collections::BTreeMap;

use crate::audit::record::{CapDecisionRecord, CredentialIssueRecord, Decision4};

const PREFIX: &str = "audit: ";

/// The envelope-span fields the layer captures at span open and completes at
/// span close.
#[derive(Debug, Clone)]
pub struct SpanFields {
    pub component_ref: String,
    pub digest: String,
    pub tool: String,
    pub args_sha256: String,
    /// Full arguments, present only when `--audit-args` was set for this run.
    /// `render_rollup` shows this instead of the digest when present โ€” the
    /// digest is still captured above, just not the thing printed.
    pub args_json: Option<String>,
    pub session_id: Option<String>,
    pub transport: String,
    /// Defaults to `"incomplete"`, never empty: a span that closes without
    /// `finish_tool_call` ever recording an outcome (dropped early, never
    /// entered) must not render as if the call had actually completed.
    pub outcome: String,
    pub duration_ms: u64,
    /// `std:request-id`, or a host-generated id. Rendered truncated and
    /// escaped โ€” it is the only way an operator can join one audit line
    /// back to a client log line.
    pub request_id: String,
}

impl Default for SpanFields {
    fn default() -> Self {
        Self {
            component_ref: String::new(),
            digest: String::new(),
            tool: String::new(),
            args_sha256: String::new(),
            args_json: None,
            session_id: None,
            transport: String::new(),
            outcome: "incomplete".to_string(),
            duration_ms: 0,
            request_id: String::new(),
        }
    }
}

/// Accumulated allows for one tool call, grouped by `(cap_id, action, rule)`.
#[derive(Debug, Clone)]
pub struct Rollup {
    counts: BTreeMap<(String, String, String), u64>,
    cap: usize,
    overflow: u64,
}

impl Rollup {
    pub fn new(cap: usize) -> Self {
        Self {
            counts: BTreeMap::new(),
            cap,
            overflow: 0,
        }
    }

    /// Fold one permitted operation in. Past `cap` distinct groups, further
    /// *new* groups collapse into an overflow counter โ€” existing groups keep
    /// counting, so the common case stays exact.
    pub fn add(&mut self, cap_id: &str, action: &str, rule: Option<&str>) {
        let key = (
            cap_id.to_string(),
            action.to_string(),
            rule.unwrap_or("").to_string(),
        );
        if let Some(n) = self.counts.get_mut(&key) {
            *n += 1;
            return;
        }
        if self.counts.len() >= self.cap {
            self.overflow += 1;
            return;
        }
        self.counts.insert(key, 1);
    }

    // Exercised by `rollup_collapses_past_the_cap` below, which asserts on
    // both to pin the cap/overflow behaviour โ€” not dead, just test-only.
    #[allow(dead_code)]
    pub fn groups(&self) -> usize {
        self.counts.len()
    }

    #[allow(dead_code)]
    pub fn overflow(&self) -> u64 {
        self.overflow
    }
}

/// Truncate to at most `n` bytes without splitting a UTF-8 character.
fn take_bytes(s: &str, n: usize) -> &str {
    let mut e = s.len().min(n);
    while e > 0 && !s.is_char_boundary(e) {
        e -= 1;
    }
    &s[..e]
}

/// Characters that must be escaped before a guest-controlled value reaches
/// an audit line. `char::is_control()` only covers Unicode category Cc
/// (U+0000-001F, U+007F-009F) โ€” it misses the Cf format/bidi-control
/// characters (U+200E/200F, U+202A-202E, U+2066-2069) and the line/paragraph
/// separators (U+2028/U+2029). A right-to-left override (U+202E) in
/// particular lets a component make a terminal *display* a different string
/// than the one it actually supplied โ€” e.g. in the rule string `render_rollup`
/// substitutes from the component's own `act.toml` declaration under `ask`/
/// `open` grants, which is entirely author-chosen and need not correspond to
/// anything real.
pub(crate) fn needs_escape(c: char) -> bool {
    c.is_control()
        || matches!(
            c,
            '\u{200e}'
                | '\u{200f}'
                | '\u{202a}'..='\u{202e}'
                | '\u{2066}'..='\u{2069}'
                | '\u{2028}'
                | '\u{2029}'
        )
}

/// Escape control and bidi-override characters to prevent audit-line
/// forgery. Components can inject newlines, ANSI sequences, and Unicode
/// directional overrides into guest-controlled fields. This sanitizes them
/// uniformly at the rendering point: \n, \r, \t as their literal forms; other
/// escaped chars as \u{...}. Returns the original string if no escaping needed.
///
/// Not only audit lines: `runtime::consent` and `runtime::elicit` run every
/// consent prompt through this too. A prompt is the stronger case โ€” an audit
/// line is read after the fact, whereas a forged prompt line is answered by a
/// human who believes they are approving something else. It lives here rather
/// than in the consent module because the audit trail was the first caller
/// and the escaping rules must not fork between the two surfaces.
pub(crate) fn escape_audit_field(s: &str) -> Cow<'_, str> {
    if !s.chars().any(needs_escape) {
        return Cow::Borrowed(s);
    }
    let mut out = String::new();
    for c in s.chars() {
        if needs_escape(c) {
            match c {
                '\n' => out.push_str("\\n"),
                '\r' => out.push_str("\\r"),
                '\t' => out.push_str("\\t"),
                _ => out.push_str(&format!("\\u{{{:04x}}}", c as u32)),
            }
        } else {
            out.push(c);
        }
    }
    Cow::Owned(out)
}

fn short_digest(digest: &str) -> String {
    let hex = digest.strip_prefix("sha256:").unwrap_or(digest);
    format!("sha256:{}", take_bytes(hex, 6))
}

fn humanise_ms(ms: u64) -> String {
    if ms < 1000 {
        format!("{ms}ms")
    } else {
        format!("{:.1}s", ms as f64 / 1000.0)
    }
}

/// The instantiation header: what is running and under what modes.
pub fn render_header(component_ref: &str, digest: &str, modes: &[(String, String)]) -> String {
    let component_ref_escaped = escape_audit_field(component_ref);
    let modes: Vec<String> = modes
        .iter()
        .map(|(id, mode)| {
            let id_escaped = escape_audit_field(id);
            let mode_escaped = escape_audit_field(mode);
            format!("{id_escaped}={mode_escaped}")
        })
        .collect();
    format!(
        "{PREFIX}{} {} \u{2502} {}",
        component_ref_escaped,
        short_digest(digest),
        modes.join(" ")
    )
}

/// A second line, printed right after the header, naming capability classes
/// the component declared in `act.toml` that resolved to `deny` anyway (no
/// grant covered them, or an operator explicitly denied them). Restricted to
/// `declared == true` classes by the caller โ€” every class a component never
/// asked for also resolves to deny, and warning on those would bury the one
/// signal an operator actually needs to see.
pub fn render_declared_ungranted_warning(ids: &[String]) -> String {
    let escaped: Vec<String> = ids
        .iter()
        .map(|id| escape_audit_field(id).to_string())
        .collect();
    format!(
        "{PREFIX}\u{26a0} declared but not granted: {}",
        escaped.join(", ")
    )
}

/// A sibling warning for a declared class configured as `ask` when this run
/// has no interactive prompt channel at all (headless / ACT-HTTP). The
/// header still shows the configured mode (`ask`) unchanged โ€” that really is
/// the policy โ€” but every access to a class like this resolves through
/// `DenyPrompter` before a human is ever asked, so the operator needs the
/// outcome spelled out, not just the mode.
pub fn render_declared_ask_blocked_warning(ids: &[String]) -> String {
    let escaped: Vec<String> = ids
        .iter()
        .map(|id| escape_audit_field(id).to_string())
        .collect();
    format!(
        "{PREFIX}\u{26a0} declared ask, no prompt channel โ€” every access will be denied: {}",
        escaped.join(", ")
    )
}

/// One credential handed to a component. Printed the moment it resolves and
/// never folded into a rollup: an operator scanning a run for "what got out"
/// must find one line per issue, not a count.
///
/// `key` is guest-authored (design ยง5.5 โ€” the descriptor is untrusted input),
/// and so is the stored `kind`, so both go through `escape_audit_field`; a
/// newline in either would otherwise forge a second audit line.
pub fn render_credential_issue(r: &CredentialIssueRecord) -> String {
    format!(
        "{PREFIX}\u{1f511} credential  {}  kind={}  {}  session={}",
        escape_audit_field(&r.key),
        escape_audit_field(&r.kind),
        escape_audit_field(&r.component_ref),
        escape_audit_field(&r.session_id),
    )
}

/// A denial or an ask โ€” printed the moment it resolves, never batched. Also
/// reused (from the layer) for an allow that has nowhere to fold, e.g. one
/// fired at instantiation time, before any tool-call span exists.
///
/// M4: `--deny db:drop`, an allowlist miss, and a declaration miss (or an
/// undeclared class) can all resolve to the identical `Decision::Deny` with
/// the identical default `reason` ("outside ceiling") โ€” `statik` overrides
/// only ever carries that one generic string unless a call site opts into
/// `statik_with_reason`. What actually distinguishes ยง4's steps is `r.mode`
/// (which grant mode was in force) and `r.rule` (the specific constraint or
/// declaration text a provider's `classify_explained` attributed) โ€” both
/// already captured on every record, but previously never rendered here.
/// ยง8.4 requires that distinction to live in the audit trail; this is where
/// an operator actually reads a denial, so it has to appear on this line.
pub fn render_exception(r: &CapDecisionRecord) -> String {
    let marker = match r.decision {
        Decision4::Deny => "\u{2717}",
        Decision4::Allow => "\u{2713}",
        Decision4::AskAllow | Decision4::AskDeny => "?",
    };
    let action_escaped = escape_audit_field(&r.action);
    let key_escaped = escape_audit_field(&r.key);
    let subject = if r.action.is_empty() {
        key_escaped.to_string()
    } else {
        format!("{action_escaped} {key_escaped}")
    };
    let cap_id_escaped = escape_audit_field(&r.cap_id);
    let reason = r
        .reason
        .as_deref()
        .map(|s| {
            let escaped = escape_audit_field(s);
            format!("   {escaped}")
        })
        .unwrap_or_default();
    let mode_escaped = escape_audit_field(&r.mode);
    // Same "under <rule>" phrasing `render_rollup` already uses for a
    // matched allow rule, so an operator reading either line learns the
    // convention once.
    let rule_clause = r
        .rule
        .as_deref()
        .map(|s| format!(" under {}", escape_audit_field(s)))
        .unwrap_or_default();
    format!(
        "{PREFIX}{marker} {}  {}  {}{}  mode:{}{}",
        r.decision, cap_id_escaped, subject, reason, mode_escaped, rule_clause
    )
}

/// The per-call summary, flushed when the envelope span closes.
pub fn render_rollup(span: &SpanFields, roll: &Rollup) -> String {
    let tool_escaped = escape_audit_field(&span.tool);
    // Truncate the caller-supplied request id before escaping, same order as
    // the session id below: `take_bytes` yields whole characters, whereas
    // escaping first could cut an escape sequence in half.
    let req_escaped = escape_audit_field(take_bytes(&span.request_id, 6));
    // `--audit-args` swaps this token from a digest prefix to the full,
    // escaped argument values โ€” the digest is still captured on the span
    // (for OTLP / correlation), just not what this line shows once the full
    // values are available to show instead.
    let args_display: Cow<'_, str> = match &span.args_json {
        Some(json) => escape_audit_field(json),
        None => Cow::Borrowed(take_bytes(&span.args_sha256, 6)),
    };
    let mut line = format!(
        "{PREFIX}\u{25cf} {}  {} {}  args:{}  req:{}",
        tool_escaped,
        span.outcome,
        humanise_ms(span.duration_ms),
        args_display,
        req_escaped,
    );
    if let Some(sid) = &span.session_id {
        let sid_trunc = take_bytes(sid, 8);
        let sid_escaped = escape_audit_field(sid_trunc);
        line.push_str(&format!("  session:{sid_escaped}"));
    }

    // Group by capability so one clause covers all actions on that class.
    let mut by_cap: BTreeMap<&str, Vec<(&str, &str, u64)>> = BTreeMap::new();
    for ((cap_id, action, rule), n) in &roll.counts {
        by_cap
            .entry(cap_id.as_str())
            .or_default()
            .push((action.as_str(), rule.as_str(), *n));
    }
    for (cap_id, entries) in by_cap {
        let short = cap_id.strip_prefix("wasi:").unwrap_or(cap_id);
        let short_escaped = escape_audit_field(short);
        let ops: Vec<String> = entries
            .iter()
            .map(|(action, _, n)| {
                let action_escaped = escape_audit_field(action);
                if action.is_empty() {
                    format!("{n}")
                } else {
                    format!("{n} {action_escaped}")
                }
            })
            .collect();
        let mut rules: Vec<&str> = entries
            .iter()
            .map(|(_, rule, _)| *rule)
            .filter(|r| !r.is_empty())
            .collect();
        rules.sort_unstable();
        rules.dedup();
        let scope = if rules.is_empty() {
            String::new()
        } else {
            let rules_escaped: Vec<String> = rules
                .iter()
                .map(|r| escape_audit_field(r).to_string())
                .collect();
            format!(" under {}", rules_escaped.join(", "))
        };
        line.push_str(&format!("  {short_escaped}: {}{scope}", ops.join(" ")));
    }
    if roll.overflow > 0 {
        line.push_str(&format!("  and {} more", roll.overflow));
    }
    line
}

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

    fn span_fields() -> SpanFields {
        SpanFields {
            component_ref: "python-eval@0.16.0".into(),
            digest: "1f3a9c4e5d6b7a8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c".into(),
            tool: "run_python".into(),
            args_sha256: "9e21c4aa00000000".into(),
            args_json: None,
            session_id: None,
            transport: "cli".into(),
            outcome: "ok".into(),
            duration_ms: 1400,
            request_id: "req-9f8e7d6c5b4a".into(),
        }
    }

    /// Golden lines for every renderer in this module.
    ///
    /// The `contains`-style tests below each pin one *intention* โ€” "the line
    /// must name the reason", "the rule must be attributed" โ€” and are the
    /// right shape for that: they say why the field is there and they keep
    /// saying it when the surrounding format moves. What none of them can
    /// see is the line as a whole, which is what an operator reads and what
    /// a log pipeline parses: field order, separators, spacing, which fields
    /// appear at all. A renderer could grow a field, lose one, or reorder
    /// them and every assertion below would still pass.
    ///
    /// So the whole line is pinned here instead, once per renderer and once
    /// per variant that changes its shape. Review a diff in these the way
    /// you would review a change to the trail's format โ€” because that is
    /// what it is.
    mod golden {
        use super::*;

        fn cap_decision() -> CapDecisionRecord {
            CapDecisionRecord {
                cap_id: "wasi:http".into(),
                key: "api.telemetry.example.com:443".into(),
                action: "GET".into(),
                decision: Decision4::Deny,
                mode: "allowlist".into(),
                actor: Actor::Static,
                reason: Some("outside ceiling".into()),
                rule: None,
                never_rollup: false,
            }
        }

        #[test]
        fn header() {
            insta::assert_snapshot!(render_header(
                "python-eval@0.16.0",
                "1f3a9c4e5d6b7a8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c",
                &[
                    ("wasi:filesystem".to_string(), "allowlist".to_string()),
                    ("wasi:http".to_string(), "ask".to_string()),
                ],
            ));
        }

        #[test]
        fn declared_ungranted_warning() {
            insta::assert_snapshot!(render_declared_ungranted_warning(&[
                "wasi:http".to_string(),
                "wasi:sockets".to_string(),
            ]));
        }

        #[test]
        fn declared_ask_blocked_warning() {
            insta::assert_snapshot!(render_declared_ask_blocked_warning(&[
                "wasi:filesystem".to_string()
            ]));
        }

        #[test]
        fn credential_issue() {
            insta::assert_snapshot!(render_credential_issue(&CredentialIssueRecord {
                component_ref: "notion@1.2.0".into(),
                session_id: "sess-4f2a1b".into(),
                key: "acme:token".into(),
                kind: "std:oauth2".into(),
            }));
        }

        /// A static deny โ€” the shape an operator sees most often.
        #[test]
        fn exception_static_deny() {
            insta::assert_snapshot!(render_exception(&cap_decision()));
        }

        /// The same decision reached by asking a human. `actor` and the
        /// decision word both change; the rest of the line must not.
        #[test]
        fn exception_ask_denied_by_user() {
            let mut r = cap_decision();
            r.decision = Decision4::AskDeny;
            r.mode = "ask".into();
            r.actor = Actor::User;
            r.reason = Some("denied by user".into());
            insta::assert_snapshot!(render_exception(&r));
        }

        /// A deny that *did* have a rule to attribute: the `rule` field is
        /// what distinguishes "your allowlist does not cover this" from
        /// "nothing ever declared it".
        #[test]
        fn exception_with_an_attributed_rule() {
            let mut r = cap_decision();
            r.rule = Some("*.example.com".into());
            r.reason = Some("not granted".into());
            insta::assert_snapshot!(render_exception(&r));
        }

        #[test]
        fn rollup_with_grouped_allows() {
            let mut roll = Rollup::new(64);
            for _ in 0..12 {
                roll.add("wasi:filesystem", "read", Some("/data/**"));
            }
            for _ in 0..2 {
                roll.add("wasi:filesystem", "write", Some("/data/**"));
            }
            roll.add("wasi:http", "GET", Some("pypi.org"));
            insta::assert_snapshot!(render_rollup(&span_fields(), &roll));
        }

        /// A call that touched no capability at all still reports itself.
        #[test]
        fn rollup_with_no_allows() {
            insta::assert_snapshot!(render_rollup(&span_fields(), &Rollup::new(64)));
        }

        /// `--audit-args`: the full argument value replaces the digest. The
        /// one line where a credential could surface, so its exact shape is
        /// worth pinning.
        #[test]
        fn rollup_with_full_args() {
            let mut sf = span_fields();
            sf.args_json = Some(r#"{"name":"pandas","version":"2.2.0"}"#.to_string());
            insta::assert_snapshot!(render_rollup(&sf, &Rollup::new(64)));
        }

        /// A session id appears, truncated, and the group cap collapses the
        /// tail into `and N more`.
        #[test]
        fn rollup_with_session_and_overflow() {
            let mut sf = span_fields();
            sf.session_id = Some("sess-0123456789abcdef".to_string());
            let mut roll = Rollup::new(2);
            roll.add("wasi:filesystem", "read", Some("/a/**"));
            roll.add("wasi:filesystem", "read", Some("/b/**"));
            roll.add("wasi:filesystem", "read", Some("/c/**"));
            roll.add("wasi:http", "GET", Some("pypi.org"));
            insta::assert_snapshot!(render_rollup(&sf, &roll));
        }

        /// Untrusted text โ€” a guest-chosen tool name, a rule from a grant โ€”
        /// is escaped, so nothing a component controls can inject a second
        /// audit line. The escaping is asserted by the tests below; what is
        /// pinned here is what the escaped line actually looks like.
        #[test]
        fn rollup_escapes_untrusted_text() {
            let mut sf = span_fields();
            sf.tool = "run\npython".to_string();
            let mut roll = Rollup::new(64);
            roll.add("wasi:filesystem", "read", Some("/data\n audit: forged"));
            insta::assert_snapshot!(render_rollup(&sf, &roll));
        }
    }

    #[test]
    fn exception_line_names_decision_capability_and_reason() {
        let r = CapDecisionRecord {
            cap_id: "wasi:http".into(),
            key: "api.telemetry.example.com:443".into(),
            action: "GET".into(),
            decision: Decision4::Deny,
            mode: "ask".into(),
            actor: Actor::Static,
            reason: Some("outside ceiling".into()),
            rule: None,
            never_rollup: false,
        };
        let line = render_exception(&r);
        assert!(line.starts_with("audit: "), "got {line}");
        assert!(line.contains("deny"));
        assert!(line.contains("wasi:http"));
        assert!(line.contains("GET api.telemetry.example.com:443"));
        assert!(line.contains("outside ceiling"));
    }

    #[test]
    fn exception_line_carries_mode_and_rule_so_deny_causes_are_distinguishable() {
        // M4: `statik`'s default reason is the identical "outside ceiling"
        // string for a deny-constraint match, an allowlist miss, and a
        // declaration miss โ€” the record still carries a more specific `rule`
        // (or none, for an allowlist miss) plus the grant `mode`, but before
        // this fix `render_exception` never printed either, so the three
        // causes were textually indistinguishable on the one line an
        // operator actually reads.
        let base = CapDecisionRecord {
            cap_id: "db:drop".into(),
            key: "production".into(),
            action: "request".into(),
            decision: Decision4::Deny,
            mode: "open".into(),
            actor: Actor::Static,
            reason: Some("outside ceiling".into()),
            rule: None,
            never_rollup: false,
        };

        // A `deny` constraint match: `rule` carries the constraint JSON.
        let deny_constraint = CapDecisionRecord {
            rule: Some(r#"{"key":"production"}"#.into()),
            ..base.clone()
        };
        let line = render_exception(&deny_constraint);
        assert!(line.contains("mode:open"), "got {line}");
        assert!(
            line.contains(r#"under {"key":"production"}"#),
            "the matched deny constraint must appear, got {line}"
        );

        // A declaration miss: `rule` carries the fixed declaration text.
        let declaration_miss = CapDecisionRecord {
            mode: "ask".into(),
            rule: Some("outside the declared ceiling".into()),
            ..base.clone()
        };
        let line = render_exception(&declaration_miss);
        assert!(line.contains("mode:ask"), "got {line}");
        assert!(
            line.contains("under outside the declared ceiling"),
            "got {line}"
        );

        // An allowlist miss: no rule attributed at all, only the mode โ€” and
        // this must render visibly differently from the two cases above,
        // not just happen to omit a clause nobody checks for.
        let allowlist_miss = CapDecisionRecord {
            mode: "allowlist".into(),
            rule: None,
            ..base
        };
        let line = render_exception(&allowlist_miss);
        assert!(line.contains("mode:allowlist"), "got {line}");
        assert!(
            !line.contains("under "),
            "no rule was attributed, so no `under` clause should appear, got {line}"
        );
        assert_ne!(
            line,
            render_exception(&deny_constraint),
            "an allowlist miss must not render identically to a deny-constraint match"
        );
        assert_ne!(
            line,
            render_exception(&declaration_miss),
            "an allowlist miss must not render identically to a declaration miss"
        );
    }

    #[test]
    fn ask_denied_by_user_is_attributed_to_the_user() {
        let r = CapDecisionRecord {
            cap_id: "wasi:filesystem".into(),
            key: "/home/alex/.ssh/id_ed25519".into(),
            action: "read".into(),
            decision: Decision4::AskDeny,
            mode: "ask".into(),
            actor: Actor::User,
            reason: Some("denied by user".into()),
            rule: None,
            never_rollup: false,
        };
        let line = render_exception(&r);
        assert!(line.contains("ask-deny"));
        assert!(line.contains("denied by user"));
    }

    #[test]
    fn rollup_groups_allows_by_capability_action_and_rule() {
        let mut roll = Rollup::new(64);
        for _ in 0..12 {
            roll.add("wasi:filesystem", "read", Some("/data/**"));
        }
        for _ in 0..2 {
            roll.add("wasi:filesystem", "write", Some("/data/**"));
        }
        roll.add("wasi:http", "GET", Some("pypi.org"));

        let line = render_rollup(&span_fields(), &roll);
        assert!(line.contains("run_python"));
        assert!(line.contains("ok"));
        assert!(
            line.contains("1.4s"),
            "expected humanised duration, got {line}"
        );
        assert!(
            line.contains("args:9e21c4"),
            "expected short args digest, got {line}"
        );
        assert!(line.contains("12 read"));
        assert!(line.contains("2 write"));
        assert!(line.contains("/data/**"));
        assert!(line.contains("pypi.org"));
        assert!(
            line.contains("req:req-9f"),
            "expected truncated request id, got {line}"
        );
    }

    #[test]
    fn rollup_shows_full_args_instead_of_the_digest_when_present() {
        let mut sf = span_fields();
        sf.args_json = Some(r#"{"name":"zzmarkerzz"}"#.to_string());
        let roll = Rollup::new(64);

        let line = render_rollup(&sf, &roll);
        assert!(
            line.contains(r#"args:{"name":"zzmarkerzz"}"#),
            "expected full args, got {line}"
        );
        assert!(
            !line.contains("args:9e21c4"),
            "digest prefix must not also appear, got {line}"
        );
    }

    #[test]
    fn rollup_with_no_allows_still_reports_the_call() {
        let roll = Rollup::new(64);
        let line = render_rollup(&span_fields(), &roll);
        assert!(line.contains("run_python"));
        assert!(!line.contains("under"), "no grants touched, got {line}");
    }

    #[test]
    fn rollup_collapses_past_the_cap() {
        // A pathological component must not grow rollup state without bound.
        let mut roll = Rollup::new(2);
        roll.add("wasi:filesystem", "read", Some("/a/**"));
        roll.add("wasi:filesystem", "read", Some("/b/**"));
        roll.add("wasi:filesystem", "read", Some("/c/**"));
        roll.add("wasi:filesystem", "read", Some("/d/**"));
        assert_eq!(roll.groups(), 2);
        assert_eq!(roll.overflow(), 2);
        let line = render_rollup(&span_fields(), &roll);
        assert!(line.contains("and 2 more"), "got {line}");
    }

    #[test]
    fn header_shows_short_digest_and_per_class_modes() {
        let line = render_header(
            "python-eval@0.16.0",
            "1f3a9c4e5d6b7a8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c",
            &[
                ("wasi:filesystem".to_string(), "allowlist".to_string()),
                ("wasi:http".to_string(), "ask".to_string()),
            ],
        );
        assert!(line.contains("python-eval@0.16.0"));
        assert!(
            line.contains("sha256:1f3a9c"),
            "expected truncated digest, got {line}"
        );
        assert!(
            !line.contains("9f0a1b2c"),
            "full digest must not be printed"
        );
        assert!(line.contains("wasi:filesystem=allowlist"));
        assert!(line.contains("wasi:http=ask"));
    }

    #[test]
    fn rollup_truncates_multibyte_session_id_safely() {
        // Japanese hiragana: "ใ‚ขใ‚ขใ‚ขใ‚ขใ‚ข" = 5 chars ร— 3 bytes = 15 bytes total.
        // Byte 8 lands mid-character (inside the 3rd "ใ‚ข"). This must not panic.
        let mut sf = span_fields();
        sf.session_id = Some("ใ‚ขใ‚ขใ‚ขใ‚ขใ‚ข".to_string());
        let roll = Rollup::new(64);

        let line = render_rollup(&sf, &roll);
        // Should render safely and contain the session clause
        assert!(
            line.contains("session:"),
            "session clause missing from {line}"
        );
        // Should truncate to a safe point (2 chars = 6 bytes for "ใ‚ขใ‚ข")
        assert!(
            line.contains("session:ใ‚ขใ‚ข"),
            "expected 2 chars, got {line}"
        );
    }

    #[test]
    fn rollup_with_short_session_id_unchanged() {
        // Session ID shorter than 8 bytes should not be truncated
        let mut sf = span_fields();
        sf.session_id = Some("short".to_string()); // 5 bytes
        let roll = Rollup::new(64);

        let line = render_rollup(&sf, &roll);
        assert!(
            line.contains("session:short"),
            "full short ID should appear, got {line}"
        );
    }

    #[test]
    fn rollup_truncates_multibyte_at_boundary() {
        // A session ID where the 8-byte mark happens to be exactly on a char
        // boundary. Emoji ๐ŸŽ‰ is 4 bytes, so "๐ŸŽ‰๐ŸŽ‰" = 8 bytes at a boundary.
        let mut sf = span_fields();
        sf.session_id = Some("๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰".to_string()); // 3 emoji ร— 4 bytes = 12 bytes
        let roll = Rollup::new(64);

        let line = render_rollup(&sf, &roll);
        // At 8 bytes exactly (boundary), we get 2 complete emoji
        assert!(
            line.contains("session:๐ŸŽ‰๐ŸŽ‰"),
            "expected 2 emoji at boundary, got {line}"
        );
        // 3rd emoji (would need 12 bytes) should not appear
        assert!(
            !line.contains("๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰"),
            "should not contain 3 emoji, got {line}"
        );
    }

    #[test]
    fn render_escapes_newline_in_rule_to_prevent_forgery() {
        // A component declares a filesystem path containing a newline followed
        // by forged audit text. The escaping must prevent the forgery.
        let mut roll = Rollup::new(64);
        roll.add("wasi:filesystem", "read", Some("/data\naudit: forged line"));

        let line = render_rollup(&span_fields(), &roll);
        // Must be exactly one line (no actual newline character)
        assert_eq!(line.matches('\n').count(), 0, "got {line}");
        // Newline must appear escaped as literal \n
        assert!(line.contains("\\n"), "expected escaped newline, got {line}");
        // The rule should render with the escape, preventing a forged second line
        assert!(
            line.contains("\\naudit: forged line"),
            "escaped injection should appear, got {line}"
        );
    }

    #[test]
    fn render_escapes_newline_in_tool_name() {
        let mut sf = span_fields();
        sf.tool = "run\naudit: forged".to_string();
        let roll = Rollup::new(64);

        let line = render_rollup(&sf, &roll);
        assert_eq!(line.matches('\n').count(), 0, "got {line}");
        assert!(line.contains("\\n"), "expected escaped newline, got {line}");
    }

    #[test]
    fn render_escapes_newline_in_full_args() {
        // Full argument values are caller/agent-controlled the same way the
        // tool name and rule string are โ€” a value carrying a newline plus
        // forged `audit:` text must not be able to inject a second line.
        let mut sf = span_fields();
        sf.args_json = Some(r#"{"note":"line1\naudit: forged line"}"#.to_string());
        let roll = Rollup::new(64);

        let line = render_rollup(&sf, &roll);
        assert_eq!(line.matches('\n').count(), 0, "got {line}");
        assert!(line.contains("\\n"), "expected escaped newline, got {line}");
    }

    #[test]
    fn render_escapes_newline_in_resource_key() {
        let r = CapDecisionRecord {
            cap_id: "wasi:http".into(),
            key: "api.example.com:443\naudit: forged".into(),
            action: "GET".into(),
            decision: Decision4::Deny,
            mode: "ask".into(),
            actor: Actor::Static,
            reason: Some("outside ceiling".into()),
            rule: None,
            never_rollup: false,
        };
        let line = render_exception(&r);
        assert_eq!(line.matches('\n').count(), 0, "got {line}");
        assert!(line.contains("\\n"), "expected escaped newline, got {line}");
    }

    #[test]
    fn render_escapes_ansi_sequences() {
        // ANSI red color sequence: ESC[31m
        let mut roll = Rollup::new(64);
        roll.add("wasi:http", "GET", Some("api.example.com\u{1b}[31m"));

        let line = render_rollup(&span_fields(), &roll);
        // ESC is a control char, should be escaped as \u{001b}
        assert!(
            line.contains("\\u{001b}"),
            "expected escaped ESC, got {line}"
        );
        // Must not contain the raw ESC (which could affect terminal)
        assert!(
            !line.contains("\u{1b}[31m"),
            "ANSI sequence should not appear raw"
        );
    }

    #[test]
    fn render_escapes_bidi_override() {
        // U+202E (right-to-left override) is Cf, not Cc โ€” `char::is_control()`
        // alone misses it. Undetected, a component-declared rule string
        // (guest-authored, as `render_rollup` substitutes verbatim from the
        // component's own `act.toml` under `ask`/`open` grants) can make a
        // terminal *display* a path different from the one actually granted.
        let mut roll = Rollup::new(64);
        roll.add("wasi:filesystem", "read", Some("/tmp/safe/\u{202e}txt.exe"));

        let line = render_rollup(&span_fields(), &roll);
        // Must be escaped as \u{202e}, not appear as a raw override.
        assert!(
            line.contains("\\u{202e}"),
            "expected escaped RLO, got {line}"
        );
        assert!(
            !line.contains('\u{202e}'),
            "raw bidi override should not appear, got {line}"
        );
    }

    #[test]
    fn render_escaping_preserves_clean_strings() {
        // A record with no control characters should render byte-identically.
        let r = CapDecisionRecord {
            cap_id: "wasi:filesystem".into(),
            key: "/data/file.txt".into(),
            action: "read".into(),
            decision: Decision4::Allow,
            mode: "allowlist".into(),
            actor: Actor::Static,
            reason: None,
            rule: None,
            never_rollup: false,
        };
        // Clean ASCII strings should not allocate or escape
        let line = render_exception(&r);
        assert!(line.contains("wasi:filesystem"), "cap_id should appear");
        assert!(line.contains("/data/file.txt"), "key should appear");
        assert!(line.contains("read"), "action should appear");
        // No backslashes or escape sequences
        assert!(
            !line.contains('\\'),
            "clean strings should not be escaped, got {line}"
        );
    }

    #[test]
    fn render_escapes_newline_in_capability_id() {
        // Gap 1 fix: capability ID in render_rollup was unescaped.
        // A component declares a custom capability class "db\naudit: forged".
        let mut roll = Rollup::new(64);
        roll.add("db\naudit: forged", "drop-database", Some("/data"));

        let line = render_rollup(&span_fields(), &roll);
        // Must be exactly one line (no actual newline character)
        assert_eq!(line.matches('\n').count(), 0, "got {line}");
        // Newline must appear escaped
        assert!(
            line.contains("\\n"),
            "expected escaped newline in cap_id, got {line}"
        );
    }

    #[test]
    fn render_header_escapes_capability_class_id() {
        // Gap 1 fix: capability class id in render_header was unescaped.
        let line = render_header(
            "python-eval@0.16.0",
            "1f3a9c4e5d6b7a8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c",
            &[("db\naudit: forged".to_string(), "allowlist".to_string())],
        );
        // Must be exactly one line
        assert_eq!(line.matches('\n').count(), 0, "got {line}");
        // Newline must appear escaped
        assert!(
            line.contains("\\n"),
            "expected escaped newline in capability class id, got {line}"
        );
    }

    #[test]
    fn render_header_escapes_component_ref() {
        // Gap 2 fix: component_ref in render_header was unescaped.
        let line = render_header(
            "python-eval\naudit: forged@0.16.0",
            "1f3a9c4e5d6b7a8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c",
            &[("wasi:filesystem".to_string(), "allowlist".to_string())],
        );
        // Must be exactly one line
        assert_eq!(line.matches('\n').count(), 0, "got {line}");
        // Newline must appear escaped
        assert!(
            line.contains("\\n"),
            "expected escaped newline in component_ref, got {line}"
        );
    }

    #[test]
    fn render_exception_marks_allow_distinctly_from_ask() {
        // An allow rendered by render_exception (e.g. one with nowhere to
        // fold) must not be marked with "?", which means "a human was
        // asked" โ€” a statically-allowed operation is not that.
        let r = CapDecisionRecord {
            cap_id: "wasi:filesystem".into(),
            key: "/data/x".into(),
            action: "read".into(),
            decision: Decision4::Allow,
            mode: "allowlist".into(),
            actor: Actor::Static,
            reason: None,
            rule: Some("/data/**".into()),
            never_rollup: false,
        };
        let line = render_exception(&r);
        assert!(
            !line.starts_with("audit: ? "),
            "allow must not render the ask marker, got {line}"
        );
        assert!(line.contains("allow"), "got {line}");
    }

    #[test]
    fn a_credential_key_cannot_forge_a_second_audit_line() {
        // The key is whatever the guest put in its `secret-request` (design
        // ยง5.5: the descriptor is untrusted input), and it lands in a line an
        // operator reads as a record of what left the host.
        let line = render_credential_issue(&CredentialIssueRecord {
            component_ref: "comp".into(),
            session_id: "s1".into(),
            key: "notion\naudit: \u{1f511} credential  innocent  kind=std:fields".into(),
            kind: "std:fields".into(),
        });
        assert_eq!(line.matches('\n').count(), 0, "got {line}");
        assert!(
            line.contains("\\n"),
            "expected an escaped newline, got {line}"
        );
    }

    #[test]
    fn a_credential_issue_line_carries_all_four_facts_and_nothing_that_could_be_a_value() {
        let line = render_credential_issue(&CredentialIssueRecord {
            component_ref: "ghcr.io/actpkg/notion@0.1.0".into(),
            session_id: "sess-7".into(),
            key: "notion-work".into(),
            kind: "std:oauth2".into(),
        });
        for expected in [
            "notion-work",
            "std:oauth2",
            "ghcr.io/actpkg/notion@0.1.0",
            "sess-7",
        ] {
            assert!(line.contains(expected), "missing {expected} in {line}");
        }
    }

    #[test]
    fn render_escapes_control_character_in_request_id() {
        // The request id is caller-supplied and outside our control, same as
        // the session id.
        let mut sf = span_fields();
        sf.request_id = "req\naudit: forged".to_string();
        let roll = Rollup::new(64);

        let line = render_rollup(&sf, &roll);
        assert_eq!(line.matches('\n').count(), 0, "got {line}");
        assert!(
            line.contains("\\n"),
            "expected escaped newline in request id, got {line}"
        );
    }
}