car-engine 0.26.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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
//! Authorization pipeline for tool execution.
//!
//! Provides a structured pre-execution decision path with typed decisions.
//! Each stage can Allow, Deny, or AskUser, and the pipeline short-circuits
//! on the first Deny.

use car_ir::{Action, ActionType, ToolSchema};
use car_policy::PolicyEngine;
use car_state::StateStore;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// The stage that produced an authorization decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthzStage {
    /// Tool existence check.
    ToolExists,
    /// Capability check (agent-level whitelist/blacklist).
    Capability,
    /// Permission mode / approval policy.
    Permission,
    /// Permanent restrictions (never bypassable).
    Restriction,
    /// Policy engine rules.
    Policy,
    /// Executor-level parameter validation.
    Validation,
}

/// The authorization decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthzDecision {
    /// Execution is allowed to proceed.
    Allow,
    /// Execution requires user approval before proceeding.
    AskUser,
    /// Execution is denied.
    Deny,
}

/// A complete authorization result from the pipeline.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthzResult {
    /// The final decision.
    pub decision: AuthzDecision,
    /// The stage that produced the decision (for Deny/AskUser, the stage that stopped it).
    pub stage: AuthzStage,
    /// Machine-readable reason code.
    pub reason_code: String,
    /// Human-readable explanation.
    pub explanation: String,
    /// Results from each stage that was evaluated.
    pub stage_results: Vec<StageResult>,
}

/// Result from a single authorization stage.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StageResult {
    pub stage: AuthzStage,
    pub decision: AuthzDecision,
    pub reason: String,
}

impl AuthzResult {
    pub fn allowed(stage: AuthzStage) -> Self {
        Self {
            decision: AuthzDecision::Allow,
            stage,
            reason_code: "allowed".to_string(),
            explanation: "All authorization checks passed".to_string(),
            stage_results: Vec::new(),
        }
    }

    pub fn denied(stage: AuthzStage, reason_code: &str, explanation: &str) -> Self {
        Self {
            decision: AuthzDecision::Deny,
            stage,
            reason_code: reason_code.to_string(),
            explanation: explanation.to_string(),
            stage_results: Vec::new(),
        }
    }

    pub fn ask_user(stage: AuthzStage, reason_code: &str, explanation: &str) -> Self {
        Self {
            decision: AuthzDecision::AskUser,
            stage,
            reason_code: reason_code.to_string(),
            explanation: explanation.to_string(),
            stage_results: Vec::new(),
        }
    }

    fn with_stages(mut self, stages: Vec<StageResult>) -> Self {
        self.stage_results = stages;
        self
    }
}

/// A permanent restriction that can never be bypassed.
pub struct Restriction {
    pub name: String,
    pub description: String,
    check: Box<dyn Fn(&Action) -> Option<String> + Send + Sync>,
}

impl Restriction {
    pub fn new<F>(name: &str, description: &str, check: F) -> Self
    where
        F: Fn(&Action) -> Option<String> + Send + Sync + 'static,
    {
        Self {
            name: name.to_string(),
            description: description.to_string(),
            check: Box::new(check),
        }
    }

    fn check(&self, action: &Action) -> Option<String> {
        (self.check)(action)
    }
}

/// Callback for permission mode decisions (allow/ask/deny).
/// Products implement this to integrate their approval UX.
#[async_trait::async_trait]
pub trait PermissionHandler: Send + Sync {
    /// Decide whether to allow, ask, or deny a tool call.
    async fn check(&self, tool_name: &str, action: &Action) -> AuthzDecision;
}

/// Default permission handler that allows everything.
pub struct AllowAllPermissions;

#[async_trait::async_trait]
impl PermissionHandler for AllowAllPermissions {
    async fn check(&self, _tool_name: &str, _action: &Action) -> AuthzDecision {
        AuthzDecision::Allow
    }
}

/// The authorization pipeline.
pub struct AuthzPipeline {
    restrictions: Vec<Restriction>,
    permission_handler: Box<dyn PermissionHandler>,
}

impl AuthzPipeline {
    pub fn new() -> Self {
        Self {
            restrictions: Vec::new(),
            permission_handler: Box::new(AllowAllPermissions),
        }
    }

    /// Add a permanent restriction.
    pub fn add_restriction(&mut self, restriction: Restriction) {
        self.restrictions.push(restriction);
    }

    /// Set the permission handler.
    pub fn set_permission_handler(&mut self, handler: Box<dyn PermissionHandler>) {
        self.permission_handler = handler;
    }

    /// Run the full authorization pipeline for an action.
    ///
    /// Stages (in order):
    /// 1. Tool exists
    /// 2. Capability allows it
    /// 3. Permission mode / approval
    /// 4. Permanent restrictions
    /// 5. Policy engine
    /// 6. Executor-level validation
    pub async fn authorize(
        &self,
        action: &Action,
        tools: &HashMap<String, ToolSchema>,
        capabilities: Option<&crate::capabilities::CapabilitySet>,
        policies: &PolicyEngine,
        state: &StateStore,
    ) -> AuthzResult {
        let mut stages = Vec::new();

        // Stage 1: Tool exists
        if let Some(tool_name) = &action.tool {
            if action.action_type == ActionType::ToolCall && !tools.contains_key(tool_name) {
                stages.push(StageResult {
                    stage: AuthzStage::ToolExists,
                    decision: AuthzDecision::Deny,
                    reason: format!("tool '{}' not registered", tool_name),
                });
                return AuthzResult::denied(
                    AuthzStage::ToolExists,
                    "tool_not_found",
                    &format!("Tool '{}' is not registered", tool_name),
                )
                .with_stages(stages);
            }
        }
        stages.push(StageResult {
            stage: AuthzStage::ToolExists,
            decision: AuthzDecision::Allow,
            reason: "tool registered".to_string(),
        });

        // Stage 2: Capability check
        if let Some(caps) = capabilities {
            if let Some(tool_name) = &action.tool {
                if !caps.tool_allowed(tool_name) {
                    stages.push(StageResult {
                        stage: AuthzStage::Capability,
                        decision: AuthzDecision::Deny,
                        reason: format!("tool '{}' not in capability set", tool_name),
                    });
                    return AuthzResult::denied(
                        AuthzStage::Capability,
                        "capability_denied",
                        &format!("Tool '{}' denied by capability set", tool_name),
                    )
                    .with_stages(stages);
                }
            }
        }
        stages.push(StageResult {
            stage: AuthzStage::Capability,
            decision: AuthzDecision::Allow,
            reason: "capability check passed".to_string(),
        });

        // Stage 3: Permission mode
        if let Some(tool_name) = &action.tool {
            let perm = self.permission_handler.check(tool_name, action).await;
            stages.push(StageResult {
                stage: AuthzStage::Permission,
                decision: perm,
                reason: format!("permission handler returned {:?}", perm),
            });
            if perm == AuthzDecision::Deny {
                return AuthzResult::denied(
                    AuthzStage::Permission,
                    "permission_denied",
                    &format!("Permission denied for tool '{}'", tool_name),
                )
                .with_stages(stages);
            }
            if perm == AuthzDecision::AskUser {
                return AuthzResult::ask_user(
                    AuthzStage::Permission,
                    "approval_required",
                    &format!("Tool '{}' requires user approval", tool_name),
                )
                .with_stages(stages);
            }
        } else {
            stages.push(StageResult {
                stage: AuthzStage::Permission,
                decision: AuthzDecision::Allow,
                reason: "no tool name, skipped".to_string(),
            });
        }

        // Stage 4: Permanent restrictions
        for restriction in &self.restrictions {
            if let Some(reason) = restriction.check(action) {
                stages.push(StageResult {
                    stage: AuthzStage::Restriction,
                    decision: AuthzDecision::Deny,
                    reason: reason.clone(),
                });
                return AuthzResult::denied(
                    AuthzStage::Restriction,
                    &format!("restriction_{}", restriction.name),
                    &format!("Permanent restriction '{}': {}", restriction.name, reason),
                )
                .with_stages(stages);
            }
        }
        stages.push(StageResult {
            stage: AuthzStage::Restriction,
            decision: AuthzDecision::Allow,
            reason: "all restrictions passed".to_string(),
        });

        // Stage 5: Policy engine
        let violations = policies.check(action, state);
        if !violations.is_empty() {
            let reasons: Vec<String> = violations
                .iter()
                .map(|v| format!("{}: {}", v.policy_name, v.reason))
                .collect();
            stages.push(StageResult {
                stage: AuthzStage::Policy,
                decision: AuthzDecision::Deny,
                reason: reasons.join("; "),
            });
            return AuthzResult::denied(
                AuthzStage::Policy,
                "policy_violation",
                &format!("Policy violations: {}", reasons.join("; ")),
            )
            .with_stages(stages);
        }
        stages.push(StageResult {
            stage: AuthzStage::Policy,
            decision: AuthzDecision::Allow,
            reason: "all policies passed".to_string(),
        });

        // Stage 6: Validation (deferred to caller — we just mark it as passed here)
        stages.push(StageResult {
            stage: AuthzStage::Validation,
            decision: AuthzDecision::Allow,
            reason: "validation deferred".to_string(),
        });

        AuthzResult::allowed(AuthzStage::Validation).with_stages(stages)
    }
}

impl Default for AuthzPipeline {
    fn default() -> Self {
        Self::new()
    }
}

/// Bridges a [`car_policy::PermissionGate`] into the authorization
/// pipeline's permission stage.
///
/// This is where the permission-tier model (survey §3.4.3, §5.2.5) meets
/// the existing pipeline: the gate classifies each action's risk tier,
/// compares it to the session's granted standing authority, and consults
/// the durable approval ledger. Its decision maps onto the pipeline's
/// existing vocabulary — `Allow` proceeds, `NeedsApproval` becomes
/// `AskUser` (autonomy suspended pending a human decision), and a prior
/// rejection becomes `Deny`. Every decision is audited to the event log
/// as a `PermissionDecision` event so the tier reasoning is inspectable
/// rather than implicit.
pub struct TierPermissionHandler {
    gate: std::sync::Arc<tokio::sync::RwLock<car_policy::PermissionGate>>,
    log: Option<std::sync::Arc<tokio::sync::Mutex<car_eventlog::EventLog>>>,
}

impl TierPermissionHandler {
    pub fn new(
        gate: std::sync::Arc<tokio::sync::RwLock<car_policy::PermissionGate>>,
    ) -> Self {
        Self { gate, log: None }
    }

    /// Audit each gate decision to this event log as a `PermissionDecision`.
    pub fn with_event_log(
        mut self,
        log: std::sync::Arc<tokio::sync::Mutex<car_eventlog::EventLog>>,
    ) -> Self {
        self.log = Some(log);
        self
    }

    /// Record a durable human-in-the-loop decision through the gate and
    /// emit it to the event log as an `ApprovalRecorded` event — the
    /// auditable state transition §5.2.5 calls for ("who approved/rejected
    /// what, when, on what evidence"). `approve=false` records a rejection.
    pub async fn record_approval(
        &self,
        action: &Action,
        approve: bool,
        reviewer: &str,
        reason: &str,
        evidence: Option<String>,
    ) -> car_policy::ApprovalRecord {
        let record = {
            let mut gate = self.gate.write().await;
            if approve {
                gate.approve(action, reviewer, reason, evidence)
            } else {
                gate.reject(action, reviewer, reason, evidence)
            }
        };
        if let Some(log) = &self.log {
            let mut data = HashMap::new();
            data.insert("fingerprint".into(), record.fingerprint.clone().into());
            data.insert(
                "approval".into(),
                match record.decision {
                    car_policy::ApprovalDecision::Approved => "approved",
                    car_policy::ApprovalDecision::Rejected => "rejected",
                }
                .into(),
            );
            data.insert("required_tier".into(), record.required_tier.as_str().into());
            data.insert("reviewer".into(), record.reviewer.clone().into());
            data.insert("reason".into(), record.reason.clone().into());
            if let Some(ev) = &record.evidence {
                data.insert("evidence".into(), ev.clone().into());
            }
            log.lock().await.append(
                car_eventlog::EventKind::ApprovalRecorded,
                Some(&action.id),
                None,
                data,
            );
        }
        record
    }

    /// Map a gate decision onto the pipeline's decision vocabulary.
    fn map_decision(decision: &car_policy::GateDecision) -> AuthzDecision {
        match decision {
            car_policy::GateDecision::Allow { .. } => AuthzDecision::Allow,
            car_policy::GateDecision::NeedsApproval { .. } => AuthzDecision::AskUser,
            car_policy::GateDecision::Deny { .. } => AuthzDecision::Deny,
        }
    }

    /// Flatten a gate decision into structured event data for the audit
    /// trail.
    fn decision_data(
        decision: &car_policy::GateDecision,
    ) -> HashMap<String, serde_json::Value> {
        use car_policy::GateDecision::*;
        let mut data = HashMap::new();
        match decision {
            Allow { required, granted } => {
                data.insert("gate_decision".into(), "allow".into());
                data.insert("required_tier".into(), required.as_str().into());
                data.insert("granted_tier".into(), granted.as_str().into());
            }
            NeedsApproval {
                required,
                granted,
                fingerprint,
                reason,
            } => {
                data.insert("gate_decision".into(), "needs_approval".into());
                data.insert("required_tier".into(), required.as_str().into());
                data.insert("granted_tier".into(), granted.as_str().into());
                data.insert("fingerprint".into(), fingerprint.clone().into());
                data.insert("reason".into(), reason.clone().into());
            }
            Deny {
                required,
                fingerprint,
                reason,
            } => {
                data.insert("gate_decision".into(), "deny".into());
                data.insert("required_tier".into(), required.as_str().into());
                data.insert("fingerprint".into(), fingerprint.clone().into());
                data.insert("reason".into(), reason.clone().into());
            }
        }
        data
    }
}

#[async_trait::async_trait]
impl PermissionHandler for TierPermissionHandler {
    async fn check(&self, _tool_name: &str, action: &Action) -> AuthzDecision {
        let decision = {
            let gate = self.gate.read().await;
            gate.evaluate(action)
        };
        if let Some(log) = &self.log {
            let data = Self::decision_data(&decision);
            log.lock().await.append(
                car_eventlog::EventKind::PermissionDecision,
                Some(&action.id),
                None,
                data,
            );
        }
        Self::map_decision(&decision)
    }
}

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

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

    fn test_tools() -> HashMap<String, ToolSchema> {
        let mut m = HashMap::new();
        m.insert(
            "read".to_string(),
            ToolSchema {
                name: "read".to_string(),
                description: "Read a file".to_string(),
                parameters: serde_json::json!({"type": "object"}),
                returns: None,
                idempotent: true,
                cache_ttl_secs: None,
                rate_limit: None,
            },
        );
        m
    }

    #[tokio::test]
    async fn test_allow_registered_tool() {
        let pipeline = AuthzPipeline::new();
        let tools = test_tools();
        let policies = PolicyEngine::new();
        let state = StateStore::new();

        let result = pipeline
            .authorize(&test_action("read"), &tools, None, &policies, &state)
            .await;
        assert_eq!(result.decision, AuthzDecision::Allow);
        assert_eq!(result.stage_results.len(), 6);
    }

    #[tokio::test]
    async fn test_deny_unregistered_tool() {
        let pipeline = AuthzPipeline::new();
        let tools = test_tools();
        let policies = PolicyEngine::new();
        let state = StateStore::new();

        let result = pipeline
            .authorize(&test_action("delete"), &tools, None, &policies, &state)
            .await;
        assert_eq!(result.decision, AuthzDecision::Deny);
        assert_eq!(result.stage, AuthzStage::ToolExists);
        assert_eq!(result.reason_code, "tool_not_found");
    }

    #[tokio::test]
    async fn test_capability_denial() {
        let pipeline = AuthzPipeline::new();
        let tools = test_tools();
        let policies = PolicyEngine::new();
        let state = StateStore::new();
        let mut caps = crate::capabilities::CapabilitySet::default();
        caps.denied_tools.insert("read".to_string());

        let result = pipeline
            .authorize(&test_action("read"), &tools, Some(&caps), &policies, &state)
            .await;
        assert_eq!(result.decision, AuthzDecision::Deny);
        assert_eq!(result.stage, AuthzStage::Capability);
    }

    #[tokio::test]
    async fn test_restriction() {
        let mut pipeline = AuthzPipeline::new();
        pipeline.add_restriction(Restriction::new("no_read", "Never allow read", |action| {
            if action.tool.as_deref() == Some("read") {
                Some("reads are restricted".to_string())
            } else {
                None
            }
        }));
        let tools = test_tools();
        let policies = PolicyEngine::new();
        let state = StateStore::new();

        let result = pipeline
            .authorize(&test_action("read"), &tools, None, &policies, &state)
            .await;
        assert_eq!(result.decision, AuthzDecision::Deny);
        assert_eq!(result.stage, AuthzStage::Restriction);
    }

    #[tokio::test]
    async fn test_policy_violation() {
        let pipeline = AuthzPipeline::new();
        let tools = test_tools();
        let state = StateStore::new();
        let mut policies = PolicyEngine::new();
        policies.register(
            "deny_all",
            Box::new(|_action: &Action, _state: &StateStore| Some("denied by test".to_string())),
            "test policy",
        );

        let result = pipeline
            .authorize(&test_action("read"), &tools, None, &policies, &state)
            .await;
        assert_eq!(result.decision, AuthzDecision::Deny);
        assert_eq!(result.stage, AuthzStage::Policy);
    }

    #[tokio::test]
    async fn test_ask_user_permission() {
        struct AskPermissions;
        #[async_trait::async_trait]
        impl PermissionHandler for AskPermissions {
            async fn check(&self, _tool_name: &str, _action: &Action) -> AuthzDecision {
                AuthzDecision::AskUser
            }
        }

        let mut pipeline = AuthzPipeline::new();
        pipeline.set_permission_handler(Box::new(AskPermissions));
        let tools = test_tools();
        let policies = PolicyEngine::new();
        let state = StateStore::new();

        let result = pipeline
            .authorize(&test_action("read"), &tools, None, &policies, &state)
            .await;
        assert_eq!(result.decision, AuthzDecision::AskUser);
        assert_eq!(result.stage, AuthzStage::Permission);
        assert_eq!(result.reason_code, "approval_required");
    }

    #[tokio::test]
    async fn test_stage_results_trace() {
        let pipeline = AuthzPipeline::new();
        let tools = test_tools();
        let policies = PolicyEngine::new();
        let state = StateStore::new();

        let result = pipeline
            .authorize(&test_action("read"), &tools, None, &policies, &state)
            .await;
        // All 6 stages should be present when everything passes
        let stage_names: Vec<AuthzStage> = result.stage_results.iter().map(|s| s.stage).collect();
        assert_eq!(
            stage_names,
            vec![
                AuthzStage::ToolExists,
                AuthzStage::Capability,
                AuthzStage::Permission,
                AuthzStage::Restriction,
                AuthzStage::Policy,
                AuthzStage::Validation,
            ]
        );
    }

    #[tokio::test]
    async fn test_short_circuit_on_deny() {
        let pipeline = AuthzPipeline::new();
        let tools = test_tools();
        let policies = PolicyEngine::new();
        let state = StateStore::new();

        // Unregistered tool should short-circuit at stage 1
        let result = pipeline
            .authorize(&test_action("nonexistent"), &tools, None, &policies, &state)
            .await;
        assert_eq!(result.stage_results.len(), 1);
        assert_eq!(result.stage_results[0].stage, AuthzStage::ToolExists);
    }

    #[tokio::test]
    async fn test_serde_roundtrip() {
        let result = AuthzResult::denied(AuthzStage::Policy, "policy_violation", "Test violation");
        let json = serde_json::to_string(&result).unwrap();
        let roundtripped: AuthzResult = serde_json::from_str(&json).unwrap();
        assert_eq!(roundtripped.decision, AuthzDecision::Deny);
        assert_eq!(roundtripped.stage, AuthzStage::Policy);
        assert_eq!(roundtripped.reason_code, "policy_violation");
    }

    // --- TierPermissionHandler bridge (permission tiers → pipeline) ---

    use std::sync::Arc;
    use tokio::sync::RwLock;

    fn deploy_action() -> Action {
        let mut a = test_action("deploy_service");
        a.id = "deploy-1".to_string();
        a
    }

    #[tokio::test]
    async fn tier_handler_asks_user_for_full_access() {
        // A FullAccess action under a SandboxEdit grant must escalate to
        // the user, surfacing as AuthzDecision::AskUser through the
        // pipeline's permission stage.
        let gate = Arc::new(RwLock::new(car_policy::PermissionGate::new(
            car_policy::PermissionTier::SandboxEdit,
        )));
        let handler = TierPermissionHandler::new(gate);
        assert_eq!(
            handler.check("deploy_service", &deploy_action()).await,
            AuthzDecision::AskUser
        );
    }

    #[tokio::test]
    async fn tier_handler_allows_after_approval_and_audits() {
        let gate = Arc::new(RwLock::new(car_policy::PermissionGate::new(
            car_policy::PermissionTier::SandboxEdit,
        )));
        let log = Arc::new(tokio::sync::Mutex::new(car_eventlog::EventLog::new()));
        let handler = TierPermissionHandler::new(gate.clone()).with_event_log(log.clone());
        let action = deploy_action();

        // First pass: escalation, audited.
        assert_eq!(
            handler.check("deploy_service", &action).await,
            AuthzDecision::AskUser
        );
        // Human approves the operation through the handler (durable ledger
        // entry + ApprovalRecorded audit event).
        handler
            .record_approval(&action, true, "matt", "reviewed", Some("diff".into()))
            .await;
        // Now the same operation is allowed.
        assert_eq!(
            handler.check("deploy_service", &action).await,
            AuthzDecision::Allow
        );

        let log = log.lock().await;
        // Both evaluations were audited as PermissionDecision events.
        let decisions: Vec<_> = log
            .events()
            .iter()
            .filter(|e| e.kind == car_eventlog::EventKind::PermissionDecision)
            .collect();
        assert_eq!(decisions.len(), 2);
        assert_eq!(
            decisions[0].data.get("gate_decision").unwrap(),
            "needs_approval"
        );
        assert_eq!(decisions[1].data.get("gate_decision").unwrap(), "allow");
        // The approval itself was audited as a durable state transition.
        let approvals: Vec<_> = log
            .events()
            .iter()
            .filter(|e| e.kind == car_eventlog::EventKind::ApprovalRecorded)
            .collect();
        assert_eq!(approvals.len(), 1);
        assert_eq!(approvals[0].data.get("approval").unwrap(), "approved");
        assert_eq!(approvals[0].data.get("reviewer").unwrap(), "matt");
    }

    #[tokio::test]
    async fn tier_handler_denies_after_rejection() {
        let gate = Arc::new(RwLock::new(car_policy::PermissionGate::new(
            car_policy::PermissionTier::FullAccess,
        )));
        let handler = TierPermissionHandler::new(gate.clone());
        let action = deploy_action();
        gate.write()
            .await
            .reject(&action, "matt", "not authorized", None);
        assert_eq!(
            handler.check("deploy_service", &action).await,
            AuthzDecision::Deny
        );
    }
}