car-server-core 0.52.1

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
//! Session permission-tier enforcement at proposal admission (Parslee-ai/car#890).
//!
//! The daemon has had the whole permission machinery for a while: a
//! per-session [`car_policy::PermissionGate`] carrying the granted standing
//! tier and the risk classifier, a daemon-wide durable
//! [`car_policy::ApprovalLedger`], and the `permission.evaluate` /
//! `permission.approve` / `permission.reject` RPCs that read and write them.
//! What it did not have was a *call site*: `proposal.submit` dispatched
//! straight to the executor, so an action the daemon's own
//! `permission.evaluate` called `needs_approval` executed anyway — on the same
//! session, in the same breath — and its state write persisted. The published
//! contract (`docs/websocket-protocol.md`, the `car_policy::permission` module
//! doc) said such an action "cannot run autonomously". It could.
//!
//! [`PermissionAdmissionGate`] is that call site. It is an
//! [`AdmissionGate`], so it runs on every proposal admitted by a session
//! runtime, *before any action executes*, alongside
//! `car_engine::StaticVerificationGate` and [`crate::supervision::SupervisionGate`].
//!
//! # One verdict, one evaluator
//!
//! The gate and `handle_permission_evaluate` both call [`evaluate_action`]
//! over the same `PermissionGate`, durable ledger, and authenticated bound
//! agent identity. That is load-bearing, not incidental: an enforcement
//! point that classified actions with its own fresh `RiskClassifier` would be
//! free to disagree with the advisory RPC an operator is looking at, which
//! replaces one inconsistency with a worse one. The gate holds the *same*
//! `Arc<RwLock<PermissionGate>>` the `permission.*` handlers hold, so a
//! `permission.set_tier` on the session is visible here on the very next
//! submit, and a custom classifier rule installed on the session applies to
//! both surfaces by construction.
//!
//! # Why the gate reads the shared ledger itself
//!
//! Escalations resolve through the daemon-wide
//! [`crate::session::ServerState::approval_ledger`], not through the
//! executor's own. `Runtime::approval_ledger` is `None` on daemon sessions and
//! must stay that way — a second ledger instance would let the approver's
//! decision land somewhere the runner never reads. So the loop closes here
//! instead: once `permission.approve` records a decision for an action's
//! fingerprint, `evaluate_axes` returns `Allow` on the next submit and this
//! gate produces **no escalation at all**, which is what admits the proposal.
//!
//! The consequence for an *unapproved* escalation is deliberate. The executor
//! resolves `GateOutcome::NeedsApproval` against its own (absent) ledger, finds
//! nothing, and fails closed with the escalation's reason and fingerprint on
//! every rejected action. That is the intended UX: the caller is told the
//! proposal needs a human, and told exactly which fingerprints to approve.
//!
//! # Which fingerprint an operator approves
//!
//! [`GateOutcome::NeedsApproval`] carries one fingerprint, and a proposal can
//! escalate several actions, so the escalation's own fingerprint is a
//! deterministic composite (sorted + deduped per-action fingerprints under a
//! `permission:` prefix) — the same shape `car_engine::SkillCeilingGate` uses
//! for its multi-action case. **It is an identity, not an approval target**:
//! nothing looks it up. The approvable fingerprints are the per-action ones,
//! and the `reason` names every one of them next to its required and granted
//! tier so `permission.approve { fingerprint, required_tier }` can be driven
//! straight off the error text.

use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use car_engine::admission::{AdmissionGate, GateContext, GateOutcome};
use car_ir::{Action, ActionProposal, ActionType};
use car_policy::agent_permissions::{AgentPermissionPolicy, ApprovalMode};
use car_policy::{ActionAxes, ApprovalDecision, GateDecision, PermissionTier};
use tokio::sync::{Mutex, RwLock};

pub const AGENT_TOOL_OVERRIDE_SOURCE: &str = "agent_tool_override";
pub const APPROVAL_LEDGER_SOURCE: &str = "approval_ledger";

/// One action's shared advisory/enforcement verdict plus its authorization
/// provenance. `permission.evaluate` and `proposal.submit` both call
/// [`evaluate_action`], so an exact tool exception cannot drift between them.
pub struct PermissionEvaluation {
    pub axes: ActionAxes,
    pub authorization_source: Option<&'static str>,
    pub schema_digest: Option<String>,
}

fn required_tier(decision: &GateDecision) -> PermissionTier {
    match decision {
        GateDecision::Allow { required, .. }
        | GateDecision::NeedsApproval { required, .. }
        | GateDecision::Deny { required, .. } => *required,
    }
}

/// Evaluate one action with an optional exact agent/tool override. The risk
/// classifier still supplies `required` and `reversibility`; an override only
/// changes authorization. Both identifiers are literal map keys.
pub fn evaluate_action(
    gate: &car_policy::PermissionGate,
    policy: &AgentPermissionPolicy,
    agent_id: Option<&str>,
    action: &Action,
    callback_schema_digest: Option<&str>,
    ceiling: Option<PermissionTier>,
    ledger: &car_policy::ApprovalLedger,
) -> PermissionEvaluation {
    let mut axes = gate.evaluate_axes(action, ceiling, Some(ledger));
    let Some((agent_id, tool)) = agent_id
        .zip(action.tool.as_deref())
        .filter(|_| action.action_type == ActionType::ToolCall)
    else {
        return PermissionEvaluation {
            axes,
            authorization_source: None,
            schema_digest: None,
        };
    };
    let Some(rule) = policy.resolve_tool(agent_id, tool) else {
        return PermissionEvaluation {
            axes,
            authorization_source: None,
            schema_digest: None,
        };
    };

    let fingerprint = car_policy::action_fingerprint(action);
    if ledger
        .lookup(&fingerprint)
        .is_some_and(|record| record.decision == ApprovalDecision::Rejected)
    {
        return PermissionEvaluation {
            axes,
            authorization_source: Some(APPROVAL_LEDGER_SOURCE),
            schema_digest: None,
        };
    }

    let required = required_tier(&axes.decision);
    let granted = ceiling
        .map(|value| gate.granted_tier().min(value))
        .unwrap_or_else(|| gate.granted_tier());
    let ceiling_blocks_override = ceiling.is_some_and(|value| !value.covers(required));
    let authorization_source = match rule.mode {
        ApprovalMode::AlwaysAllow
            if rule.schema_digest.as_deref() == callback_schema_digest
                && callback_schema_digest.is_some() =>
        {
            match axes.decision {
                GateDecision::NeedsApproval { .. } if !ceiling_blocks_override => {
                    axes.decision = GateDecision::Allow { required, granted };
                    Some(AGENT_TOOL_OVERRIDE_SOURCE)
                }
                GateDecision::Allow { .. }
                    if ledger
                        .lookup(&fingerprint)
                        .is_some_and(|record| record.decision == ApprovalDecision::Approved) =>
                {
                    Some(APPROVAL_LEDGER_SOURCE)
                }
                _ => None,
            }
        }
        ApprovalMode::AlwaysAllow => None,
        ApprovalMode::Deny => {
            axes.decision = GateDecision::Deny {
                required,
                fingerprint,
                reason: format!(
                    "exact tool '{tool}' is denied for agent '{agent_id}' by host policy"
                ),
            };
            Some(AGENT_TOOL_OVERRIDE_SOURCE)
        }
        // Keep existing approval/rejection ledger decisions and the mandatory
        // HITL result. If the base tier alone would allow the action, raise the
        // exact tool's configured approval requirement here. An already-
        // approved fingerprint must remain admissible or the operator could
        // never complete the approve -> re-submit loop.
        ApprovalMode::RequireApproval => match axes.decision {
            decision @ GateDecision::Allow { .. }
                if ledger
                    .lookup(&fingerprint)
                    .is_some_and(|record| record.decision == ApprovalDecision::Approved) =>
            {
                axes.decision = decision;
                Some(APPROVAL_LEDGER_SOURCE)
            }
            GateDecision::Allow { .. } => {
                axes.decision = GateDecision::NeedsApproval {
                    required,
                    granted,
                    fingerprint,
                    reason: format!(
                        "exact tool '{tool}' requires approval for agent '{agent_id}' by host policy"
                    ),
                };
                Some(AGENT_TOOL_OVERRIDE_SOURCE)
            }
            _ => None,
        },
    };

    PermissionEvaluation {
        axes,
        authorization_source,
        schema_digest: (authorization_source == Some(AGENT_TOOL_OVERRIDE_SOURCE))
            .then(|| callback_schema_digest.map(str::to_string))
            .flatten(),
    }
}

/// Enforces the session's granted permission tier on every submitted proposal.
///
/// The authorization inputs are shared handles, never owned copies:
/// - `gate` is the session's own [`car_policy::PermissionGate`], so the tier
///   the `permission.*` RPCs report is the tier enforced here.
/// - `ledger` is the daemon-wide approval ledger, so a decision recorded on
///   the host connection clears an escalation raised on an agent connection,
///   and survives a restart.
pub struct PermissionAdmissionGate {
    gate: Arc<RwLock<car_policy::PermissionGate>>,
    ledger: Arc<RwLock<car_policy::ApprovalLedger>>,
    authenticated: Arc<AtomicBool>,
    agent_id: Arc<Mutex<Option<String>>>,
    callback_tool_schema_digests: Arc<RwLock<HashMap<String, String>>>,
    registry: Arc<car_engine::ToolRegistry>,
    memgine: Option<Arc<Mutex<car_memgine::MemgineEngine>>>,
    log: Option<Arc<Mutex<car_eventlog::EventLog>>>,
}

impl PermissionAdmissionGate {
    /// Build a gate over a session's permission gate and the shared daemon
    /// approval ledger. Pass the very same `Arc`s the `permission.*` handlers
    /// use — a second `PermissionGate` instance is the bug class this exists
    /// to close.
    pub fn new(
        gate: Arc<RwLock<car_policy::PermissionGate>>,
        ledger: Arc<RwLock<car_policy::ApprovalLedger>>,
    ) -> Self {
        Self {
            gate,
            ledger,
            authenticated: Arc::new(AtomicBool::new(false)),
            agent_id: Arc::new(Mutex::new(None)),
            callback_tool_schema_digests: Arc::new(RwLock::new(HashMap::new())),
            registry: Arc::new(car_engine::ToolRegistry::new()),
            memgine: None,
            log: None,
        }
    }

    pub fn with_authenticated_agent(
        mut self,
        authenticated: Arc<AtomicBool>,
        agent_id: Arc<Mutex<Option<String>>>,
    ) -> Self {
        self.authenticated = authenticated;
        self.agent_id = agent_id;
        self
    }

    pub fn with_event_log(mut self, log: Arc<Mutex<car_eventlog::EventLog>>) -> Self {
        self.log = Some(log);
        self
    }

    pub fn with_callback_tools(
        mut self,
        callback_tool_schema_digests: Arc<RwLock<HashMap<String, String>>>,
        registry: Arc<car_engine::ToolRegistry>,
    ) -> Self {
        self.callback_tool_schema_digests = callback_tool_schema_digests;
        self.registry = registry;
        self
    }

    pub fn with_skill_memgine(mut self, memgine: Arc<Mutex<car_memgine::MemgineEngine>>) -> Self {
        self.memgine = Some(memgine);
        self
    }
}

pub async fn eligible_callback_tool_digests(
    callbacks: &RwLock<HashMap<String, String>>,
    registry: &car_engine::ToolRegistry,
) -> HashMap<String, String> {
    let mut eligible = callbacks.read().await.clone();
    for server_owned in registry.names().await {
        eligible.remove(&server_owned);
    }
    eligible
}

fn decision_audit_data(
    evaluation: &PermissionEvaluation,
    agent_id: &str,
    action: &Action,
) -> HashMap<String, serde_json::Value> {
    let mut data = HashMap::new();
    data.insert("agent_id".into(), agent_id.into());
    data.insert(
        "tool".into(),
        action.tool.as_deref().unwrap_or_default().into(),
    );
    data.insert(
        "authorization_source".into(),
        evaluation.authorization_source.unwrap_or_default().into(),
    );
    if let Some(digest) = evaluation.schema_digest.as_deref() {
        data.insert("authorization_schema_digest".into(), digest.into());
    }
    data.insert(
        "reversibility".into(),
        evaluation.axes.reversibility.as_str().into(),
    );
    match &evaluation.axes.decision {
        GateDecision::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());
        }
        GateDecision::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());
        }
        GateDecision::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 AdmissionGate for PermissionAdmissionGate {
    fn name(&self) -> &str {
        "permission"
    }

    async fn check(&self, proposal: &ActionProposal, _ctx: &GateContext<'_>) -> GateOutcome {
        let agent_id = if self.authenticated.load(Ordering::Acquire) {
            self.agent_id.lock().await.clone()
        } else {
            None
        };
        let policy = if agent_id.is_some() {
            crate::agent_permissions::load_policy()
        } else {
            AgentPermissionPolicy::default()
        };
        let ceiling = if agent_id.is_some() {
            match (
                self.memgine.as_ref(),
                proposal
                    .context
                    .get(car_engine::SKILL_CONTEXT_KEY)
                    .and_then(serde_json::Value::as_str),
            ) {
                (Some(memgine), Some(skill)) => memgine
                    .lock()
                    .await
                    .skill_meta(skill)
                    .and_then(|meta| meta.deployment_tier),
                _ => None,
            }
        } else {
            None
        };
        let callback_tools =
            eligible_callback_tool_digests(&self.callback_tool_schema_digests, &self.registry)
                .await;
        // Lock order is gate-then-ledger, matching every `permission.*`
        // handler (evaluate/pending read both in that order; approve/reject
        // reads the gate then writes the ledger), so admission cannot
        // deadlock against a concurrent approval on the same connection.
        let gate = self.gate.read().await;
        let ledger = self.ledger.read().await;

        let mut denied: HashSet<String> = HashSet::new();
        let mut deny_notes: Vec<String> = Vec::new();
        let mut escalate: HashSet<String> = HashSet::new();
        let mut escalation_notes: Vec<String> = Vec::new();
        let mut fingerprints: Vec<String> = Vec::new();

        for action in &proposal.actions {
            let evaluation = evaluate_action(
                &gate,
                &policy,
                agent_id.as_deref(),
                action,
                action
                    .tool
                    .as_deref()
                    .and_then(|tool| callback_tools.get(tool))
                    .map(String::as_str),
                ceiling,
                &ledger,
            );
            if evaluation.authorization_source.is_some() {
                if let (Some(log), Some(agent_id)) = (&self.log, agent_id.as_deref()) {
                    log.lock().await.append(
                        car_eventlog::EventKind::PermissionDecision,
                        Some(&action.id),
                        Some(&proposal.id),
                        decision_audit_data(&evaluation, agent_id, action),
                    );
                }
            }
            match evaluation.axes.decision {
                car_policy::GateDecision::Allow { .. } => {}
                car_policy::GateDecision::Deny {
                    required,
                    fingerprint,
                    reason,
                } => {
                    denied.insert(action.id.clone());
                    deny_notes.push(format!(
                        "action '{}' requires {} and was {} (fingerprint: {fingerprint})",
                        action.id,
                        required.as_str(),
                        reason,
                    ));
                }
                car_policy::GateDecision::NeedsApproval {
                    required,
                    granted,
                    fingerprint,
                    reason,
                } => {
                    escalate.insert(action.id.clone());
                    escalation_notes.push(format!(
                        "action '{}' requires {} but the session is granted {}{reason} \
                         (approve fingerprint: {fingerprint})",
                        action.id,
                        required.as_str(),
                        granted.as_str(),
                    ));
                    fingerprints.push(fingerprint);
                }
            }
        }

        // Fail-closed: a standing operator rejection is not resolvable by an
        // approval elsewhere in the same proposal, so a Deny anywhere sinks the
        // whole thing regardless of what else escalated. (The engine's own
        // aggregation takes the same stance — a hard reject is never
        // approval-resolvable.)
        if !denied.is_empty() {
            return GateOutcome::Reject {
                blocked: denied,
                reason: format!(
                    "operator previously rejected this operation: {}",
                    deny_notes.join("; ")
                ),
            };
        }

        if escalate.is_empty() {
            return GateOutcome::Allow;
        }

        // Sorted + deduped so the same action set in a different proposal order
        // yields the same escalation identity.
        fingerprints.sort();
        fingerprints.dedup();
        GateOutcome::NeedsApproval {
            actions: escalate,
            fingerprint: format!("permission:{}", fingerprints.join(",")),
            reason: format!(
                "action(s) exceed the session's granted permission tier and require \
                 human approval: {}",
                escalation_notes.join("; ")
            ),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use car_ir::{Action, ActionType};
    use car_policy::{
        action_fingerprint, AgentPermissionPolicy, ApprovalDecision, ApprovalLedger, ApprovalMode,
        GateDecision, PermissionGate, PermissionTier,
    };
    use std::collections::HashMap;

    fn state_write(id: &str, key: &str) -> Action {
        let mut a = Action::new(ActionType::StateWrite);
        a.id = id.to_string();
        a.parameters
            .insert("key".to_string(), serde_json::Value::from(key));
        a.parameters
            .insert("value".to_string(), serde_json::Value::from("v"));
        a.max_retries = 0;
        a
    }

    /// "deploy" is in the classifier's full-access keyword set.
    fn full_access_action(id: &str) -> Action {
        let mut a = Action::new(ActionType::ToolCall);
        a.id = id.to_string();
        a.tool = Some("deploy_service".to_string());
        a.max_retries = 0;
        a
    }

    fn newsroom_publish(id: &str, edition_id: &str) -> Action {
        let mut action = Action::new(ActionType::ToolCall);
        action.id = id.to_string();
        action.tool = Some("newsroom.publish".to_string());
        action
            .parameters
            .insert("edition_id".into(), edition_id.into());
        action
            .parameters
            .insert("delivery".into(), "send email".into());
        action
    }

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

    fn build(
        granted: PermissionTier,
        ledger: ApprovalLedger,
    ) -> (
        PermissionAdmissionGate,
        Arc<RwLock<car_policy::PermissionGate>>,
    ) {
        let gate = Arc::new(RwLock::new(PermissionGate::new(granted)));
        let ledger = Arc::new(RwLock::new(ledger));
        (PermissionAdmissionGate::new(gate.clone(), ledger), gate)
    }

    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 action_within_the_grant_is_allowed() {
        let (gate, _) = build(PermissionTier::SandboxEdit, ApprovalLedger::new());
        let (s, v) = (HashMap::new(), HashMap::new());
        let p = proposal(vec![state_write("a", "k")]);
        assert!(matches!(
            gate.check(&p, &ctx(&s, &v)).await,
            GateOutcome::Allow
        ));
    }

    /// The reported defect: a state_write on a `read_only` session. The gate
    /// escalates it instead of letting it through, and names the action's own
    /// fingerprint so the operator can approve exactly that operation.
    #[tokio::test]
    async fn action_above_the_grant_escalates() {
        let (gate, _) = build(PermissionTier::ReadOnly, ApprovalLedger::new());
        let (s, v) = (HashMap::new(), HashMap::new());
        let action = state_write("a", "k");
        let expected_fp = action_fingerprint(&action);
        let p = proposal(vec![action]);
        match gate.check(&p, &ctx(&s, &v)).await {
            GateOutcome::NeedsApproval {
                actions,
                fingerprint,
                reason,
            } => {
                assert!(actions.contains("a"));
                assert!(fingerprint.starts_with("permission:"));
                assert!(fingerprint.contains(&expected_fp));
                // Required + granted tier and the approvable fingerprint are
                // all in the reason — it is what reaches the caller.
                assert!(reason.contains("sandbox_edit"), "{reason}");
                assert!(reason.contains("read_only"), "{reason}");
                assert!(reason.contains(&expected_fp), "{reason}");
            }
            other => panic!("expected escalation, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn a_recorded_rejection_denies() {
        let action = state_write("a", "k");
        let mut ledger = ApprovalLedger::new();
        ledger
            .record_decision(
                &action_fingerprint(&action),
                PermissionTier::SandboxEdit,
                ApprovalDecision::Rejected,
                "operator",
                "not this one",
                None,
            )
            .expect("in-memory ledger cannot fail");
        // Granted tier would otherwise cover it — the standing rejection wins.
        let (gate, _) = build(PermissionTier::FullAccess, ledger);
        let (s, v) = (HashMap::new(), HashMap::new());
        let p = proposal(vec![action]);
        match gate.check(&p, &ctx(&s, &v)).await {
            GateOutcome::Reject { blocked, reason } => {
                assert!(blocked.contains("a"));
                assert!(reason.contains("previously rejected"), "{reason}");
            }
            other => panic!("expected reject, got {other:?}"),
        }
    }

    /// The approve → re-submit loop: a recorded approval makes the very same
    /// proposal admissible, with no escalation raised at all.
    #[tokio::test]
    async fn a_recorded_approval_allows() {
        let action = state_write("a", "k");
        let mut ledger = ApprovalLedger::new();
        ledger
            .record_decision(
                &action_fingerprint(&action),
                PermissionTier::SandboxEdit,
                ApprovalDecision::Approved,
                "operator",
                "reviewed",
                None,
            )
            .expect("in-memory ledger cannot fail");
        let (gate, _) = build(PermissionTier::ReadOnly, ledger);
        let (s, v) = (HashMap::new(), HashMap::new());
        let p = proposal(vec![action]);
        assert!(matches!(
            gate.check(&p, &ctx(&s, &v)).await,
            GateOutcome::Allow
        ));
    }

    /// Only the offending actions are named — but the whole proposal is held,
    /// because partial execution of a plan whose later steps need a human is
    /// the outcome admission exists to prevent.
    #[tokio::test]
    async fn multi_action_escalation_names_only_the_offenders() {
        let (gate, _) = build(PermissionTier::SandboxEdit, ApprovalLedger::new());
        let (s, v) = (HashMap::new(), HashMap::new());
        let ok = state_write("a1", "k");
        let bad1 = full_access_action("a2");
        let bad2 = full_access_action("a3");
        let fp2 = action_fingerprint(&bad2);
        let p = proposal(vec![ok, bad1, bad2]);
        match gate.check(&p, &ctx(&s, &v)).await {
            GateOutcome::NeedsApproval {
                actions,
                fingerprint,
                ..
            } => {
                assert!(!actions.contains("a1"), "the in-grant write is not blamed");
                assert!(actions.contains("a2"));
                assert!(actions.contains("a3"));
                // a2 and a3 are the same operation, so they share a
                // fingerprint — the composite dedupes it.
                assert_eq!(fingerprint, format!("permission:{fp2}"));
            }
            other => panic!("expected escalation, got {other:?}"),
        }
    }

    /// A live `permission.set_tier` is visible on the next check, because the
    /// gate holds the session's gate rather than a snapshot of its tier.
    #[tokio::test]
    async fn tier_changes_take_effect_on_the_shared_gate() {
        let (gate, shared) = build(PermissionTier::ReadOnly, ApprovalLedger::new());
        let (s, v) = (HashMap::new(), HashMap::new());
        let p = proposal(vec![state_write("a", "k")]);
        assert!(matches!(
            gate.check(&p, &ctx(&s, &v)).await,
            GateOutcome::NeedsApproval { .. }
        ));
        shared
            .write()
            .await
            .set_granted_tier(PermissionTier::SandboxEdit);
        assert!(matches!(
            gate.check(&p, &ctx(&s, &v)).await,
            GateOutcome::Allow
        ));
    }

    #[test]
    fn exact_agent_tool_override_changes_authorization_not_risk_axes() {
        const DIGEST: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let gate = PermissionGate::new(PermissionTier::SandboxEdit);
        let ledger = ApprovalLedger::new();
        let mut policy = AgentPermissionPolicy::default();
        policy.set_tool(
            "daily-continuity-newsroom",
            "newsroom.publish",
            ApprovalMode::AlwaysAllow,
            Some(DIGEST.into()),
        );

        for (action_id, edition_id) in [("publish-1", "2026-09-04"), ("publish-2", "rerun-2")] {
            let action = newsroom_publish(action_id, edition_id);
            let evaluation = evaluate_action(
                &gate,
                &policy,
                Some("daily-continuity-newsroom"),
                &action,
                Some(DIGEST),
                None,
                &ledger,
            );
            assert!(matches!(
                evaluation.axes.decision,
                GateDecision::Allow {
                    required: PermissionTier::FullAccess,
                    ..
                }
            ));
            assert_eq!(
                evaluation.axes.reversibility,
                car_ir::Reversibility::Irreversible
            );
            assert_eq!(
                evaluation.authorization_source,
                Some(AGENT_TOOL_OVERRIDE_SOURCE)
            );
        }

        for (agent, tool) in [
            ("daily-continuity-newsroom", "mail.send"),
            ("daily-continuity-newsroom", "deploy_service"),
            ("another-agent", "newsroom.publish"),
        ] {
            let mut action = newsroom_publish("other", "2026-09-04");
            action.tool = Some(tool.to_string());
            let evaluation =
                evaluate_action(&gate, &policy, Some(agent), &action, None, None, &ledger);
            assert!(matches!(
                evaluation.axes.decision,
                GateDecision::NeedsApproval { .. }
            ));
            assert_eq!(evaluation.authorization_source, None);
        }

        let unbound = newsroom_publish("unbound", "2026-09-04");
        assert!(matches!(
            evaluate_action(&gate, &policy, None, &unbound, None, None, &ledger)
                .axes
                .decision,
            GateDecision::NeedsApproval { .. }
        ));
    }

    #[test]
    fn exact_deny_and_require_approval_override_base_tier_allow() {
        let gate = PermissionGate::new(PermissionTier::SandboxEdit);
        let mut ledger = ApprovalLedger::new();
        let action = state_write("a", "k");
        let mut policy = AgentPermissionPolicy::default();

        policy.set_tool("agent", "", ApprovalMode::Deny, None);
        // State-write actions have no tool identity, so tool policy cannot be
        // smuggled onto another action kind.
        assert!(matches!(
            evaluate_action(&gate, &policy, Some("agent"), &action, None, None, &ledger,)
                .axes
                .decision,
            GateDecision::Allow { .. }
        ));

        let mut tool = Action::new(ActionType::ToolCall);
        tool.tool = Some("safe.read".into());
        policy.set_tool("agent", "safe.read", ApprovalMode::Deny, None);
        assert!(matches!(
            evaluate_action(&gate, &policy, Some("agent"), &tool, None, None, &ledger,)
                .axes
                .decision,
            GateDecision::Deny { .. }
        ));

        policy.set_tool("agent", "safe.read", ApprovalMode::RequireApproval, None);
        assert!(matches!(
            evaluate_action(&gate, &policy, Some("agent"), &tool, None, None, &ledger,)
                .axes
                .decision,
            GateDecision::NeedsApproval { .. }
        ));

        ledger
            .record_decision(
                &action_fingerprint(&tool),
                PermissionTier::SandboxEdit,
                ApprovalDecision::Approved,
                "operator",
                "reviewed",
                None,
            )
            .expect("in-memory ledger cannot fail");
        assert!(matches!(
            evaluate_action(&gate, &policy, Some("agent"), &tool, None, None, &ledger,)
                .axes
                .decision,
            GateDecision::Allow { .. }
        ));
    }

    #[test]
    fn durable_rejection_beats_matching_always_allow_override() {
        const DIGEST: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let gate = PermissionGate::new(PermissionTier::SandboxEdit);
        let action = newsroom_publish("publish-rejected", "2026-09-04");
        let mut ledger = ApprovalLedger::new();
        ledger
            .record_decision(
                &action_fingerprint(&action),
                PermissionTier::FullAccess,
                ApprovalDecision::Rejected,
                "operator",
                "explicit rejection",
                None,
            )
            .unwrap();
        let mut policy = AgentPermissionPolicy::default();
        policy.set_tool(
            "daily-continuity-newsroom",
            "newsroom.publish",
            ApprovalMode::AlwaysAllow,
            Some(DIGEST.into()),
        );

        let evaluation = evaluate_action(
            &gate,
            &policy,
            Some("daily-continuity-newsroom"),
            &action,
            Some(DIGEST),
            None,
            &ledger,
        );
        assert!(matches!(
            evaluation.axes.decision,
            GateDecision::Deny { .. }
        ));
        assert_eq!(
            evaluation.authorization_source,
            Some(APPROVAL_LEDGER_SOURCE)
        );
    }

    #[test]
    fn tool_field_cannot_smuggle_override_onto_non_tool_action() {
        const DIGEST: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let gate = PermissionGate::new(PermissionTier::ReadOnly);
        let ledger = ApprovalLedger::new();
        let mut action = state_write("write", "key");
        action.tool = Some("newsroom.publish".into());
        let mut policy = AgentPermissionPolicy::default();
        policy.set_tool(
            "daily-continuity-newsroom",
            "newsroom.publish",
            ApprovalMode::AlwaysAllow,
            Some(DIGEST.into()),
        );

        let evaluation = evaluate_action(
            &gate,
            &policy,
            Some("daily-continuity-newsroom"),
            &action,
            Some(DIGEST),
            None,
            &ledger,
        );
        assert!(matches!(
            evaluation.axes.decision,
            GateDecision::NeedsApproval { .. }
        ));
        assert_eq!(evaluation.authorization_source, None);
    }
}