car-verify 0.35.0

Formal verification for Agent IR — the novel contribution
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
//! Static information-flow + tool-sequence safety checks over a plan.
//!
//! Applies *Towards Verifiably Safe Tool Use for LLM Agents* (arXiv 2601.08012,
//! ICSE 2026 NIER) to CAR — see `docs/proposals/verifiable-tool-safety.md`. The
//! paper labels each tool with a **capability**, **confidentiality**, and
//! **trust level**, then enforces specifications on *data flows* and *tool
//! sequences* to catch system-level hazards (sensitive data reaching an
//! exfiltration sink, hazardous orderings) that per-action checks miss.
//!
//! CAR needs no new annotation layer for this: `car_ir::Action` already declares
//! its reads (`state_dependencies`) and writes (`expected_effects`), and the DAG
//! threads them — these are exactly the keys [`dependency_edges`] sequences on,
//! so taint propagated along them agrees with execution by construction. This
//! module propagates a confidentiality *taint* in the executor's own
//! topological order — reusing the happens-before machinery
//! [`crate::transaction`] established — and flags two hazard classes. The only
//! new input is a small per-tool label table, passed like `verify_with_schemas`
//! passes tool schemas (no IR/FFI struct change).

use crate::dag::transitive_ancestors;
use car_ir::{build_dag, Action, ActionProposal, ActionType};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Keys an action writes, as the **executor** sees them: `expected_effects`
/// plus a `StateWrite`'s `key` param. These are exactly the keys
/// [`dependency_edges`] treats as writes, so taint flows along the same edges
/// the runtime sequences on (not the transactional `write_set`, which the
/// executor does not order on — that is `transaction.rs`'s surface).
fn writes_of(a: &Action) -> Vec<String> {
    let mut w: Vec<String> = a.expected_effects.keys().cloned().collect();
    if a.action_type == ActionType::StateWrite {
        if let Some(k) = a.parameters.get("key").and_then(|v| v.as_str()) {
            if !w.iter().any(|e| e == k) {
                w.push(k.to_string());
            }
        }
    }
    w
}

/// Keys an action reads, as the executor sees them: `state_dependencies` — the
/// reads that create dependency edges.
fn reads_of(a: &Action) -> Vec<String> {
    a.state_dependencies.clone()
}

/// Data-sensitivity level a tool's output carries. Ordinal: `Public < Internal
/// < Secret`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum Confidentiality {
    #[default]
    Public,
    Internal,
    Secret,
}

/// Whether a tool's output is verified/trusted or untrusted (the paper's trust
/// level). An `Untrusted` action is treated as a sink for the sensitive-flow
/// check (untrusted code must not receive secrets), in addition to any tool
/// explicitly marked `sink`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum TrustLevel {
    #[default]
    Trusted,
    Untrusted,
}

/// The capability-enhanced-MCP labels for one tool.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ToolLabels {
    /// Capability class, e.g. `"fs_read"`, `"net_send"`, `"db_write"`. Used by
    /// the tool-sequence check.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capability: Option<String>,
    /// Sensitivity of the data this tool produces.
    #[serde(default)]
    pub confidentiality: Confidentiality,
    /// Whether this tool's output is trusted/verified.
    #[serde(default)]
    pub trust: TrustLevel,
    /// True if this tool is an exfiltration / externally-observable sink.
    #[serde(default)]
    pub sink: bool,
    /// True if this tool sanitizes/declassifies — its output taint resets to
    /// `Public` regardless of inputs.
    #[serde(default)]
    pub declassifier: bool,
}

/// Policy parameters for the checks.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowPolicy {
    /// Minimum confidentiality that, reaching a sink/untrusted action, is a
    /// violation. Default `Internal` (so `Internal` and `Secret` are guarded;
    /// `Public` never triggers).
    #[serde(default = "default_min_confidential")]
    pub min_confidential: Confidentiality,
    /// Forbidden ordered capability pairs `(before, after)`: a violation when an
    /// action whose capability is `before` is a DAG ancestor of one whose
    /// capability is `after`, with no declassifier in between.
    #[serde(default)]
    pub forbidden_sequences: Vec<(String, String)>,
}

fn default_min_confidential() -> Confidentiality {
    Confidentiality::Internal
}

impl Default for FlowPolicy {
    fn default() -> Self {
        Self {
            min_confidential: Confidentiality::Internal,
            forbidden_sequences: Vec::new(),
        }
    }
}

/// The class of a detected hazard.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FlowViolationKind {
    /// Confidential data reaches an exfiltration/untrusted sink.
    SensitiveToSink,
    /// A forbidden tool ordering occurs along the DAG.
    ForbiddenSequence,
}

/// A single detected hazard, with an actionable explanation and mitigation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowViolation {
    pub kind: FlowViolationKind,
    /// Action ids involved (the sink, or the ordered pair).
    pub actions: Vec<String>,
    /// The tainted state key, when the violation is about a data flow.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
    pub explanation: String,
    pub mitigation: String,
}

/// The result of the information-flow + sequence checks.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowReport {
    pub safe: bool,
    pub violations: Vec<FlowViolation>,
}

fn labels_for<'a>(
    action: &Action,
    labels: &'a HashMap<String, ToolLabels>,
) -> Option<&'a ToolLabels> {
    action.tool.as_deref().and_then(|t| labels.get(t))
}

/// Check a proposal for information-flow and tool-sequence hazards.
///
/// `labels` maps a tool name → its [`ToolLabels`]; tools absent from the map are
/// treated as `Public`/`Trusted`/non-sink (unlabeled = unconstrained, so an
/// empty map yields a trivially-safe report). Returns a [`FlowReport`].
pub fn check_information_flow(
    proposal: &ActionProposal,
    labels: &HashMap<String, ToolLabels>,
    policy: &FlowPolicy,
) -> FlowReport {
    let actions = &proposal.actions;
    let mut violations = Vec::new();

    // --- Check 1: confidentiality taint propagation over the DAG ---
    // taint[key] = highest confidentiality currently held by that key.
    let mut taint: HashMap<String, Confidentiality> = HashMap::new();
    for level in build_dag(actions) {
        for idx in level {
            let action = &actions[idx];
            let lbl = labels_for(action, labels).cloned().unwrap_or_default();

            // Input taint = max over keys this action reads.
            let input_taint = reads_of(action)
                .iter()
                .filter_map(|k| taint.get(k).copied())
                .max()
                .unwrap_or(Confidentiality::Public);

            // Sink / untrusted action receiving sensitive data is a violation.
            let is_sink = lbl.sink || lbl.trust == TrustLevel::Untrusted;
            if is_sink && input_taint >= policy.min_confidential {
                // Name the tainted key(s) the sink reads, for the message.
                let key = reads_of(action).into_iter().find(|k| {
                    taint.get(k).copied().unwrap_or(Confidentiality::Public)
                        >= policy.min_confidential
                });
                violations.push(FlowViolation {
                    kind: FlowViolationKind::SensitiveToSink,
                    actions: vec![action.id.clone()],
                    key: key.clone(),
                    explanation: format!(
                        "action '{}'{} consumes {:?}-level data{} — sensitive data must not reach an exfiltration/untrusted sink",
                        action.id,
                        action.tool.as_deref().map(|t| format!(" (tool '{t}')")).unwrap_or_default(),
                        input_taint,
                        key.as_deref().map(|k| format!(" via key '{k}'")).unwrap_or_default(),
                    ),
                    mitigation:
                        "route the data through a declassifier/sanitizer before this sink, or remove the dependency"
                            .to_string(),
                });
            }

            // Output taint: declassifier resets to Public; otherwise the max of
            // input taint and this tool's own confidentiality.
            let output_taint = if lbl.declassifier {
                Confidentiality::Public
            } else {
                input_taint.max(lbl.confidentiality)
            };
            for k in writes_of(action) {
                // A key's taint is the highest it has ever carried in this plan;
                // a non-declassifying writer can only raise it, a declassifier
                // sets it explicitly to Public for the keys it writes.
                if lbl.declassifier {
                    taint.insert(k, Confidentiality::Public);
                } else {
                    let e = taint.entry(k).or_insert(Confidentiality::Public);
                    if output_taint > *e {
                        *e = output_taint;
                    }
                }
            }
        }
    }

    // --- Check 2: forbidden tool-sequence (ordering) constraints ---
    if !policy.forbidden_sequences.is_empty() {
        let ancestors = transitive_ancestors(actions);
        let cap = |i: usize| labels_for(&actions[i], labels).and_then(|l| l.capability.clone());
        for after_idx in 0..actions.len() {
            let Some(after_cap) = cap(after_idx) else {
                continue;
            };
            for &before_idx in &ancestors[after_idx] {
                let Some(before_cap) = cap(before_idx) else {
                    continue;
                };
                let forbidden = policy
                    .forbidden_sequences
                    .iter()
                    .any(|(b, a)| *b == before_cap && *a == after_cap);
                if !forbidden {
                    continue;
                }
                // A declassifier strictly between them clears the hazard.
                let cleared = ancestors[after_idx].iter().any(|&mid| {
                    mid != before_idx
                        && ancestors[mid].contains(&before_idx)
                        && labels_for(&actions[mid], labels)
                            .map(|l| l.declassifier)
                            .unwrap_or(false)
                });
                if cleared {
                    continue;
                }
                violations.push(FlowViolation {
                    kind: FlowViolationKind::ForbiddenSequence,
                    actions: vec![
                        actions[before_idx].id.clone(),
                        actions[after_idx].id.clone(),
                    ],
                    key: None,
                    explanation: format!(
                        "forbidden ordering: '{}' ({before_cap}) happens-before '{}' ({after_cap})",
                        actions[before_idx].id, actions[after_idx].id
                    ),
                    mitigation:
                        "insert a declassifier/sanitizer between them, or break the dependency"
                            .to_string(),
                });
            }
        }
    }

    FlowReport {
        safe: violations.is_empty(),
        violations,
    }
}

// --- Slice 2: enforcement ---------------------------------------------------
//
// `check_information_flow` *detects* hazards; on its own that's advisory. The
// paper's goal is "proactive guardrails ... reducing dependence on user
// confirmation, making autonomy a deliberate design choice." This maps each
// violation class to an enforcement action so the runtime blocks the clear
// hazards, escalates the ambiguous ones to a human, and stays autonomous
// otherwise. The mapping is pure; wiring `RequireApproval` to
// `car_policy::PermissionGate`'s HITL ledger is the engine step (see the
// proposal's later slices).

/// What to do about a detected flow hazard.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FlowAction {
    /// Proceed autonomously.
    Allow,
    /// Suspend autonomy pending a human decision (HITL).
    RequireApproval,
    /// Refuse outright.
    Block,
}

/// How each violation class is enforced. Defaults follow the paper's stance:
/// data exfiltration (`SensitiveToSink`) is unacceptable → `Block`; a forbidden
/// ordering is suspicious but may be legitimate → `RequireApproval`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowGatePolicy {
    #[serde(default = "default_sensitive_action")]
    pub on_sensitive_to_sink: FlowAction,
    #[serde(default = "default_sequence_action")]
    pub on_forbidden_sequence: FlowAction,
}

fn default_sensitive_action() -> FlowAction {
    FlowAction::Block
}
fn default_sequence_action() -> FlowAction {
    FlowAction::RequireApproval
}

impl Default for FlowGatePolicy {
    fn default() -> Self {
        Self {
            on_sensitive_to_sink: FlowAction::Block,
            on_forbidden_sequence: FlowAction::RequireApproval,
        }
    }
}

/// The enforcement decision over a [`FlowReport`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowGateDecision {
    /// The most severe action required (`Block` > `RequireApproval` > `Allow`).
    pub action: FlowAction,
    /// Violations that must block.
    pub blocked: Vec<FlowViolation>,
    /// Violations that require human approval.
    pub needs_approval: Vec<FlowViolation>,
    /// Human/agent-actionable summary.
    pub reason: String,
}

/// Map a [`FlowReport`] to an enforcement [`FlowGateDecision`] under `policy`.
/// The overall `action` is the most severe across violations; a safe report
/// (no violations) is `Allow`.
pub fn gate_flow(report: &FlowReport, policy: &FlowGatePolicy) -> FlowGateDecision {
    let mut blocked = Vec::new();
    let mut needs_approval = Vec::new();

    for v in &report.violations {
        let action = match v.kind {
            FlowViolationKind::SensitiveToSink => policy.on_sensitive_to_sink,
            FlowViolationKind::ForbiddenSequence => policy.on_forbidden_sequence,
        };
        match action {
            FlowAction::Block => blocked.push(v.clone()),
            FlowAction::RequireApproval => needs_approval.push(v.clone()),
            FlowAction::Allow => {}
        }
    }

    let action = if !blocked.is_empty() {
        FlowAction::Block
    } else if !needs_approval.is_empty() {
        FlowAction::RequireApproval
    } else {
        FlowAction::Allow
    };

    let reason = match action {
        FlowAction::Block => format!(
            "blocked: {} flow hazard(s) must not run ({} also need approval)",
            blocked.len(),
            needs_approval.len()
        ),
        FlowAction::RequireApproval => format!(
            "{} flow hazard(s) require human approval before running",
            needs_approval.len()
        ),
        FlowAction::Allow => "no flow hazards — may proceed".to_string(),
    };

    FlowGateDecision {
        action,
        blocked,
        needs_approval,
        reason,
    }
}

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

    // Reads become `state_dependencies` and writes become `expected_effects` —
    // the keys the executor (and `dependency_edges`) actually sequence on, so the
    // taint analysis and the DAG agree.
    fn action(id: &str, tool: &str, reads: &[&str], writes: &[&str]) -> Action {
        let effects: serde_json::Map<String, serde_json::Value> =
            writes.iter().map(|w| (w.to_string(), json!("v"))).collect();
        serde_json::from_value(json!({
            "type": "tool_call",
            "id": id,
            "tool": tool,
            "state_dependencies": reads,
            "expected_effects": effects,
        }))
        .unwrap()
    }

    fn proposal(actions: Vec<Action>) -> ActionProposal {
        serde_json::from_value(json!({ "actions": actions })).unwrap()
    }

    fn labels(pairs: Vec<(&str, ToolLabels)>) -> HashMap<String, ToolLabels> {
        pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect()
    }

    #[test]
    fn secret_reaching_sink_is_flagged() {
        // read_secret writes `s` (Secret); send reads `s` and is a sink.
        let p = proposal(vec![
            action("a1", "read_secret", &[], &["s"]),
            action("a2", "send", &["s"], &[]),
        ]);
        let lbls = labels(vec![
            (
                "read_secret",
                ToolLabels {
                    confidentiality: Confidentiality::Secret,
                    ..Default::default()
                },
            ),
            (
                "send",
                ToolLabels {
                    sink: true,
                    ..Default::default()
                },
            ),
        ]);
        let r = check_information_flow(&p, &lbls, &FlowPolicy::default());
        assert!(!r.safe);
        assert_eq!(r.violations.len(), 1);
        assert_eq!(r.violations[0].kind, FlowViolationKind::SensitiveToSink);
        assert_eq!(r.violations[0].key.as_deref(), Some("s"));
        assert_eq!(r.violations[0].actions, vec!["a2"]);
    }

    #[test]
    fn declassifier_between_clears_the_flow() {
        // read_secret -> sanitize (declassifier) -> send. The sink reads the
        // sanitized key, which is Public.
        let p = proposal(vec![
            action("a1", "read_secret", &[], &["s"]),
            action("a2", "sanitize", &["s"], &["clean"]),
            action("a3", "send", &["clean"], &[]),
        ]);
        let lbls = labels(vec![
            (
                "read_secret",
                ToolLabels {
                    confidentiality: Confidentiality::Secret,
                    ..Default::default()
                },
            ),
            (
                "sanitize",
                ToolLabels {
                    declassifier: true,
                    ..Default::default()
                },
            ),
            (
                "send",
                ToolLabels {
                    sink: true,
                    ..Default::default()
                },
            ),
        ]);
        let r = check_information_flow(&p, &lbls, &FlowPolicy::default());
        assert!(
            r.safe,
            "sanitized data reaching the sink is fine: {:?}",
            r.violations
        );
    }

    #[test]
    fn public_data_to_sink_is_safe() {
        let p = proposal(vec![
            action("a1", "read_public", &[], &["s"]),
            action("a2", "send", &["s"], &[]),
        ]);
        let lbls = labels(vec![
            (
                "read_public",
                ToolLabels {
                    confidentiality: Confidentiality::Public,
                    ..Default::default()
                },
            ),
            (
                "send",
                ToolLabels {
                    sink: true,
                    ..Default::default()
                },
            ),
        ]);
        assert!(check_information_flow(&p, &lbls, &FlowPolicy::default()).safe);
    }

    #[test]
    fn untrusted_action_counts_as_sink() {
        let p = proposal(vec![
            action("a1", "read_secret", &[], &["s"]),
            action("a2", "eval_untrusted", &["s"], &[]),
        ]);
        let lbls = labels(vec![
            (
                "read_secret",
                ToolLabels {
                    confidentiality: Confidentiality::Secret,
                    ..Default::default()
                },
            ),
            (
                "eval_untrusted",
                ToolLabels {
                    trust: TrustLevel::Untrusted,
                    ..Default::default()
                },
            ),
        ]);
        let r = check_information_flow(&p, &lbls, &FlowPolicy::default());
        assert!(!r.safe);
        assert_eq!(r.violations[0].kind, FlowViolationKind::SensitiveToSink);
    }

    #[test]
    fn taint_propagates_transitively() {
        // secret -> copy (carries taint to t) -> send reads t.
        let p = proposal(vec![
            action("a1", "read_secret", &[], &["s"]),
            action("a2", "copy", &["s"], &["t"]),
            action("a3", "send", &["t"], &[]),
        ]);
        let lbls = labels(vec![
            (
                "read_secret",
                ToolLabels {
                    confidentiality: Confidentiality::Secret,
                    ..Default::default()
                },
            ),
            ("copy", ToolLabels::default()), // public tool, but carries input taint forward
            (
                "send",
                ToolLabels {
                    sink: true,
                    ..Default::default()
                },
            ),
        ]);
        let r = check_information_flow(&p, &lbls, &FlowPolicy::default());
        assert!(!r.safe, "taint must flow through the intermediate copy");
        assert_eq!(r.violations[0].actions, vec!["a3"]);
    }

    #[test]
    fn forbidden_sequence_flagged_by_ancestry() {
        // secret_read happens-before net_send via a dependency.
        let p = proposal(vec![
            action("a1", "reader", &[], &["x"]),
            action("a2", "sender", &["x"], &[]),
        ]);
        let lbls = labels(vec![
            (
                "reader",
                ToolLabels {
                    capability: Some("secret_read".into()),
                    ..Default::default()
                },
            ),
            (
                "sender",
                ToolLabels {
                    capability: Some("net_send".into()),
                    ..Default::default()
                },
            ),
        ]);
        let policy = FlowPolicy {
            forbidden_sequences: vec![("secret_read".into(), "net_send".into())],
            ..Default::default()
        };
        let r = check_information_flow(&p, &lbls, &policy);
        assert!(!r.safe);
        assert_eq!(r.violations[0].kind, FlowViolationKind::ForbiddenSequence);
        assert_eq!(r.violations[0].actions, vec!["a1", "a2"]);
    }

    #[test]
    fn unordered_capabilities_are_not_a_sequence_violation() {
        // No dependency between them (disjoint keys) → not happens-before.
        let p = proposal(vec![
            action("a1", "reader", &[], &["x"]),
            action("a2", "sender", &["y"], &[]),
        ]);
        let lbls = labels(vec![
            (
                "reader",
                ToolLabels {
                    capability: Some("secret_read".into()),
                    ..Default::default()
                },
            ),
            (
                "sender",
                ToolLabels {
                    capability: Some("net_send".into()),
                    ..Default::default()
                },
            ),
        ]);
        let policy = FlowPolicy {
            forbidden_sequences: vec![("secret_read".into(), "net_send".into())],
            ..Default::default()
        };
        // The sequence check requires ancestry; with no edge there's no
        // happens-before, so no sequence violation.
        let seq_violations = check_information_flow(&p, &lbls, &policy)
            .violations
            .into_iter()
            .filter(|v| v.kind == FlowViolationKind::ForbiddenSequence)
            .count();
        assert_eq!(seq_violations, 0);
    }

    #[test]
    fn empty_labels_is_trivially_safe() {
        let p = proposal(vec![action("a1", "anything", &["a"], &["b"])]);
        let r = check_information_flow(&p, &HashMap::new(), &FlowPolicy::default());
        assert!(r.safe);
    }

    #[test]
    fn internal_threshold_can_be_raised_to_secret_only() {
        // Internal data to a sink: a violation at default, but allowed when the
        // policy only guards Secret.
        let p = proposal(vec![
            action("a1", "read_internal", &[], &["s"]),
            action("a2", "send", &["s"], &[]),
        ]);
        let lbls = labels(vec![
            (
                "read_internal",
                ToolLabels {
                    confidentiality: Confidentiality::Internal,
                    ..Default::default()
                },
            ),
            (
                "send",
                ToolLabels {
                    sink: true,
                    ..Default::default()
                },
            ),
        ]);
        assert!(!check_information_flow(&p, &lbls, &FlowPolicy::default()).safe);
        let secret_only = FlowPolicy {
            min_confidential: Confidentiality::Secret,
            ..Default::default()
        };
        assert!(check_information_flow(&p, &lbls, &secret_only).safe);
    }

    // --- Slice 2: enforcement gate ---

    #[test]
    fn safe_report_gates_to_allow() {
        let report = FlowReport {
            safe: true,
            violations: vec![],
        };
        let d = gate_flow(&report, &FlowGatePolicy::default());
        assert_eq!(d.action, FlowAction::Allow);
        assert!(d.blocked.is_empty() && d.needs_approval.is_empty());
    }

    #[test]
    fn sensitive_to_sink_blocks_by_default() {
        let report = FlowReport {
            safe: false,
            violations: vec![FlowViolation {
                kind: FlowViolationKind::SensitiveToSink,
                actions: vec!["a2".into()],
                key: Some("s".into()),
                explanation: "x".into(),
                mitigation: "y".into(),
            }],
        };
        let d = gate_flow(&report, &FlowGatePolicy::default());
        assert_eq!(d.action, FlowAction::Block);
        assert_eq!(d.blocked.len(), 1);
    }

    #[test]
    fn forbidden_sequence_escalates_to_approval_by_default() {
        let report = FlowReport {
            safe: false,
            violations: vec![FlowViolation {
                kind: FlowViolationKind::ForbiddenSequence,
                actions: vec!["a1".into(), "a2".into()],
                key: None,
                explanation: "x".into(),
                mitigation: "y".into(),
            }],
        };
        let d = gate_flow(&report, &FlowGatePolicy::default());
        assert_eq!(d.action, FlowAction::RequireApproval);
        assert_eq!(d.needs_approval.len(), 1);
    }

    #[test]
    fn block_dominates_when_both_present() {
        let report = FlowReport {
            safe: false,
            violations: vec![
                FlowViolation {
                    kind: FlowViolationKind::ForbiddenSequence,
                    actions: vec![],
                    key: None,
                    explanation: "".into(),
                    mitigation: "".into(),
                },
                FlowViolation {
                    kind: FlowViolationKind::SensitiveToSink,
                    actions: vec![],
                    key: None,
                    explanation: "".into(),
                    mitigation: "".into(),
                },
            ],
        };
        let d = gate_flow(&report, &FlowGatePolicy::default());
        assert_eq!(d.action, FlowAction::Block);
        assert_eq!(d.blocked.len(), 1);
        assert_eq!(d.needs_approval.len(), 1);
    }

    #[test]
    fn policy_can_relax_sink_to_approval() {
        let report = FlowReport {
            safe: false,
            violations: vec![FlowViolation {
                kind: FlowViolationKind::SensitiveToSink,
                actions: vec![],
                key: None,
                explanation: "".into(),
                mitigation: "".into(),
            }],
        };
        let policy = FlowGatePolicy {
            on_sensitive_to_sink: FlowAction::RequireApproval,
            ..Default::default()
        };
        assert_eq!(
            gate_flow(&report, &policy).action,
            FlowAction::RequireApproval
        );
    }
}