car-engine 0.49.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
//! VIGIL intent gate — the live in-loop verify-before-commit call-site
//! (arXiv 2601.05755; `docs/proposals/intent-grounded-verification.md`).
//!
//! The VIGIL slices shipped as stateless verify/policy cores
//! (`car_verify::intent::check_intent` / `gate_intent`,
//! `car_policy::intent_gate::enforce_intent`); nothing on the runtime
//! *called* them on a normal proposal. This module attaches them to the
//! executor's admission seam as an [`AdmissionGate`] — per the epic-merge
//! review's unification finding: ONE enforcement plumbing, the executor's
//! central ledger resolution (A7), instead of a second parallel
//! ledger-resolving authority.
//!
//! Semantics preserved from the cores: a **forbidden capability** or a
//! **tool-stream-influenced out-of-intent action** (reachable from an
//! `untrusted` tool's result through the dependency graph — the injection
//! signature) is a hard `Reject`, never approvable. Untainted drift is
//! policy-driven (default: escalate to approval, resolved against the
//! durable ledger by content-bound fingerprint).
//!
//! Project config: `.car/intent.json` (the `tool-labels.json` idiom) —
//! an [`IntentGateConfig`] naming the `intent` spec, the `untrusted_tools`
//! whose outputs count as tool-stream input, and the untainted-drift
//! policy.

use crate::admission::{AdmissionGate, GateContext, GateOutcome};
use crate::taint::TaintLedger;
use car_ir::ActionProposal;
use car_verify::intent::{
    check_intent, gate_intent, intent_actions_from, IntentGatePolicy, IntentSpec,
};
use serde::{Deserialize, Serialize};
use sha2::Digest;
use std::collections::HashSet;
use std::path::Path;
use std::sync::Arc;

/// The deserialized `.car/intent.json` document.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct IntentGateConfig {
    /// The declared task intent (VIGIL's root of trust).
    #[serde(default)]
    pub intent: IntentSpec,
    /// Tools whose RESULTS are tool-stream input from an open environment
    /// (web fetch, inbox read, …). An action calling one — and everything
    /// downstream of it in the dependency graph — is treated as
    /// potentially injection-influenced.
    #[serde(default)]
    pub untrusted_tools: Vec<String>,
    /// Untainted-drift policy — deserialized DIRECTLY as
    /// [`car_verify::intent::IntentDisposition`] (`"allow"` /
    /// `"require_approval"` / `"block"`, snake_case). Typed so a typo'd
    /// or wrong-case value ("Block", "deny") is a LOUD parse error,
    /// never a silent downgrade of a hard block to approvable (linus
    /// review). Absent = the core's default (require_approval).
    #[serde(default)]
    pub on_untainted_drift: Option<car_verify::intent::IntentDisposition>,
}

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

impl std::fmt::Display for IntentLoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

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

/// Load `.car/intent.json`. Absent file ⇒ `Ok(None)` (the gate is
/// opt-in); a present-but-malformed file is a loud error, never a
/// silently-ungated session (the strict-and-loud A2 loader stance).
pub fn load_intent_config(
    car_dir: impl AsRef<Path>,
) -> Result<Option<IntentGateConfig>, IntentLoadError> {
    let path = car_dir.as_ref().join("intent.json");
    if !path.exists() {
        return Ok(None);
    }
    let raw = std::fs::read_to_string(&path).map_err(|e| IntentLoadError {
        message: format!("read {}: {e}", path.display()),
    })?;
    serde_json::from_str(&raw)
        .map(Some)
        .map_err(|e| IntentLoadError {
            message: format!("parse {}: {e}", path.display()),
        })
}

/// The admission gate. Cheap and side-effect-free per the seam contract:
/// the cores are pure and the config is captured at construction.
pub struct IntentGate {
    intent: IntentSpec,
    untrusted_tools: HashSet<String>,
    policy: IntentGatePolicy,
    /// Runtime taint provenance, when the runtime installed one. `None`
    /// ⇒ taint enters only through `untrusted_tools` and one proposal's
    /// own dependency DAG — the original, statically-scoped behavior.
    taint: Option<Arc<TaintLedger>>,
}

impl IntentGate {
    /// A gate with no runtime provenance: taint is derived from the tool
    /// names and the proposal's own DAG only.
    pub fn new(config: IntentGateConfig) -> Self {
        Self::build(config, None)
    }

    /// A gate backed by the runtime's [`TaintLedger`], so a result the
    /// executor observed as tainted marks the actions that READ it — even
    /// when their own tool is trusted, and even when the tainting action
    /// belongs to an earlier proposal (the replan case). See
    /// [`crate::taint`].
    pub fn with_taint(config: IntentGateConfig, ledger: Arc<TaintLedger>) -> Self {
        Self::build(config, Some(ledger))
    }

    fn build(config: IntentGateConfig, taint: Option<Arc<TaintLedger>>) -> Self {
        let policy = match config.on_untainted_drift {
            Some(d) => IntentGatePolicy {
                on_untainted_drift: d,
            },
            None => IntentGatePolicy::default(),
        };
        Self {
            intent: config.intent,
            untrusted_tools: config.untrusted_tools.into_iter().collect(),
            policy,
            taint,
        }
    }
}

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

    async fn check(&self, proposal: &ActionProposal, ctx: &GateContext<'_>) -> GateOutcome {
        // Derive IntentActions from the proposal's own IR (the Slice 4
        // populater): tool, effective write set → targets,
        // metadata.capabilities, the same dependency DAG the runtime
        // sequences on. Taint enters two ways: statically through
        // untrusted TOOLS, and — when the runtime installed a
        // [`TaintLedger`] — through `untrusted_ids`, the actions whose
        // read set touches a state key an untrusted result actually
        // wrote at execution time. The second is what covers a trusted
        // tool laundering attacker content and a replan that carries no
        // dependency edge back to the poisoned action. From there
        // `check_intent` propagates along depends_on exactly as before.
        let untrusted_ids = match &self.taint {
            Some(ledger) => {
                let tenant = ctx.scope.and_then(|s| s.tenant_id.as_deref());
                ledger.untrusted_action_ids(tenant, &proposal.actions).await
            }
            None => HashSet::new(),
        };
        let intent_actions =
            intent_actions_from(&proposal.actions, &self.untrusted_tools, &untrusted_ids);
        let report = check_intent(&self.intent, &intent_actions);
        // NOTE: `report.safe` only means "nothing commit-blocked" —
        // untainted drift is REPORTED in `violations` with safe=true,
        // and the gate policy decides its disposition. So gate on
        // violations, not on `safe`.
        if report.violations.is_empty() {
            return GateOutcome::Allow;
        }
        let decision = gate_intent(&report, &self.policy);
        if !decision.blocked.is_empty() {
            return GateOutcome::Reject {
                blocked: decision.blocked.iter().map(|v| v.action.clone()).collect(),
                reason: decision.reason,
            };
        }
        if !decision.needs_approval.is_empty() {
            // Content-bound fingerprint over EVERY escalated violation
            // (the C-8 lesson: fingerprinting one hazard lets one
            // approval admit the rest), sorted for order independence,
            // then HASHED: the components (action ids, write-set keys,
            // tool names) are model-authored strings under VIGIL's own
            // threat model, so a delimiter-joined key would be forgeable
            // by embedding the separator in a detail (linus review).
            // A ledger key is a security identity, not a log line.
            let mut fps: Vec<String> = decision
                .needs_approval
                .iter()
                .map(car_policy::intent_gate::intent_fingerprint)
                .collect();
            fps.sort();
            fps.dedup();
            let canonical = serde_json::to_string(&fps).unwrap_or_default();
            let digest = sha2::Sha256::digest(canonical.as_bytes());
            return GateOutcome::NeedsApproval {
                actions: decision
                    .needs_approval
                    .iter()
                    .map(|v| v.action.clone())
                    .collect(),
                fingerprint: format!("intent:sha256:{:x}", digest),
                reason: decision.reason,
            };
        }
        GateOutcome::Allow
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::admission::GateContext;
    use car_ir::{Action, ActionProposal, ActionType};
    use std::collections::HashMap;

    fn tool_action(id: &str, tool: &str) -> Action {
        {
            let mut a = Action::new(ActionType::ToolCall);
            a.id = id.to_string();
            a.tool = Some(tool.to_string());
            a.max_retries = 0;
            a
        }
    }

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

    fn ctx<'a>(
        state: &'a HashMap<String, serde_json::Value>,
        versions: &'a HashMap<String, u64>,
    ) -> GateContext<'a> {
        GateContext {
            session_id: None,
            scope: None,
            state,
            versions,
        }
    }

    #[tokio::test]
    async fn injection_signature_is_hard_rejected() {
        // fetch_web is untrusted; send_payment is out of the declared
        // intent AND downstream of the untrusted result → hard Reject
        // (never approvable) — the VIGIL injection case.
        let gate = IntentGate::new(IntentGateConfig {
            intent: IntentSpec {
                allowed_tools: vec!["fetch_web".to_string(), "summarize".to_string()],
                ..Default::default()
            },
            untrusted_tools: vec!["fetch_web".to_string()],
            on_untainted_drift: None,
        });
        let mut fetch = tool_action("a1", "fetch_web");
        fetch
            .expected_effects
            .insert("page".into(), serde_json::json!(""));
        let mut pay = tool_action("a2", "send_payment");
        pay.state_dependencies.push("page".into());
        let p = proposal(vec![fetch, pay]);
        let (state, versions) = (HashMap::new(), HashMap::new());
        match gate.check(&p, &ctx(&state, &versions)).await {
            GateOutcome::Reject { blocked, .. } => assert!(blocked.contains("a2")),
            other => panic!("expected Reject, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn untainted_drift_escalates_with_content_bound_fingerprint() {
        let gate = IntentGate::new(IntentGateConfig {
            intent: IntentSpec {
                allowed_tools: vec!["summarize".to_string()],
                ..Default::default()
            },
            untrusted_tools: vec![],
            on_untainted_drift: None, // default: require approval
        });
        let p = proposal(vec![tool_action("a1", "send_email")]);
        let (state, versions) = (HashMap::new(), HashMap::new());
        match gate.check(&p, &ctx(&state, &versions)).await {
            GateOutcome::NeedsApproval {
                actions,
                fingerprint,
                ..
            } => {
                assert!(actions.contains("a1"));
                assert!(!fingerprint.is_empty());
            }
            other => panic!("expected NeedsApproval, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn in_intent_proposal_is_allowed() {
        let gate = IntentGate::new(IntentGateConfig {
            intent: IntentSpec {
                allowed_tools: vec!["summarize".to_string()],
                ..Default::default()
            },
            untrusted_tools: vec![],
            on_untainted_drift: None,
        });
        let p = proposal(vec![tool_action("a1", "summarize")]);
        let (state, versions) = (HashMap::new(), HashMap::new());
        assert!(matches!(
            gate.check(&p, &ctx(&state, &versions)).await,
            GateOutcome::Allow
        ));
    }

    fn taint_config() -> IntentGateConfig {
        IntentGateConfig {
            intent: IntentSpec {
                allowed_tools: vec!["fetch_web".to_string(), "summarize".to_string()],
                ..Default::default()
            },
            untrusted_tools: vec!["fetch_web".to_string()],
            on_untainted_drift: None,
        }
    }

    /// An out-of-intent `send_payment` that reads state key `page`, with no
    /// dependency edge to whatever wrote `page` — the replan shape.
    fn out_of_intent_reader() -> ActionProposal {
        let mut pay = tool_action("a9", "send_payment");
        pay.state_dependencies.push("page".into());
        proposal(vec![pay])
    }

    #[tokio::test]
    async fn without_the_ledger_a_replanned_reader_only_escalates() {
        // The control: this is exactly today's behavior, and exactly the
        // hole. The poisoned `fetch_web` is in a PREVIOUS proposal, so the
        // gate sees a lone out-of-intent action with no untrusted
        // dependency — the model's own drift, merely approvable.
        let gate = IntentGate::new(taint_config());
        let (state, versions) = (HashMap::new(), HashMap::new());
        match gate
            .check(&out_of_intent_reader(), &ctx(&state, &versions))
            .await
        {
            GateOutcome::NeedsApproval { actions, .. } => assert!(actions.contains("a9")),
            other => panic!("expected NeedsApproval without a ledger, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn runtime_taint_hard_rejects_a_replanned_out_of_intent_reader() {
        // Same proposal, same intent — but the runtime observed `fetch_web`
        // writing `page`. That provenance makes the reader tool-stream-
        // influenced, which is the injection signature: a hard block, never
        // approvable.
        let ledger = Arc::new(crate::taint::TaintLedger::new(
            ["fetch_web".to_string()].into_iter().collect(),
        ));
        let mut fetch = tool_action("a1", "fetch_web");
        fetch
            .expected_effects
            .insert("page".into(), serde_json::json!(""));
        ledger
            .record_result(None, &fetch, ["page".to_string()])
            .await;

        let gate = IntentGate::with_taint(taint_config(), ledger);
        let (state, versions) = (HashMap::new(), HashMap::new());
        match gate
            .check(&out_of_intent_reader(), &ctx(&state, &versions))
            .await
        {
            GateOutcome::Reject { blocked, .. } => assert!(blocked.contains("a9")),
            other => panic!("expected Reject with runtime taint, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn runtime_taint_under_another_tenant_does_not_reject() {
        // Provenance is tenant-partitioned; tenant A's poisoned fetch must
        // not hard-block tenant B. Without a scope the gate looks at the
        // untenanted partition, which is empty here.
        let ledger = Arc::new(crate::taint::TaintLedger::new(
            ["fetch_web".to_string()].into_iter().collect(),
        ));
        ledger
            .record_result(
                Some("tenant-a"),
                &tool_action("a1", "fetch_web"),
                ["page".to_string()],
            )
            .await;

        let gate = IntentGate::with_taint(taint_config(), ledger);
        let (state, versions) = (HashMap::new(), HashMap::new());
        match gate
            .check(&out_of_intent_reader(), &ctx(&state, &versions))
            .await
        {
            GateOutcome::NeedsApproval { .. } => {}
            other => panic!("expected NeedsApproval for a different tenant, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn an_empty_ledger_preserves_the_no_ledger_verdict() {
        // Installing the ledger must not change anything on its own — only
        // an observed tainted result may.
        let ledger = Arc::new(crate::taint::TaintLedger::new(
            ["fetch_web".to_string()].into_iter().collect(),
        ));
        let gate = IntentGate::with_taint(taint_config(), ledger);
        let (state, versions) = (HashMap::new(), HashMap::new());
        match gate
            .check(&out_of_intent_reader(), &ctx(&state, &versions))
            .await
        {
            GateOutcome::NeedsApproval { .. } => {}
            other => panic!("expected NeedsApproval with an empty ledger, got {other:?}"),
        }
    }

    #[test]
    fn typo_in_drift_policy_is_a_loud_parse_error() {
        // linus review: a stringly policy silently degraded "Block"/"deny"
        // typos to require_approval — a hard block becoming approvable.
        // Typed deserialization must reject loudly instead.
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(
            tmp.path().join("intent.json"),
            r#"{"on_untainted_drift": "Block"}"#,
        )
        .unwrap();
        assert!(
            load_intent_config(tmp.path()).is_err(),
            "wrong case must not parse"
        );
        std::fs::write(
            tmp.path().join("intent.json"),
            r#"{"on_untainted_drift": "block"}"#,
        )
        .unwrap();
        let cfg = load_intent_config(tmp.path()).unwrap().unwrap();
        assert_eq!(
            cfg.on_untainted_drift,
            Some(car_verify::intent::IntentDisposition::Block)
        );
    }

    #[test]
    fn loader_absent_is_none_malformed_is_loud() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(load_intent_config(tmp.path()).unwrap().is_none());
        std::fs::write(tmp.path().join("intent.json"), "{not json").unwrap();
        assert!(load_intent_config(tmp.path()).is_err());
    }
}