car-engine 0.35.0

Core runtime engine for Common Agent Runtime
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
//! Information-flow admission gate + tool-label loading (EPIC A / A3+A4).
//!
//! `car_verify::check_information_flow` is a verified static check for data
//! exfiltration and forbidden tool orderings, but it was never called by
//! the runtime, and it needs per-tool *labels* (capability, confidentiality,
//! trust, sink) that nothing produced. This module supplies both halves:
//!
//! - **A3 — labels**: a built-in default label table for CAR's commodity
//!   tools, plus a `.car/tool-labels.json` loader so a project can declare
//!   which tools are sinks, which produce confidential data, and what tool
//!   orderings are forbidden.
//! - **A4 — the gate**: [`InformationFlowGate`], an [`crate::admission::AdmissionGate`]
//!   that runs `check_information_flow` → `gate_flow` on every admitted
//!   proposal, blocking exfiltration and escalating forbidden orderings to
//!   approval (which fails closed until A7 wires the approval transport).

use crate::admission::{AdmissionGate, GateContext, GateOutcome};
use car_ir::ActionProposal;
use car_verify::infoflow::{
    check_information_flow, gate_flow, Confidentiality, FlowAction, FlowGatePolicy, FlowPolicy,
    ToolLabels, TrustLevel,
};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::Path;

/// The deserialized `.car/tool-labels.json` document: per-tool labels plus
/// the flow policy (what counts as a hazard) and the gate policy (what to
/// do about each hazard class). Every field defaults, so a partial file is
/// valid.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ToolLabelConfig {
    /// Tool name → information-flow labels.
    #[serde(default)]
    pub labels: HashMap<String, ToolLabels>,
    /// What confidentiality reaching a sink is a violation, and which tool
    /// orderings are forbidden.
    #[serde(default)]
    pub flow_policy: FlowPolicy,
    /// How each hazard class is enforced (block / approve / allow).
    #[serde(default)]
    pub gate_policy: FlowGatePolicy,
}

/// Default information-flow labels for CAR's built-in commodity tools.
///
/// Conservative and capability-only: the network-reaching tools are marked
/// as exfiltration sinks (so any confidential data flowing into them is
/// caught), and the file/process tools get capability tags so forbidden
/// orderings can be expressed against them. Nothing is marked confidential
/// by default — a project declares which of *its* tools/sources produce
/// sensitive data in `.car/tool-labels.json`.
pub fn builtin_tool_labels() -> HashMap<String, ToolLabels> {
    fn sink(capability: &str) -> ToolLabels {
        ToolLabels {
            capability: Some(capability.to_string()),
            sink: true,
            ..Default::default()
        }
    }
    fn cap(capability: &str) -> ToolLabels {
        ToolLabels {
            capability: Some(capability.to_string()),
            ..Default::default()
        }
    }
    fn source(capability: &str, confidentiality: Confidentiality) -> ToolLabels {
        ToolLabels {
            capability: Some(capability.to_string()),
            confidentiality,
            ..Default::default()
        }
    }
    let mut m = HashMap::new();
    // Network-reaching tools are exfiltration sinks.
    m.insert("http_request".to_string(), sink("net_send"));
    m.insert("web_search".to_string(), sink("net_send"));
    m.insert("browser".to_string(), sink("net_send"));
    m.insert("search".to_string(), sink("net_send"));
    // Host-side Studio generators submit prompts to external services.
    m.insert("generate_music".to_string(), sink("net_send"));
    m.insert("generate_jingle".to_string(), sink("net_send"));
    m.insert("generate_studio_image".to_string(), sink("net_send"));
    m.insert("generate_song".to_string(), sink("net_send"));
    // Host automation can drive apps, clipboard, browsers, and messaging.
    m.insert("run_applescript".to_string(), sink("host_automation"));
    // Durable assistant memory persists across sessions and process restarts.
    m.insert("remember".to_string(), sink("persistent_memory"));
    m.insert(
        "recall".to_string(),
        source(
            "persistent_memory_read",
            car_verify::infoflow::Confidentiality::Internal,
        ),
    );
    // Vision tools read user/workspace images. OCR and classification output can
    // expose private screenshots, scans, photos, or generated artifacts.
    m.insert(
        "read_image_text".to_string(),
        source(
            "vision_read",
            car_verify::infoflow::Confidentiality::Internal,
        ),
    );
    m.insert(
        "classify_image".to_string(),
        source(
            "vision_read",
            car_verify::infoflow::Confidentiality::Internal,
        ),
    );
    // Filesystem + process tools: capability-tagged, not sinks.
    m.insert("read_file".to_string(), cap("fs_read"));
    m.insert("write_file".to_string(), cap("fs_write"));
    m.insert("edit_file".to_string(), cap("fs_write"));
    m.insert("list_dir".to_string(), cap("fs_read"));
    m.insert("find_files".to_string(), cap("fs_read"));
    m.insert("grep_files".to_string(), cap("fs_read"));
    m.insert("shell".to_string(), cap("process_exec"));
    m
}

fn merge_builtin_label(builtin: ToolLabels, project: ToolLabels) -> ToolLabels {
    let capability = builtin.capability.clone().or(project.capability);
    let confidentiality = std::cmp::max(builtin.confidentiality, project.confidentiality);
    let trust = if matches!(builtin.trust, TrustLevel::Untrusted)
        || matches!(project.trust, TrustLevel::Untrusted)
    {
        TrustLevel::Untrusted
    } else {
        TrustLevel::Trusted
    };

    ToolLabels {
        capability,
        confidentiality,
        trust,
        sink: builtin.sink || project.sink,
        declassifier: builtin.declassifier,
    }
}

fn merge_flow_policy(builtin: FlowPolicy, project: FlowPolicy) -> FlowPolicy {
    let mut forbidden_sequences = builtin.forbidden_sequences;
    forbidden_sequences.extend(project.forbidden_sequences);
    forbidden_sequences.sort();
    forbidden_sequences.dedup();

    FlowPolicy {
        min_confidential: std::cmp::min(builtin.min_confidential, project.min_confidential),
        forbidden_sequences,
    }
}

fn merge_gate_policy(builtin: FlowGatePolicy, project: FlowGatePolicy) -> FlowGatePolicy {
    FlowGatePolicy {
        on_sensitive_to_sink: std::cmp::max(
            builtin.on_sensitive_to_sink,
            project.on_sensitive_to_sink,
        ),
        on_forbidden_sequence: std::cmp::max(
            builtin.on_forbidden_sequence,
            project.on_forbidden_sequence,
        ),
    }
}

/// Load tool labels for a project, merging `.car/tool-labels.json` with the
/// built-in defaults.
///
/// `car_dir` is the project's `.car` directory; this reads
/// `car_dir/tool-labels.json` if present. Built-in labels are the base;
/// project labels can add new tools or strengthen built-ins, but cannot weaken
/// built-in sinks, capabilities, taint sources, trust labels, or enforcement
/// defaults. A missing file is not an error (returns builtins + default
/// policies); a malformed file *is* an error.
pub fn load_tool_labels(car_dir: impl AsRef<Path>) -> Result<ToolLabelConfig, FlowLoadError> {
    let mut config = ToolLabelConfig {
        labels: builtin_tool_labels(),
        flow_policy: FlowPolicy::default(),
        gate_policy: FlowGatePolicy::default(),
    };
    let path = car_dir.as_ref().join("tool-labels.json");
    if !path.exists() {
        return Ok(config);
    }
    let src = std::fs::read_to_string(&path).map_err(|e| FlowLoadError {
        message: format!("reading {}: {e}", path.display()),
    })?;
    let file: ToolLabelConfig = serde_json::from_str(&src).map_err(|e| FlowLoadError {
        message: format!("parsing {}: {e}", path.display()),
    })?;
    for (name, project_label) in file.labels {
        match config.labels.remove(&name) {
            Some(builtin_label) => {
                config
                    .labels
                    .insert(name, merge_builtin_label(builtin_label, project_label));
            }
            None => {
                config.labels.insert(name, project_label);
            }
        }
    }
    config.flow_policy = merge_flow_policy(config.flow_policy, file.flow_policy);
    config.gate_policy = merge_gate_policy(config.gate_policy, file.gate_policy);
    Ok(config)
}

/// An [`AdmissionGate`] that enforces information-flow safety: confidential
/// data must not reach an exfiltration sink, and forbidden tool orderings
/// are escalated to human approval.
pub struct InformationFlowGate {
    labels: HashMap<String, ToolLabels>,
    flow_policy: FlowPolicy,
    gate_policy: FlowGatePolicy,
}

impl InformationFlowGate {
    /// Build a gate from a resolved [`ToolLabelConfig`].
    pub fn new(config: ToolLabelConfig) -> Self {
        Self {
            labels: config.labels,
            flow_policy: config.flow_policy,
            gate_policy: config.gate_policy,
        }
    }

    /// Build a gate from the built-in defaults only.
    pub fn with_builtin_labels() -> Self {
        Self::new(ToolLabelConfig {
            labels: builtin_tool_labels(),
            ..Default::default()
        })
    }
}

#[async_trait::async_trait]
impl AdmissionGate for InformationFlowGate {
    fn name(&self) -> &str {
        "information_flow"
    }

    async fn check(&self, proposal: &ActionProposal, _ctx: &GateContext<'_>) -> GateOutcome {
        let report = check_information_flow(proposal, &self.labels, &self.flow_policy);
        if report.safe {
            return GateOutcome::Allow;
        }
        let decision = gate_flow(&report, &self.gate_policy);
        match decision.action {
            FlowAction::Allow => GateOutcome::Allow,
            FlowAction::Block => {
                let blocked: HashSet<String> = decision
                    .blocked
                    .iter()
                    .flat_map(|v| v.actions.iter().cloned())
                    .collect();
                GateOutcome::Reject {
                    blocked,
                    reason: decision.reason,
                }
            }
            FlowAction::RequireApproval => {
                let actions: HashSet<String> = decision
                    .needs_approval
                    .iter()
                    .flat_map(|v| v.actions.iter().cloned())
                    .collect();
                // Stable fingerprint over EVERY hazard (linus review C-8):
                // fingerprinting only the first hazard let one approval
                // admit hazards 2..n. Sorted for order independence, then
                // HASHED — the components carry model-chosen action ids
                // and state keys, so a delimiter-joined ledger key would
                // be forgeable by embedding the separator (same fix as
                // the intent gate; a ledger key is a security identity).
                let mut fps: Vec<String> = decision
                    .needs_approval
                    .iter()
                    .map(car_policy::flow_fingerprint)
                    .collect();
                fps.sort();
                fps.dedup();
                let fingerprint = if fps.is_empty() {
                    "flow:unknown".to_string()
                } else {
                    use sha2::Digest;
                    let canonical = serde_json::to_string(&fps).unwrap_or_default();
                    format!(
                        "flow:sha256:{:x}",
                        sha2::Sha256::digest(canonical.as_bytes())
                    )
                };
                GateOutcome::NeedsApproval {
                    actions,
                    fingerprint,
                    reason: decision.reason,
                }
            }
        }
    }
}

/// Error raised while loading `.car/tool-labels.json`.
#[derive(Debug, Clone)]
pub struct FlowLoadError {
    pub message: String,
}

impl fmt::Display for FlowLoadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "tool-labels load error: {}", self.message)
    }
}

impl std::error::Error for FlowLoadError {}

#[cfg(test)]
mod tests {
    use super::*;
    use car_ir::{Action, ActionType, FailureBehavior};

    fn tool_action(id: &str, tool: &str) -> Action {
        Action {
            id: id.to_string(),
            action_type: ActionType::ToolCall,
            tool: Some(tool.to_string()),
            parameters: HashMap::new(),
            preconditions: vec![],
            expected_effects: HashMap::new(),
            state_dependencies: vec![],
            read_set: vec![],
            write_set: vec![],
            assumptions: vec![],
            invocation_mode: Default::default(),
            idempotent: false,
            max_retries: 0,
            failure_behavior: FailureBehavior::Abort,
            timeout_ms: None,
            metadata: HashMap::new(),
        }
    }

    fn proposal(actions: Vec<Action>) -> ActionProposal {
        ActionProposal {
            id: "p".to_string(),
            source: "test".to_string(),
            actions,
            timestamp: chrono::Utc::now(),
            context: HashMap::new(),
        }
    }

    #[test]
    fn builtins_mark_network_tools_as_sinks() {
        let labels = builtin_tool_labels();
        assert!(labels.get("http_request").unwrap().sink);
        assert!(labels.get("web_search").unwrap().sink);
        assert!(labels.get("generate_music").unwrap().sink);
        assert!(labels.get("generate_jingle").unwrap().sink);
        assert!(labels.get("generate_studio_image").unwrap().sink);
        assert!(labels.get("generate_song").unwrap().sink);
        assert!(labels.get("run_applescript").unwrap().sink);
        assert!(labels.get("remember").unwrap().sink);
        assert!(labels.get("browser").unwrap().sink);
        assert!(!labels.get("read_file").unwrap().sink);
    }

    #[test]
    fn builtins_mark_recall_as_internal_source() {
        let labels = builtin_tool_labels();
        let recall = labels.get("recall").unwrap();
        assert_eq!(
            recall.confidentiality,
            car_verify::infoflow::Confidentiality::Internal
        );
        assert!(!recall.sink);
    }

    #[test]
    fn builtins_mark_vision_tools_as_internal_sources() {
        let labels = builtin_tool_labels();
        for name in ["read_image_text", "classify_image"] {
            let label = labels.get(name).unwrap();
            assert_eq!(
                label.confidentiality,
                car_verify::infoflow::Confidentiality::Internal,
                "{name} should carry internal taint"
            );
            assert!(!label.sink, "{name} is a source, not a sink");
        }
    }

    #[tokio::test]
    async fn clean_proposal_is_allowed() {
        let gate = InformationFlowGate::with_builtin_labels();
        let ctx_state = HashMap::new();
        let ctx_versions = HashMap::new();
        let ctx = GateContext {
            session_id: None,
            scope: None,
            state: &ctx_state,
            versions: &ctx_versions,
        };
        // read_file then http_request with no declared confidential data:
        // nothing sensitive flows, so it's safe.
        let p = proposal(vec![
            tool_action("a1", "read_file"),
            tool_action("a2", "http_request"),
        ]);
        assert!(matches!(gate.check(&p, &ctx).await, GateOutcome::Allow));
    }

    #[tokio::test]
    async fn confidential_to_sink_is_blocked() {
        // Label a custom source as Secret; it flows into http_request (a
        // sink) via a shared state key.
        let mut labels = builtin_tool_labels();
        labels.insert(
            "read_secret".to_string(),
            ToolLabels {
                capability: Some("fs_read".to_string()),
                confidentiality: car_verify::infoflow::Confidentiality::Secret,
                ..Default::default()
            },
        );
        let gate = InformationFlowGate::new(ToolLabelConfig {
            labels,
            ..Default::default()
        });

        // a1 reads a secret into key "data"; a2 (http_request sink) reads it.
        let mut a1 = tool_action("a1", "read_secret");
        a1.expected_effects = [("data".to_string(), serde_json::Value::from(1))].into();
        let mut a2 = tool_action("a2", "http_request");
        a2.state_dependencies = vec!["data".to_string()];

        let ctx_state = HashMap::new();
        let ctx_versions = HashMap::new();
        let ctx = GateContext {
            session_id: None,
            scope: None,
            state: &ctx_state,
            versions: &ctx_versions,
        };
        let outcome = gate.check(&proposal(vec![a1, a2]), &ctx).await;
        assert!(
            matches!(outcome, GateOutcome::Reject { .. }),
            "secret reaching a sink must be blocked, got {outcome:?}"
        );
    }

    #[tokio::test]
    async fn confidential_to_web_search_is_blocked() {
        let mut labels = builtin_tool_labels();
        labels.insert(
            "read_secret".to_string(),
            ToolLabels {
                capability: Some("fs_read".to_string()),
                confidentiality: car_verify::infoflow::Confidentiality::Secret,
                ..Default::default()
            },
        );
        let gate = InformationFlowGate::new(ToolLabelConfig {
            labels,
            ..Default::default()
        });

        let mut a1 = tool_action("a1", "read_secret");
        a1.expected_effects = [("query".to_string(), serde_json::Value::from(1))].into();
        let mut a2 = tool_action("a2", "web_search");
        a2.state_dependencies = vec!["query".to_string()];

        let ctx_state = HashMap::new();
        let ctx_versions = HashMap::new();
        let ctx = GateContext {
            session_id: None,
            scope: None,
            state: &ctx_state,
            versions: &ctx_versions,
        };
        let outcome = gate.check(&proposal(vec![a1, a2]), &ctx).await;
        assert!(
            matches!(outcome, GateOutcome::Reject { .. }),
            "secret reaching web_search must be blocked, got {outcome:?}"
        );
    }

    #[tokio::test]
    async fn recalled_memory_to_web_search_is_blocked_by_default() {
        let gate = InformationFlowGate::with_builtin_labels();
        let mut a1 = tool_action("a1", "recall");
        a1.expected_effects = [("memory_context".to_string(), serde_json::Value::from(1))].into();
        let mut a2 = tool_action("a2", "web_search");
        a2.state_dependencies = vec!["memory_context".to_string()];

        let ctx_state = HashMap::new();
        let ctx_versions = HashMap::new();
        let ctx = GateContext {
            session_id: None,
            scope: None,
            state: &ctx_state,
            versions: &ctx_versions,
        };
        let outcome = gate.check(&proposal(vec![a1, a2]), &ctx).await;
        assert!(
            matches!(outcome, GateOutcome::Reject { .. }),
            "recalled durable memory reaching web_search must be blocked, got {outcome:?}"
        );
    }

    #[tokio::test]
    async fn image_text_to_web_search_is_blocked_by_default() {
        let gate = InformationFlowGate::with_builtin_labels();
        let mut a1 = tool_action("a1", "read_image_text");
        a1.expected_effects = [("ocr_text".to_string(), serde_json::Value::from(1))].into();
        let mut a2 = tool_action("a2", "web_search");
        a2.state_dependencies = vec!["ocr_text".to_string()];

        let ctx_state = HashMap::new();
        let ctx_versions = HashMap::new();
        let ctx = GateContext {
            session_id: None,
            scope: None,
            state: &ctx_state,
            versions: &ctx_versions,
        };
        let outcome = gate.check(&proposal(vec![a1, a2]), &ctx).await;
        assert!(
            matches!(outcome, GateOutcome::Reject { .. }),
            "OCR output reaching web_search must be blocked, got {outcome:?}"
        );
    }

    #[tokio::test]
    async fn image_classification_to_persistent_memory_is_blocked_by_default() {
        let gate = InformationFlowGate::with_builtin_labels();
        let mut a1 = tool_action("a1", "classify_image");
        a1.expected_effects = [("image_labels".to_string(), serde_json::Value::from(1))].into();
        let mut a2 = tool_action("a2", "remember");
        a2.state_dependencies = vec!["image_labels".to_string()];

        let ctx_state = HashMap::new();
        let ctx_versions = HashMap::new();
        let ctx = GateContext {
            session_id: None,
            scope: None,
            state: &ctx_state,
            versions: &ctx_versions,
        };
        let outcome = gate.check(&proposal(vec![a1, a2]), &ctx).await;
        assert!(
            matches!(outcome, GateOutcome::Reject { .. }),
            "image classification output reaching persistent memory must be blocked, got {outcome:?}"
        );
    }

    #[tokio::test]
    async fn confidential_to_studio_generator_is_blocked() {
        let mut labels = builtin_tool_labels();
        labels.insert(
            "read_secret".to_string(),
            ToolLabels {
                capability: Some("fs_read".to_string()),
                confidentiality: car_verify::infoflow::Confidentiality::Secret,
                ..Default::default()
            },
        );
        let gate = InformationFlowGate::new(ToolLabelConfig {
            labels,
            ..Default::default()
        });

        let mut a1 = tool_action("a1", "read_secret");
        a1.expected_effects = [("prompt".to_string(), serde_json::Value::from(1))].into();
        let mut a2 = tool_action("a2", "generate_studio_image");
        a2.state_dependencies = vec!["prompt".to_string()];

        let ctx_state = HashMap::new();
        let ctx_versions = HashMap::new();
        let ctx = GateContext {
            session_id: None,
            scope: None,
            state: &ctx_state,
            versions: &ctx_versions,
        };
        let outcome = gate.check(&proposal(vec![a1, a2]), &ctx).await;
        assert!(
            matches!(outcome, GateOutcome::Reject { .. }),
            "secret reaching a Studio generator must be blocked, got {outcome:?}"
        );
    }

    #[tokio::test]
    async fn confidential_to_host_automation_is_blocked() {
        let mut labels = builtin_tool_labels();
        labels.insert(
            "read_secret".to_string(),
            ToolLabels {
                capability: Some("fs_read".to_string()),
                confidentiality: car_verify::infoflow::Confidentiality::Secret,
                ..Default::default()
            },
        );
        let gate = InformationFlowGate::new(ToolLabelConfig {
            labels,
            ..Default::default()
        });

        let mut a1 = tool_action("a1", "read_secret");
        a1.expected_effects = [("script".to_string(), serde_json::Value::from(1))].into();
        let mut a2 = tool_action("a2", "run_applescript");
        a2.state_dependencies = vec!["script".to_string()];

        let ctx_state = HashMap::new();
        let ctx_versions = HashMap::new();
        let ctx = GateContext {
            session_id: None,
            scope: None,
            state: &ctx_state,
            versions: &ctx_versions,
        };
        let outcome = gate.check(&proposal(vec![a1, a2]), &ctx).await;
        assert!(
            matches!(outcome, GateOutcome::Reject { .. }),
            "secret reaching host automation must be blocked, got {outcome:?}"
        );
    }

    #[tokio::test]
    async fn confidential_to_persistent_memory_is_blocked() {
        let mut labels = builtin_tool_labels();
        labels.insert(
            "read_secret".to_string(),
            ToolLabels {
                capability: Some("fs_read".to_string()),
                confidentiality: car_verify::infoflow::Confidentiality::Secret,
                ..Default::default()
            },
        );
        let gate = InformationFlowGate::new(ToolLabelConfig {
            labels,
            ..Default::default()
        });

        let mut a1 = tool_action("a1", "read_secret");
        a1.expected_effects = [("fact".to_string(), serde_json::Value::from(1))].into();
        let mut a2 = tool_action("a2", "remember");
        a2.state_dependencies = vec!["fact".to_string()];

        let ctx_state = HashMap::new();
        let ctx_versions = HashMap::new();
        let ctx = GateContext {
            session_id: None,
            scope: None,
            state: &ctx_state,
            versions: &ctx_versions,
        };
        let outcome = gate.check(&proposal(vec![a1, a2]), &ctx).await;
        assert!(
            matches!(outcome, GateOutcome::Reject { .. }),
            "secret reaching persistent memory must be blocked, got {outcome:?}"
        );
    }

    #[test]
    fn load_missing_file_returns_builtins() {
        let cfg = load_tool_labels("/nonexistent/.car").unwrap();
        assert!(cfg.labels.contains_key("http_request"));
        assert!(cfg.labels.contains_key("web_search"));
        assert!(cfg.labels.contains_key("generate_studio_image"));
        assert!(cfg.labels.contains_key("run_applescript"));
        assert!(cfg.labels.contains_key("remember"));
        assert!(cfg.labels.contains_key("recall"));
        assert!(cfg.labels.contains_key("read_image_text"));
        assert!(cfg.labels.contains_key("classify_image"));
    }

    #[test]
    fn load_merges_file_without_weakening_builtins() {
        let dir = std::env::temp_dir().join(format!("car_flow_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("tool-labels.json"),
            r#"{
                "labels": {
                    "my_tool": {"confidentiality": "secret"},
                    "http_request": {"capability": "not_net", "sink": false},
                    "recall": {"confidentiality": "public"},
                    "remember": {"sink": false, "declassifier": true}
                },
                "flow_policy": {
                    "min_confidential": "secret",
                    "forbidden_sequences": [["fs_read", "net_send"]]
                },
                "gate_policy": {
                    "on_sensitive_to_sink": "allow",
                    "on_forbidden_sequence": "block"
                }
            }"#,
        )
        .unwrap();
        let cfg = load_tool_labels(&dir).unwrap();
        // New tool added.
        assert_eq!(
            cfg.labels.get("my_tool").unwrap().confidentiality,
            car_verify::infoflow::Confidentiality::Secret
        );
        // Built-in sinks/capabilities and internal sources cannot be weakened by
        // project-local policy files.
        let http = cfg.labels.get("http_request").unwrap();
        assert!(http.sink);
        assert_eq!(http.capability.as_deref(), Some("net_send"));
        assert_eq!(
            cfg.labels.get("recall").unwrap().confidentiality,
            car_verify::infoflow::Confidentiality::Internal
        );
        let remember = cfg.labels.get("remember").unwrap();
        assert!(remember.sink);
        assert!(!remember.declassifier);
        assert_eq!(
            cfg.flow_policy.min_confidential,
            car_verify::infoflow::Confidentiality::Internal
        );
        assert_eq!(
            cfg.flow_policy.forbidden_sequences,
            vec![("fs_read".to_string(), "net_send".to_string())]
        );
        assert_eq!(
            cfg.gate_policy.on_sensitive_to_sink,
            car_verify::infoflow::FlowAction::Block
        );
        assert_eq!(
            cfg.gate_policy.on_forbidden_sequence,
            car_verify::infoflow::FlowAction::Block
        );
        // Untouched built-in preserved.
        assert!(cfg.labels.contains_key("read_file"));
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn load_malformed_file_is_error() {
        let dir = std::env::temp_dir().join(format!("car_flow_bad_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("tool-labels.json"), "{not json").unwrap();
        assert!(load_tool_labels(&dir).is_err());
        std::fs::remove_dir_all(&dir).ok();
    }
}