Skip to main content

adk_core/
approval.rs

1//! Approval service: an inbox of approval requests over an [`ApprovalStore`].
2//!
3//! A call held for approval is recorded in the run's [`ApprovalStore`] and, when the run
4//! has an [`ApprovalService`], submitted to it as an [`ApprovalRequest`] carrying an
5//! [`ApprovalPolicy`]: who may approve, how many distinct approvers it needs, whether
6//! the requester may approve their own call, when it escalates, and when it expires.
7//! Approvers list their [`inbox`](ApprovalService::inbox) and
8//! [`decide`](ApprovalService::decide); the decision that resolves the request is written
9//! to the store under the call's fingerprint, wakes the waiting durable run if one is
10//! attached, and is otherwise picked up by the next run, which resumes the held call.
11//!
12//! | Action | Effect |
13//! |--------|--------|
14//! | [`Approve`](ApprovalAction::Approve) | Counts toward the quorum; the call executes once the quorum is met |
15//! | [`Edit`](ApprovalAction::Edit) | Approves with substituted arguments; earlier approvals of other arguments stop counting. The edited call passes the [`ToolPolicy`](crate::ToolPolicy) again before it executes |
16//! | [`Reject`](ApprovalAction::Reject) | Refuses the call at once, with the reason reported to the model |
17//! | [`Respond`](ApprovalAction::Respond) | Does not run the call; the response is reported to the model in its place |
18//!
19//! Every change to a request is a compare-and-swap on its
20//! [`version`](ApprovalRequest::version), so of two approvers deciding the same version
21//! one wins and the other receives `approval.version_conflict`. [`tick`](ApprovalService::tick),
22//! driven by the service's [`Clock`], expires overdue requests (denying the call) and
23//! fires escalation steps, each exactly once.
24//!
25//! # Example
26//!
27//! ```rust
28//! use std::sync::Arc;
29//! use adk_core::principal::SubjectRef;
30//! use adk_core::{
31//!     ApprovalDecision, ApprovalPolicy, ApprovalRequest, ApprovalScope, ApprovalService,
32//!     ApprovalState, ApproverSelector, InMemoryApprovalStore, StoreApprovalService,
33//!     ToolConfirmationRequest,
34//! };
35//! use serde_json::json;
36//!
37//! # futures::executor::block_on(async {
38//! let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()));
39//! let call = ToolConfirmationRequest {
40//!     tool_name: "transfer".into(),
41//!     function_call_id: Some("call-1".into()),
42//!     args: json!({ "amount": 900 }),
43//!     origin: None,
44//!     acting: None,
45//!     evidence: Vec::new(),
46//! };
47//! let policy = ApprovalPolicy::new([ApproverSelector::group("finance")]).with_quorum(2);
48//! let request = service
49//!     .submit(ApprovalRequest::new("req-1", ApprovalScope::new("app", "u", "s"), &call, policy))
50//!     .await?;
51//!
52//! let first = service
53//!     .decide(&request.id, request.version,
54//!         ApprovalDecision::approve(SubjectRef::human("ana")).with_groups(["finance"]))
55//!     .await?;
56//! assert_eq!(first.state, ApprovalState::Pending);
57//! let second = service
58//!     .decide(&first.id, first.version,
59//!         ApprovalDecision::approve(SubjectRef::human("bo")).with_groups(["finance"]))
60//!     .await?;
61//! assert_eq!(second.state, ApprovalState::Approved);
62//! # Ok::<(), adk_core::AdkError>(())
63//! # }).unwrap();
64//! ```
65
66use std::fmt;
67use std::sync::Arc;
68use std::time::Duration;
69
70use async_trait::async_trait;
71use chrono::{DateTime, Utc};
72use serde::{Deserialize, Serialize};
73use serde_json::Value;
74
75use crate::principal::{ActingContext, SubjectKind, SubjectRef};
76use crate::{
77    AdkError, ApprovalScope, ApprovalStore, Clock, DurableRunStore, ErrorCategory, ErrorComponent,
78    ErrorDetails, Result, SystemClock, ToolApproval, ToolConfirmationRequest, ToolOrigin,
79};
80
81/// The most requests one [`ApprovalStore::list_requests`] page returns by default.
82pub const DEFAULT_APPROVAL_PAGE: usize = 100;
83
84/// How long after a request resolves [`ApprovalService::tick`] waits before applying an
85/// outcome that is still unapplied, so it does not race the decision that is applying it.
86pub const APPROVAL_REAPPLY_GRACE: Duration = Duration::from_secs(60);
87
88// ---------------------------------------------------------------------------
89// Policy
90// ---------------------------------------------------------------------------
91
92/// What an approver may do with a request.
93///
94/// # Example
95///
96/// ```rust
97/// use adk_core::ApprovalAction;
98///
99/// assert_eq!(serde_json::to_value(ApprovalAction::Respond).unwrap(), "respond");
100/// ```
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
102#[serde(rename_all = "camelCase")]
103pub enum ApprovalAction {
104    /// Approve the call as requested.
105    Approve,
106    /// Approve the call with substituted arguments.
107    Edit,
108    /// Refuse the call.
109    Reject,
110    /// Do not run the call; answer the model with a response instead.
111    Respond,
112}
113
114impl ApprovalAction {
115    /// Every action, the default set a request allows.
116    pub const ALL: [Self; 4] = [Self::Approve, Self::Edit, Self::Reject, Self::Respond];
117}
118
119/// How much harm the call can do, as shown to approvers.
120#[derive(
121    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
122)]
123#[serde(rename_all = "camelCase")]
124pub enum ApprovalRisk {
125    /// Routine.
126    Low,
127    /// Needs a look.
128    #[default]
129    Medium,
130    /// Needs a careful look.
131    High,
132    /// Irreversible or high-value.
133    Critical,
134}
135
136/// Who may approve: one subject, or every member of a group.
137///
138/// Group membership is not looked up by the service; the caller deciding asserts the
139/// groups the approver belongs to ([`ApprovalDecision::approver_groups`]), as its
140/// authentication established them. `adk-server` takes them from the authenticated
141/// request.
142///
143/// # Example
144///
145/// ```rust
146/// use adk_core::ApproverSelector;
147/// use adk_core::principal::SubjectRef;
148///
149/// let ana = SubjectRef::human("ana");
150/// assert!(ApproverSelector::group("finance").matches(&ana, &["finance".to_string()]));
151/// assert!(ApproverSelector::Subject(ana.clone()).matches(&ana, &[]));
152/// ```
153#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
154#[serde(rename_all = "camelCase")]
155pub enum ApproverSelector {
156    /// Exactly this subject.
157    Subject(SubjectRef),
158    /// Any subject in this group.
159    Group(String),
160}
161
162impl ApproverSelector {
163    /// Selects the person with `id`.
164    pub fn human(id: impl Into<String>) -> Self {
165        Self::Subject(SubjectRef::human(id))
166    }
167
168    /// Selects every member of `group`.
169    pub fn group(group: impl Into<String>) -> Self {
170        Self::Group(group.into())
171    }
172
173    /// Whether `subject`, a member of `groups`, is selected.
174    pub fn matches(&self, subject: &SubjectRef, groups: &[String]) -> bool {
175        match self {
176            Self::Subject(selected) => selected == subject,
177            Self::Group(group) => groups.iter().any(|member_of| member_of == group),
178        }
179    }
180}
181
182/// One escalation step: once `after` has passed since the request was created, the
183/// approvers in `to` may decide as well, and the notifiers hear about it.
184#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
185#[serde(rename_all = "camelCase")]
186pub struct EscalationStep {
187    /// Time from the request's creation to this step.
188    #[serde(rename = "afterSecs", with = "duration_secs")]
189    pub after: Duration,
190    /// Approvers added by this step.
191    pub to: Vec<ApproverSelector>,
192}
193
194/// What happens to a request nobody resolves before it expires.
195#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
196#[serde(rename_all = "camelCase")]
197#[non_exhaustive]
198pub enum ExpiryAction {
199    /// Deny the call.
200    #[default]
201    Deny,
202}
203
204/// Who must approve a request, and what happens when nobody does.
205///
206/// A request resolves as approved once [`quorum`](Self::quorum) distinct approvers approved
207/// and, when the policy has [`slots`](Self::slots), those approvers fill every slot, one
208/// distinct approver each: slots `[editor, publisher]` need an editor and a publisher who
209/// are two people, whatever order they decide in.
210///
211/// # Example
212///
213/// ```rust
214/// use adk_core::{ApprovalPolicy, ApproverSelector};
215/// use std::time::Duration;
216///
217/// let policy = ApprovalPolicy::new([ApproverSelector::group("payments")])
218///     .with_quorum(2)
219///     .escalate_after(Duration::from_secs(900), [ApproverSelector::group("cfo-office")])
220///     .expires_after(Duration::from_secs(3_600));
221/// assert!(policy.forbid_self_approval);
222/// assert!(policy.validate().is_ok());
223///
224/// // One editor and one publisher, two distinct people.
225/// let chain = ApprovalPolicy::for_slots([
226///     ApproverSelector::group("role:editor"),
227///     ApproverSelector::group("role:publisher"),
228/// ]);
229/// assert_eq!(chain.quorum, 2);
230/// assert!(chain.validate().is_ok());
231/// ```
232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233#[serde(rename_all = "camelCase")]
234pub struct ApprovalPolicy {
235    /// Who may approve from the start, with the [`slots`](Self::slots)' selectors.
236    pub approvers: Vec<ApproverSelector>,
237    /// Places distinct approvers must fill, one approver each, before the request is
238    /// approved; a selector listed twice needs two people. Whoever a slot selects may
239    /// approve. Empty for a policy that only counts approvals.
240    #[serde(default, skip_serializing_if = "Vec::is_empty")]
241    pub slots: Vec<ApproverSelector>,
242    /// How many distinct approvers must approve. A decision made through a delegation
243    /// counts for the delegator, so a delegator and their delegate count once.
244    pub quorum: u32,
245    /// Refuses decisions by the request's requester or acting agent, directly or
246    /// through a delegation.
247    pub forbid_self_approval: bool,
248    /// Escalation steps, in order of `after`.
249    #[serde(default, skip_serializing_if = "Vec::is_empty")]
250    pub escalation: Vec<EscalationStep>,
251    /// What expiry does.
252    #[serde(default)]
253    pub on_expiry: ExpiryAction,
254    /// How long a submitted request stays open when it carries no expiry of its own.
255    #[serde(
256        default,
257        rename = "expiresAfterSecs",
258        with = "option_duration_secs",
259        skip_serializing_if = "Option::is_none"
260    )]
261    pub expires_after: Option<Duration>,
262}
263
264impl ApprovalPolicy {
265    /// A policy needing one approval from `approvers`, refusing self-approval, with no
266    /// escalation or expiry.
267    pub fn new(approvers: impl IntoIterator<Item = ApproverSelector>) -> Self {
268        Self {
269            approvers: approvers.into_iter().collect(),
270            slots: Vec::new(),
271            quorum: 1,
272            forbid_self_approval: true,
273            escalation: Vec::new(),
274            on_expiry: ExpiryAction::Deny,
275            expires_after: None,
276        }
277    }
278
279    /// A policy needing one distinct approver for each of `slots`, refusing
280    /// self-approval, with a quorum of the number of slots.
281    ///
282    /// # Example
283    ///
284    /// ```rust
285    /// use adk_core::{ApprovalPolicy, ApproverSelector};
286    ///
287    /// // Two people from finance: the selector is listed twice.
288    /// let policy = ApprovalPolicy::for_slots([
289    ///     ApproverSelector::group("finance"),
290    ///     ApproverSelector::group("finance"),
291    /// ]);
292    /// assert_eq!((policy.slots.len(), policy.quorum), (2, 2));
293    /// ```
294    pub fn for_slots(slots: impl IntoIterator<Item = ApproverSelector>) -> Self {
295        let slots: Vec<ApproverSelector> = slots.into_iter().collect();
296        let quorum = u32::try_from(slots.len()).unwrap_or(u32::MAX).max(1);
297        Self { slots, quorum, ..Self::new([]) }
298    }
299
300    /// Adds slots that distinct approvers must fill.
301    #[must_use]
302    pub fn with_slots(mut self, slots: impl IntoIterator<Item = ApproverSelector>) -> Self {
303        self.slots.extend(slots);
304        self
305    }
306
307    /// Requires `quorum` distinct approvals.
308    #[must_use]
309    pub fn with_quorum(mut self, quorum: u32) -> Self {
310        self.quorum = quorum;
311        self
312    }
313
314    /// Lets the requester approve their own call.
315    #[must_use]
316    pub fn allow_self_approval(mut self) -> Self {
317        self.forbid_self_approval = false;
318        self
319    }
320
321    /// Adds an escalation step.
322    #[must_use]
323    pub fn escalate_after(
324        mut self,
325        after: Duration,
326        to: impl IntoIterator<Item = ApproverSelector>,
327    ) -> Self {
328        self.escalation.push(EscalationStep { after, to: to.into_iter().collect() });
329        self
330    }
331
332    /// Expires requests `ttl` after submission.
333    #[must_use]
334    pub fn expires_after(mut self, ttl: Duration) -> Self {
335        self.expires_after = Some(ttl);
336        self
337    }
338
339    /// Checks the policy can ever be satisfied.
340    ///
341    /// # Errors
342    ///
343    /// Returns `approval.invalid_policy` when there are neither approvers nor slots, the
344    /// quorum is zero, or escalation steps are out of order.
345    pub fn validate(&self) -> Result<()> {
346        if self.approvers.is_empty() && self.slots.is_empty() {
347            return Err(invalid(
348                "approval.invalid_policy",
349                "an approval policy needs approvers or slots",
350            ));
351        }
352        if self.quorum == 0 {
353            return Err(invalid(
354                "approval.invalid_policy",
355                "an approval quorum must be at least 1",
356            ));
357        }
358        if self.escalation.windows(2).any(|pair| pair[0].after > pair[1].after) {
359            return Err(invalid(
360                "approval.invalid_policy",
361                "escalation steps must be ordered by their `after` delay",
362            ));
363        }
364        Ok(())
365    }
366}
367
368// ---------------------------------------------------------------------------
369// Requests and decisions
370// ---------------------------------------------------------------------------
371
372/// Where a request is in its lifecycle.
373#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
374#[serde(rename_all = "camelCase")]
375pub enum ApprovalState {
376    /// Waiting for decisions.
377    Pending,
378    /// The quorum approved; the call executes.
379    Approved,
380    /// An approver rejected the call.
381    Rejected,
382    /// An approver answered instead of running the call.
383    Responded,
384    /// Nobody resolved it in time; the call is denied.
385    Expired,
386    /// Withdrawn; the call is denied.
387    Cancelled,
388}
389
390impl ApprovalState {
391    /// Every state.
392    pub const ALL: [Self; 6] = [
393        Self::Pending,
394        Self::Approved,
395        Self::Rejected,
396        Self::Responded,
397        Self::Expired,
398        Self::Cancelled,
399    ];
400
401    /// The state's stored name, as it serializes.
402    pub fn as_str(self) -> &'static str {
403        match self {
404            Self::Pending => "pending",
405            Self::Approved => "approved",
406            Self::Rejected => "rejected",
407            Self::Responded => "responded",
408            Self::Expired => "expired",
409            Self::Cancelled => "cancelled",
410        }
411    }
412
413    /// Whether no further decision changes the request.
414    pub fn is_terminal(self) -> bool {
415        !matches!(self, Self::Pending)
416    }
417}
418
419/// One approver's decision on a request.
420///
421/// The service sets [`decided_at`](Self::decided_at) from its clock and
422/// [`via_delegation`](Self::via_delegation) from the delegation it applied.
423///
424/// # Example
425///
426/// ```rust
427/// use adk_core::{ApprovalAction, ApprovalDecision};
428/// use adk_core::principal::SubjectRef;
429/// use serde_json::json;
430///
431/// let edit = ApprovalDecision::edit(SubjectRef::human("ana"), json!({ "amount": 50 }));
432/// assert_eq!(edit.kind, ApprovalAction::Edit);
433/// ```
434#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
435#[serde(rename_all = "camelCase")]
436pub struct ApprovalDecision {
437    /// Who decided.
438    pub approver: SubjectRef,
439    /// Groups the approver belongs to, as the caller's authentication established them,
440    /// or as the service's [`ApproverDirectory`] states them when it has one.
441    #[serde(default, skip_serializing_if = "Vec::is_empty")]
442    pub approver_groups: Vec<String>,
443    /// The delegator whose authority the approver acted under, if any.
444    #[serde(default, skip_serializing_if = "Option::is_none")]
445    pub via_delegation: Option<SubjectRef>,
446    /// The groups of the decision's [authority](Self::authority) — the approver's, or the
447    /// delegator's under a delegation — as the service established them when it recorded
448    /// the decision. The policy's [`slots`](ApprovalPolicy::slots) are filled from them.
449    #[serde(default, skip_serializing_if = "Vec::is_empty")]
450    pub authority_groups: Vec<String>,
451    /// What the approver did.
452    pub kind: ApprovalAction,
453    /// The substituted arguments of an [`Edit`](ApprovalAction::Edit).
454    #[serde(default, skip_serializing_if = "Option::is_none")]
455    pub edited_args: Option<Value>,
456    /// A rejection reason, or the text of a [`Respond`](ApprovalAction::Respond).
457    #[serde(default, skip_serializing_if = "Option::is_none")]
458    pub reason: Option<String>,
459    /// When the decision was made.
460    pub decided_at: DateTime<Utc>,
461}
462
463impl ApprovalDecision {
464    fn new(approver: SubjectRef, kind: ApprovalAction) -> Self {
465        Self {
466            approver,
467            approver_groups: Vec::new(),
468            via_delegation: None,
469            authority_groups: Vec::new(),
470            kind,
471            edited_args: None,
472            reason: None,
473            decided_at: Utc::now(),
474        }
475    }
476
477    /// An approval.
478    pub fn approve(approver: SubjectRef) -> Self {
479        Self::new(approver, ApprovalAction::Approve)
480    }
481
482    /// An approval with `args` in place of the call's arguments.
483    pub fn edit(approver: SubjectRef, args: Value) -> Self {
484        Self { edited_args: Some(args), ..Self::new(approver, ApprovalAction::Edit) }
485    }
486
487    /// A rejection.
488    pub fn reject(approver: SubjectRef, reason: impl Into<String>) -> Self {
489        Self { reason: Some(reason.into()), ..Self::new(approver, ApprovalAction::Reject) }
490    }
491
492    /// A response reported to the model instead of running the call.
493    pub fn respond(approver: SubjectRef, response: impl Into<String>) -> Self {
494        Self { reason: Some(response.into()), ..Self::new(approver, ApprovalAction::Respond) }
495    }
496
497    /// Sets the groups the approver belongs to.
498    #[must_use]
499    pub fn with_groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
500        self.approver_groups = groups.into_iter().map(Into::into).collect();
501        self
502    }
503
504    /// Acts under the delegation from `delegator`.
505    #[must_use]
506    pub fn via(mut self, delegator: SubjectRef) -> Self {
507        self.via_delegation = Some(delegator);
508        self
509    }
510
511    /// Sets the reason.
512    #[must_use]
513    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
514        self.reason = Some(reason.into());
515        self
516    }
517
518    /// The subject whose authority the decision counts for.
519    pub fn authority(&self) -> &SubjectRef {
520        self.via_delegation.as_ref().unwrap_or(&self.approver)
521    }
522}
523
524/// A call waiting for approval, with its policy and the decisions made so far.
525///
526/// # Example
527///
528/// ```rust
529/// use adk_core::{ApprovalPolicy, ApprovalRequest, ApprovalRisk, ApprovalScope,
530///     ApprovalState, ApproverSelector, ToolConfirmationRequest};
531/// use serde_json::json;
532///
533/// let call = ToolConfirmationRequest {
534///     tool_name: "refund".into(),
535///     function_call_id: Some("call-1".into()),
536///     args: json!({ "amount": 500, "card": "4242424242424242" }),
537///     origin: None,
538///     acting: None,
539///     evidence: Vec::new(),
540/// };
541/// let request = ApprovalRequest::new(
542///     "req-1",
543///     ApprovalScope::new("shop", "u-1", "s-1"),
544///     &call,
545///     ApprovalPolicy::new([ApproverSelector::group("support-leads")]),
546/// )
547/// .with_summary("Refund 500 USD")
548/// .with_risk(ApprovalRisk::High)
549/// .with_redacted_args(json!({ "amount": 500, "card": "****4242" }));
550/// assert_eq!(request.fingerprint, call.fingerprint());
551/// assert_eq!(request.state, ApprovalState::Pending);
552/// ```
553#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
554#[serde(rename_all = "camelCase")]
555pub struct ApprovalRequest {
556    /// Stable identifier.
557    pub id: String,
558    /// The session the call belongs to.
559    pub scope: ApprovalScope,
560    /// The call's fingerprint, the key its decision is recorded under.
561    pub fingerprint: String,
562    /// The tool called.
563    pub tool_name: String,
564    /// Who publishes the tool, from the held call: a surface tells one publisher's cards from
565    /// another's by it, never by the tool's name, which an MCP server can copy (spec 3.3 §7.1).
566    /// `None` for a call held without one, and for a request stored before the field existed.
567    #[serde(default, skip_serializing_if = "Option::is_none")]
568    pub origin: Option<ToolOrigin>,
569    /// The call's arguments as shown to approvers, with secrets removed.
570    pub args_redacted: Value,
571    /// What approvers see with the call, such as the exact image it would send: the held
572    /// call's own [`evidence`](ToolConfirmationRequest::evidence), whose digests its
573    /// [`fingerprint`](Self::fingerprint) binds, then any the route added
574    /// ([`ApprovalRoute::evidence`]). Surfaces load each image through the artifact service
575    /// with the viewer's own authorisation.
576    #[serde(default, skip_serializing_if = "Vec::is_empty")]
577    pub evidence: Vec<crate::Evidence>,
578    /// The agent making the call and on whose behalf.
579    #[serde(default, skip_serializing_if = "Option::is_none")]
580    pub acting: Option<ActingContext>,
581    /// Who asked for the call; refused as an approver under
582    /// [`forbid_self_approval`](ApprovalPolicy::forbid_self_approval).
583    #[serde(default, skip_serializing_if = "Option::is_none")]
584    pub requester: Option<SubjectRef>,
585    /// One line describing the call for approvers.
586    pub summary: String,
587    /// How much harm the call can do.
588    #[serde(default)]
589    pub risk: ApprovalRisk,
590    /// When the request was submitted.
591    pub created_at: DateTime<Utc>,
592    /// When the request expires.
593    #[serde(default, skip_serializing_if = "Option::is_none")]
594    pub expires_at: Option<DateTime<Utc>>,
595    /// What approvers may do.
596    pub allowed_actions: Vec<ApprovalAction>,
597    /// Who must approve.
598    pub policy: ApprovalPolicy,
599    /// The durable run waiting for the decision, woken when the request resolves.
600    #[serde(default, skip_serializing_if = "Option::is_none")]
601    pub run_id: Option<String>,
602    /// Incremented by every change; the compare-and-swap token for decisions.
603    pub version: u64,
604    /// Where the request is in its lifecycle.
605    pub state: ApprovalState,
606    /// Decisions so far, oldest first.
607    #[serde(default, skip_serializing_if = "Vec::is_empty")]
608    pub decisions: Vec<ApprovalDecision>,
609    /// How many escalation steps have fired.
610    #[serde(default)]
611    pub escalations_fired: u32,
612    /// When the request reached a terminal state.
613    #[serde(default, skip_serializing_if = "Option::is_none")]
614    pub resolved_at: Option<DateTime<Utc>>,
615    /// Why the request was cancelled or expired.
616    #[serde(default, skip_serializing_if = "Option::is_none")]
617    pub note: Option<String>,
618    /// Whether the resolution has been written to the store and the run woken.
619    #[serde(default)]
620    pub outcome_applied: bool,
621}
622
623impl ApprovalRequest {
624    /// A pending request for `call` in `scope` under `policy`, allowing every action, with
625    /// the call's [`origin`](Self::origin).
626    pub fn new(
627        id: impl Into<String>,
628        scope: ApprovalScope,
629        call: &ToolConfirmationRequest,
630        policy: ApprovalPolicy,
631    ) -> Self {
632        Self {
633            id: id.into(),
634            scope,
635            fingerprint: call.fingerprint(),
636            tool_name: call.tool_name.clone(),
637            origin: call.origin.clone(),
638            args_redacted: call.args.clone(),
639            evidence: call.evidence.clone(),
640            acting: None,
641            requester: None,
642            summary: format!("Approve a call to '{}'", call.tool_name),
643            risk: ApprovalRisk::Medium,
644            created_at: Utc::now(),
645            expires_at: None,
646            allowed_actions: ApprovalAction::ALL.to_vec(),
647            policy,
648            run_id: None,
649            version: 1,
650            state: ApprovalState::Pending,
651            decisions: Vec::new(),
652            escalations_fired: 0,
653            resolved_at: None,
654            note: None,
655            outcome_applied: false,
656        }
657    }
658
659    /// The deterministic ID of the request for the call with `fingerprint`, held in
660    /// `scope` since `held_since`.
661    ///
662    /// A call held again before its decision keeps its hold time in the
663    /// [`ApprovalStore`], so it maps to the same request; a call held after an earlier
664    /// decision gets a new one.
665    pub fn id_for_call(
666        scope: &ApprovalScope,
667        fingerprint: &str,
668        held_since: DateTime<Utc>,
669    ) -> String {
670        let key = serde_json::json!([
671            scope.app_name,
672            scope.user_id,
673            scope.session_id,
674            fingerprint,
675            held_since.timestamp_micros()
676        ]);
677        let digest = crate::action_ledger::json_digest(&key);
678        format!("apr_{}", digest.trim_start_matches("fnv1a128:"))
679    }
680
681    /// Sets the summary.
682    #[must_use]
683    pub fn with_summary(mut self, summary: impl Into<String>) -> Self {
684        self.summary = summary.into();
685        self
686    }
687
688    /// Sets the risk.
689    #[must_use]
690    pub fn with_risk(mut self, risk: ApprovalRisk) -> Self {
691        self.risk = risk;
692        self
693    }
694
695    /// Names who publishes the tool (spec 3.3 §7.1).
696    ///
697    /// # Example
698    ///
699    /// ```rust
700    /// use adk_core::{ApprovalPolicy, ApprovalRequest, ApprovalScope, ApproverSelector,
701    ///     ToolConfirmationRequest, ToolOrigin};
702    /// use serde_json::json;
703    ///
704    /// let call = ToolConfirmationRequest::new("verb_snooze", json!({ "item": "agenda-7" }));
705    /// let origin = ToolOrigin::new("verbs:adk-rust", &json!({ "name": "verb_snooze" }), None);
706    /// let request = ApprovalRequest::new(
707    ///     "apr-1",
708    ///     ApprovalScope::new("adk-rust", "ana", "s1"),
709    ///     &call,
710    ///     ApprovalPolicy::new([ApproverSelector::human("ana")]),
711    /// )
712    /// .with_origin(origin);
713    /// assert_eq!(request.origin.map(|origin| origin.source).as_deref(), Some("verbs:adk-rust"));
714    /// ```
715    #[must_use]
716    pub fn with_origin(mut self, origin: ToolOrigin) -> Self {
717        self.origin = Some(origin);
718        self
719    }
720
721    /// Shows approvers `args` in place of the call's arguments.
722    #[must_use]
723    pub fn with_redacted_args(mut self, args: Value) -> Self {
724        self.args_redacted = args;
725        self
726    }
727
728    /// Shows approvers `evidence` after the call's own. Only the call's own evidence is part
729    /// of its [`fingerprint`](Self::fingerprint).
730    ///
731    /// # Example
732    ///
733    /// ```rust
734    /// use adk_core::{
735    ///     ApprovalPolicy, ApprovalRequest, ApprovalScope, ApproverSelector, ArtifactLocator,
736    ///     Evidence, ImageEvidence, ToolConfirmationRequest,
737    /// };
738    /// use serde_json::json;
739    ///
740    /// let image = |digest: &str, file: &str| {
741    ///     Evidence::from(ImageEvidence::new(
742    ///         digest,
743    ///         ArtifactLocator::new("desk", "ana", "s1", file, 1),
744    ///         "image/png",
745    ///         640,
746    ///         180,
747    ///     ))
748    /// };
749    /// let crop = image("sha256:aa", "egress/crop.png");
750    /// let call = ToolConfirmationRequest::new("vision_describe", json!({ "question": "Total?" }))
751    ///     .with_evidence([crop.clone()]);
752    /// let overlay = image("sha256:bb", "egress/crop-regions.png");
753    /// let request = ApprovalRequest::new(
754    ///     "apr-1",
755    ///     ApprovalScope::new("desk", "ana", "s1"),
756    ///     &call,
757    ///     ApprovalPolicy::new([ApproverSelector::human("ana")]),
758    /// )
759    /// .with_evidence([overlay.clone()]);
760    /// assert_eq!(request.evidence, vec![crop, overlay]);
761    /// assert_eq!(request.fingerprint, call.fingerprint());
762    /// ```
763    #[must_use]
764    pub fn with_evidence(mut self, evidence: impl IntoIterator<Item = crate::Evidence>) -> Self {
765        self.evidence.extend(evidence);
766        self
767    }
768
769    /// Sets the acting context, and the requester to its `on_behalf_of` subject when no
770    /// requester is set.
771    #[must_use]
772    pub fn with_acting(mut self, acting: ActingContext) -> Self {
773        if self.requester.is_none() {
774            self.requester = acting.on_behalf_of.clone();
775        }
776        self.acting = Some(acting);
777        self
778    }
779
780    /// Sets the requester.
781    #[must_use]
782    pub fn with_requester(mut self, requester: SubjectRef) -> Self {
783        self.requester = Some(requester);
784        self
785    }
786
787    /// Attaches the durable run waiting for the decision.
788    #[must_use]
789    pub fn with_run_id(mut self, run_id: impl Into<String>) -> Self {
790        self.run_id = Some(run_id.into());
791        self
792    }
793
794    /// Sets the expiry.
795    #[must_use]
796    pub fn with_expires_at(mut self, at: DateTime<Utc>) -> Self {
797        self.expires_at = Some(at);
798        self
799    }
800
801    /// Restricts what approvers may do.
802    #[must_use]
803    pub fn with_allowed_actions(
804        mut self,
805        actions: impl IntoIterator<Item = ApprovalAction>,
806    ) -> Self {
807        self.allowed_actions = actions.into_iter().collect();
808        self
809    }
810
811    /// Whether [`args_redacted`](Self::args_redacted) are the call's own arguments, so an
812    /// [`Edit`](ApprovalAction::Edit) that starts from them changes only what the approver
813    /// changed (spec 3.3 §7.2). False when the shown arguments are a redacted view, a form
814    /// an MCP server asks for, or anything else in place of the call's, and for a request
815    /// without its fingerprint.
816    ///
817    /// # Example
818    ///
819    /// ```rust
820    /// use adk_core::{
821    ///     ApprovalPolicy, ApprovalRequest, ApprovalScope, ApproverSelector,
822    ///     ToolConfirmationRequest,
823    /// };
824    /// use serde_json::json;
825    ///
826    /// let call = ToolConfirmationRequest::new("pay", json!({ "amount": 500, "card": "4242424242424242" }));
827    /// let scope = ApprovalScope::new("shop", "ana", "s1");
828    /// let policy = ApprovalPolicy::new([ApproverSelector::human("ana")]);
829    /// let plain = ApprovalRequest::new("apr-1", scope.clone(), &call, policy.clone());
830    /// assert!(plain.shows_call_args());
831    /// let masked = ApprovalRequest::new("apr-2", scope, &call, policy)
832    ///     .with_redacted_args(json!({ "amount": 500, "card": "****4242" }));
833    /// assert!(!masked.shows_call_args());
834    /// ```
835    pub fn shows_call_args(&self) -> bool {
836        let shown = crate::tool_call_fingerprint(&self.tool_name, &self.args_redacted);
837        self.fingerprint.strip_suffix(shown.as_str()).is_some_and(|rest| rest.ends_with('\u{1f}'))
838    }
839
840    /// Whether the request still needs work: pending, or resolved but not yet applied.
841    pub fn is_open(&self) -> bool {
842        self.state == ApprovalState::Pending || !self.outcome_applied
843    }
844
845    /// The approvers who may decide now: the policy's approvers and slots, plus those of
846    /// every fired escalation step.
847    pub fn eligible_approvers(&self) -> impl Iterator<Item = &ApproverSelector> {
848        let fired = usize::try_from(self.escalations_fired).unwrap_or(usize::MAX);
849        self.policy
850            .approvers
851            .iter()
852            .chain(self.policy.slots.iter())
853            .chain(self.policy.escalation.iter().take(fired).flat_map(|step| step.to.iter()))
854    }
855
856    /// Whether `subject`, a member of `groups`, is among the
857    /// [eligible approvers](Self::eligible_approvers).
858    pub fn is_eligible(&self, subject: &SubjectRef, groups: &[String]) -> bool {
859        self.eligible_approvers().any(|selector| selector.matches(subject, groups))
860    }
861
862    /// Whether `subject` is the requester or the acting agent or its principal.
863    ///
864    /// A human and a service with the same id are the same party: a run a scheduler
865    /// started for `alice` acts for `service:alice`, and `human:alice` may not approve it.
866    pub fn is_self(&self, subject: &SubjectRef) -> bool {
867        let same_party = |other: &SubjectRef| {
868            other.id == subject.id
869                && (other.kind == subject.kind
870                    || (other.kind != SubjectKind::Agent && subject.kind != SubjectKind::Agent))
871        };
872        self.requester.as_ref().is_some_and(same_party)
873            || self.acting.as_ref().is_some_and(|acting| {
874                acting.on_behalf_of.as_ref().is_some_and(same_party)
875                    || SubjectRef::agent(&acting.agent.id) == *subject
876            })
877    }
878
879    /// The authorities whose approvals count toward the quorum, and the arguments they
880    /// approved when an [`Edit`](ApprovalAction::Edit) substituted them.
881    ///
882    /// An edit restarts the count: approvals before it approved other arguments.
883    pub fn quorum_progress(&self) -> (Vec<SubjectRef>, Option<Value>) {
884        let (counted, args) = self.counted_approvals();
885        (counted.into_iter().map(|decision| decision.authority().clone()).collect(), args)
886    }
887
888    /// The decisions that count toward the quorum, one per authority, and the arguments
889    /// an [`Edit`](ApprovalAction::Edit) substituted.
890    fn counted_approvals(&self) -> (Vec<&ApprovalDecision>, Option<Value>) {
891        let mut approvals: Vec<&ApprovalDecision> = Vec::new();
892        let mut args = None;
893        for decision in &self.decisions {
894            match decision.kind {
895                ApprovalAction::Approve => {
896                    if !approvals.iter().any(|held| held.authority() == decision.authority()) {
897                        approvals.push(decision);
898                    }
899                }
900                ApprovalAction::Edit => {
901                    approvals.clear();
902                    approvals.push(decision);
903                    args = decision.edited_args.clone();
904                }
905                ApprovalAction::Reject | ApprovalAction::Respond => {}
906            }
907        }
908        (approvals, args)
909    }
910
911    /// The policy's [slots](ApprovalPolicy::slots) the counted approvals leave unfilled,
912    /// each approver filling at most one: empty once every slot has its own approver.
913    ///
914    /// # Example
915    ///
916    /// ```rust
917    /// use adk_core::principal::SubjectRef;
918    /// use adk_core::{ApprovalDecision, ApprovalPolicy, ApprovalRequest, ApprovalScope,
919    ///     ApproverSelector, ToolConfirmationRequest};
920    /// use serde_json::json;
921    ///
922    /// let call = ToolConfirmationRequest::new("site_publish", json!({ "draft": "draft-1" }));
923    /// let editor = ApproverSelector::group("role:editor");
924    /// let publisher = ApproverSelector::group("role:publisher");
925    /// let mut request = ApprovalRequest::new(
926    ///     "apr-1",
927    ///     ApprovalScope::new("bakery", "amina", "drafts"),
928    ///     &call,
929    ///     ApprovalPolicy::for_slots([editor.clone(), publisher.clone()]),
930    /// );
931    /// let mut eva = ApprovalDecision::approve(SubjectRef::human("eva"));
932    /// eva.authority_groups = vec!["role:editor".into(), "role:publisher".into()];
933    /// request.decisions.push(eva);
934    /// assert_eq!(request.open_slots().len(), 1, "eva fills one slot, not both");
935    /// ```
936    pub fn open_slots(&self) -> Vec<&ApproverSelector> {
937        self.slot_holders()
938            .into_iter()
939            .filter(|(_, holder)| holder.is_none())
940            .map(|(slot, _)| slot)
941            .collect()
942    }
943
944    /// Each of the policy's [slots](ApprovalPolicy::slots), in order, with the counted
945    /// approval that fills it: a maximum matching of distinct approvers to slots, so the
946    /// order in which people decide never decides whether every slot can be filled.
947    ///
948    /// # Example
949    ///
950    /// ```rust
951    /// use adk_core::principal::SubjectRef;
952    /// use adk_core::{ApprovalDecision, ApprovalPolicy, ApprovalRequest, ApprovalScope,
953    ///     ApproverSelector, ToolConfirmationRequest};
954    /// use serde_json::json;
955    ///
956    /// let call = ToolConfirmationRequest::new("site_publish", json!({ "draft": "draft-1" }));
957    /// let mut request = ApprovalRequest::new(
958    ///     "apr-1",
959    ///     ApprovalScope::new("bakery", "amina", "drafts"),
960    ///     &call,
961    ///     ApprovalPolicy::for_slots([
962    ///         ApproverSelector::group("role:editor"),
963    ///         ApproverSelector::group("role:publisher"),
964    ///     ]),
965    /// );
966    /// let mut eva = ApprovalDecision::approve(SubjectRef::human("eva"));
967    /// eva.authority_groups = vec!["role:editor".into(), "role:publisher".into()];
968    /// let mut ed = ApprovalDecision::approve(SubjectRef::human("ed"));
969    /// ed.authority_groups = vec!["role:editor".into()];
970    /// request.decisions.extend([eva, ed]);
971    /// let holders: Vec<Option<&str>> = request
972    ///     .slot_holders()
973    ///     .into_iter()
974    ///     .map(|(_, holder)| holder.map(|decision| decision.authority().id.as_str()))
975    ///     .collect();
976    /// assert_eq!(holders, [Some("ed"), Some("eva")], "eva moves to the publisher's slot");
977    /// ```
978    pub fn slot_holders(&self) -> Vec<(&ApproverSelector, Option<&ApprovalDecision>)> {
979        let slots = &self.policy.slots;
980        if slots.is_empty() {
981            return Vec::new();
982        }
983        let (approvals, _) = self.counted_approvals();
984        // Augmenting paths: an approver takes a free slot they match, or one whose holder
985        // can move to another.
986        fn assign(
987            approver: usize,
988            approvals: &[&ApprovalDecision],
989            slots: &[ApproverSelector],
990            seen: &mut [bool],
991            filled_by: &mut [Option<usize>],
992        ) -> bool {
993            let decision = approvals[approver];
994            for (slot, selector) in slots.iter().enumerate() {
995                if seen[slot] || !selector.matches(decision.authority(), &decision.authority_groups)
996                {
997                    continue;
998                }
999                seen[slot] = true;
1000                let free = match filled_by[slot] {
1001                    None => true,
1002                    Some(holder) => assign(holder, approvals, slots, seen, filled_by),
1003                };
1004                if free {
1005                    filled_by[slot] = Some(approver);
1006                    return true;
1007                }
1008            }
1009            false
1010        }
1011        let mut filled_by: Vec<Option<usize>> = vec![None; slots.len()];
1012        for approver in 0..approvals.len() {
1013            let mut seen = vec![false; slots.len()];
1014            assign(approver, &approvals, slots, &mut seen, &mut filled_by);
1015        }
1016        slots
1017            .iter()
1018            .zip(filled_by)
1019            .map(|(slot, holder)| (slot, holder.map(|i| approvals[i])))
1020            .collect()
1021    }
1022
1023    /// The decision the governed path takes for the call once the request resolved, or
1024    /// `None` while it is pending.
1025    pub fn outcome(&self) -> Option<ToolApproval> {
1026        let last_reason = || self.decisions.last().and_then(|decision| decision.reason.clone());
1027        match self.state {
1028            ApprovalState::Pending => None,
1029            ApprovalState::Approved => {
1030                let approval = ToolApproval::approve();
1031                Some(match self.quorum_progress().1 {
1032                    Some(args) => approval.with_edited_args(args),
1033                    None => approval,
1034                })
1035            }
1036            ApprovalState::Rejected => {
1037                Some(ToolApproval::deny().with_message(match last_reason() {
1038                    Some(reason) => format!("the approver rejected it: {reason}"),
1039                    None => "the approver rejected it".to_string(),
1040                }))
1041            }
1042            ApprovalState::Responded => Some(ToolApproval::deny().with_message(format!(
1043                "the approver responded instead: {}",
1044                last_reason().unwrap_or_default()
1045            ))),
1046            ApprovalState::Expired => Some(
1047                ToolApproval::deny()
1048                    .with_message("the approval request expired before enough approvers decided"),
1049            ),
1050            ApprovalState::Cancelled => Some(ToolApproval::deny().with_message(match &self.note {
1051                Some(note) => format!("the approval request was cancelled: {note}"),
1052                None => "the approval request was cancelled".to_string(),
1053            })),
1054        }
1055    }
1056
1057    /// The position of this request in listing order.
1058    pub fn cursor(&self) -> ApprovalCursor {
1059        ApprovalCursor { created_at: self.created_at, id: self.id.clone() }
1060    }
1061}
1062
1063// ---------------------------------------------------------------------------
1064// Delegation
1065// ---------------------------------------------------------------------------
1066
1067/// When a delegation applies: from `not_before` up to, not including, `not_after`.
1068#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1069#[serde(rename_all = "camelCase")]
1070pub struct DelegationWindow {
1071    /// The first instant the delegation applies.
1072    pub not_before: DateTime<Utc>,
1073    /// The instant it stops applying.
1074    pub not_after: DateTime<Utc>,
1075}
1076
1077impl DelegationWindow {
1078    /// A window from `not_before` to `not_after`.
1079    pub fn new(not_before: DateTime<Utc>, not_after: DateTime<Utc>) -> Self {
1080        Self { not_before, not_after }
1081    }
1082
1083    /// Whether the window contains `at`.
1084    pub fn contains(&self, at: DateTime<Utc>) -> bool {
1085        self.not_before <= at && at < self.not_after
1086    }
1087}
1088
1089/// Which requests a delegation covers. Empty fields cover everything.
1090#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1091#[serde(rename_all = "camelCase")]
1092pub struct DelegationScope {
1093    /// Only requests from this application.
1094    #[serde(default, skip_serializing_if = "Option::is_none")]
1095    pub app_name: Option<String>,
1096    /// Only calls to these tools.
1097    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1098    pub tool_names: Vec<String>,
1099}
1100
1101impl DelegationScope {
1102    /// Whether the scope covers `request`.
1103    pub fn covers(&self, request: &ApprovalRequest) -> bool {
1104        self.app_name.as_ref().is_none_or(|app| *app == request.scope.app_name)
1105            && (self.tool_names.is_empty() || self.tool_names.contains(&request.tool_name))
1106    }
1107}
1108
1109/// Lets `to` decide in `from`'s place within a window and scope.
1110///
1111/// # Example
1112///
1113/// ```rust
1114/// use adk_core::{ApprovalDelegation, DelegationWindow};
1115/// use adk_core::principal::SubjectRef;
1116/// use chrono::{Duration, Utc};
1117///
1118/// let now = Utc::now();
1119/// let cover = ApprovalDelegation::new(
1120///     SubjectRef::human("ana"),
1121///     SubjectRef::human("bo"),
1122///     DelegationWindow::new(now, now + Duration::days(7)),
1123/// )
1124/// .with_from_groups(["finance"]);
1125/// assert!(cover.window.contains(now));
1126/// ```
1127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1128#[serde(rename_all = "camelCase")]
1129pub struct ApprovalDelegation {
1130    /// Stable identifier.
1131    pub id: String,
1132    /// The delegator.
1133    pub from: SubjectRef,
1134    /// Groups the delegator belongs to, as their authentication established them when
1135    /// delegating; the delegate may act under them.
1136    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1137    pub from_groups: Vec<String>,
1138    /// The delegate.
1139    pub to: SubjectRef,
1140    /// When it applies.
1141    pub window: DelegationWindow,
1142    /// Which requests it covers.
1143    #[serde(default)]
1144    pub scope: DelegationScope,
1145    /// When it was granted.
1146    pub created_at: DateTime<Utc>,
1147}
1148
1149impl ApprovalDelegation {
1150    /// A delegation from `from` to `to` over every request, with a fresh ID.
1151    pub fn new(from: SubjectRef, to: SubjectRef, window: DelegationWindow) -> Self {
1152        Self {
1153            id: format!("dlg_{}", uuid::Uuid::new_v4().simple()),
1154            from,
1155            from_groups: Vec::new(),
1156            to,
1157            window,
1158            scope: DelegationScope::default(),
1159            created_at: Utc::now(),
1160        }
1161    }
1162
1163    /// Sets the delegator's groups.
1164    #[must_use]
1165    pub fn with_from_groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
1166        self.from_groups = groups.into_iter().map(Into::into).collect();
1167        self
1168    }
1169
1170    /// Restricts the requests covered.
1171    #[must_use]
1172    pub fn with_scope(mut self, scope: DelegationScope) -> Self {
1173        self.scope = scope;
1174        self
1175    }
1176
1177    /// Whether the delegation lets its delegate decide `request` at `at`.
1178    pub fn applies_to(&self, request: &ApprovalRequest, at: DateTime<Utc>) -> bool {
1179        self.window.contains(at)
1180            && self.scope.covers(request)
1181            && request.is_eligible(&self.from, &self.from_groups)
1182    }
1183}
1184
1185// ---------------------------------------------------------------------------
1186// Store queries
1187// ---------------------------------------------------------------------------
1188
1189/// A position in the listing order of requests: creation time, then ID.
1190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1191#[serde(rename_all = "camelCase")]
1192pub struct ApprovalCursor {
1193    /// Creation time of the last request seen.
1194    pub created_at: DateTime<Utc>,
1195    /// ID of the last request seen.
1196    pub id: String,
1197}
1198
1199impl ApprovalCursor {
1200    /// Whether `request` lists after this position.
1201    pub fn precedes(&self, request: &ApprovalRequest) -> bool {
1202        (request.created_at, request.id.as_str()) > (self.created_at, self.id.as_str())
1203    }
1204
1205    /// Encodes the cursor as an opaque page token.
1206    pub fn encode(&self) -> String {
1207        format!("{}:{}", self.created_at.timestamp_micros(), self.id)
1208    }
1209
1210    /// Decodes a page token made by [`encode`](Self::encode).
1211    ///
1212    /// # Errors
1213    ///
1214    /// Returns `approval.invalid_cursor` for a malformed token.
1215    pub fn decode(token: &str) -> Result<Self> {
1216        let malformed = || invalid("approval.invalid_cursor", "malformed approval page cursor");
1217        let (micros, id) = token.split_once(':').ok_or_else(malformed)?;
1218        let created_at = micros
1219            .parse::<i64>()
1220            .ok()
1221            .and_then(DateTime::from_timestamp_micros)
1222            .ok_or_else(malformed)?;
1223        Ok(Self { created_at, id: id.to_string() })
1224    }
1225}
1226
1227/// Selects stored requests for [`ApprovalStore::list_requests`].
1228///
1229/// Results are ordered by creation time, then ID, and start after
1230/// [`after`](Self::after). A backend that stores creation times at microsecond
1231/// precision compares cursors at that precision too.
1232///
1233/// # Example
1234///
1235/// ```rust
1236/// use adk_core::{ApprovalRequestQuery, ApprovalState};
1237///
1238/// let query = ApprovalRequestQuery::default().with_states([ApprovalState::Pending]).with_limit(20);
1239/// assert_eq!(query.limit, 20);
1240/// ```
1241#[derive(Debug, Clone, PartialEq, Eq)]
1242#[non_exhaustive]
1243pub struct ApprovalRequestQuery {
1244    /// Only requests in one of these states; empty means any state.
1245    pub states: Vec<ApprovalState>,
1246    /// Only [open](ApprovalRequest::is_open) requests.
1247    pub open_only: bool,
1248    /// Only requests from this application.
1249    pub app_name: Option<String>,
1250    /// Only requests of this user ([`ApprovalScope::user_id`]) (spec 3.3 §10 C1).
1251    pub user_id: Option<String>,
1252    /// Only requests from sessions with this ID ([`ApprovalScope::session_id`]). A session
1253    /// is an application's, user's and session ID together: set
1254    /// [`app_name`](Self::app_name) and [`user_id`](Self::user_id) too, or use
1255    /// [`with_session`](Self::with_session), to select exactly one (spec 3.3 §10 C1).
1256    pub session_id: Option<String>,
1257    /// Only requests listing after this position.
1258    pub after: Option<ApprovalCursor>,
1259    /// At most this many requests.
1260    pub limit: usize,
1261}
1262
1263impl Default for ApprovalRequestQuery {
1264    fn default() -> Self {
1265        Self {
1266            states: Vec::new(),
1267            open_only: false,
1268            app_name: None,
1269            user_id: None,
1270            session_id: None,
1271            after: None,
1272            limit: DEFAULT_APPROVAL_PAGE,
1273        }
1274    }
1275}
1276
1277impl ApprovalRequestQuery {
1278    /// Only requests in `states`.
1279    #[must_use]
1280    pub fn with_states(mut self, states: impl IntoIterator<Item = ApprovalState>) -> Self {
1281        self.states = states.into_iter().collect();
1282        self
1283    }
1284
1285    /// Only open requests.
1286    #[must_use]
1287    pub fn open_only(mut self) -> Self {
1288        self.open_only = true;
1289        self
1290    }
1291
1292    /// Only requests from `app_name`.
1293    #[must_use]
1294    pub fn with_app_name(mut self, app_name: impl Into<String>) -> Self {
1295        self.app_name = Some(app_name.into());
1296        self
1297    }
1298
1299    /// Only requests from sessions with ID `session_id`, in any application and of any
1300    /// user unless those are set too (spec 3.3 §10 C1).
1301    ///
1302    /// # Example
1303    ///
1304    /// ```rust
1305    /// use adk_core::ApprovalRequestQuery;
1306    ///
1307    /// let query = ApprovalRequestQuery::default().with_app_name("shop").with_session_id("s-1");
1308    /// assert_eq!(query.session_id.as_deref(), Some("s-1"));
1309    /// ```
1310    #[must_use]
1311    pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
1312        self.session_id = Some(session_id.into());
1313        self
1314    }
1315
1316    /// Only requests of the user `user_id` (spec 3.3 §10 C1).
1317    ///
1318    /// # Example
1319    ///
1320    /// ```rust
1321    /// use adk_core::ApprovalRequestQuery;
1322    ///
1323    /// let query = ApprovalRequestQuery::default().with_user_id("alice");
1324    /// assert_eq!(query.user_id.as_deref(), Some("alice"));
1325    /// ```
1326    #[must_use]
1327    pub fn with_user_id(mut self, user_id: impl Into<String>) -> Self {
1328        self.user_id = Some(user_id.into());
1329        self
1330    }
1331
1332    /// Only requests from the one session `scope` names: its application, user and
1333    /// session ID (spec 3.3 §10 C1).
1334    ///
1335    /// # Example
1336    ///
1337    /// ```rust
1338    /// use adk_core::{ApprovalRequestQuery, ApprovalScope};
1339    ///
1340    /// let query =
1341    ///     ApprovalRequestQuery::default().with_session(&ApprovalScope::new("shop", "alice", "s-1"));
1342    /// assert_eq!(
1343    ///     (query.app_name.as_deref(), query.user_id.as_deref(), query.session_id.as_deref()),
1344    ///     (Some("shop"), Some("alice"), Some("s-1"))
1345    /// );
1346    /// ```
1347    #[must_use]
1348    pub fn with_session(self, scope: &ApprovalScope) -> Self {
1349        self.with_app_name(scope.app_name.clone())
1350            .with_user_id(scope.user_id.clone())
1351            .with_session_id(scope.session_id.clone())
1352    }
1353
1354    /// Starts after `cursor`.
1355    #[must_use]
1356    pub fn with_after(mut self, cursor: Option<ApprovalCursor>) -> Self {
1357        self.after = cursor;
1358        self
1359    }
1360
1361    /// Returns at most `limit` requests.
1362    #[must_use]
1363    pub fn with_limit(mut self, limit: usize) -> Self {
1364        self.limit = limit;
1365        self
1366    }
1367
1368    /// Whether `request` matches every filter except the limit.
1369    pub fn matches(&self, request: &ApprovalRequest) -> bool {
1370        (self.states.is_empty() || self.states.contains(&request.state))
1371            && (!self.open_only || request.is_open())
1372            && self.app_name.as_ref().is_none_or(|app| *app == request.scope.app_name)
1373            && self.user_id.as_ref().is_none_or(|user| *user == request.scope.user_id)
1374            && self.session_id.as_ref().is_none_or(|session| *session == request.scope.session_id)
1375            && self.after.as_ref().is_none_or(|cursor| cursor.precedes(request))
1376    }
1377}
1378
1379// ---------------------------------------------------------------------------
1380// Inbox
1381// ---------------------------------------------------------------------------
1382
1383/// What [`ApprovalService::inbox`] lists.
1384///
1385/// With an approver or groups set, the inbox holds the requests they may decide now,
1386/// directly or through a live delegation, excluding those self-approval rules refuse.
1387/// With neither set it holds every request in the selected states. An application or a
1388/// session narrows either to the requests of that application or session.
1389///
1390/// # Example
1391///
1392/// ```rust
1393/// use adk_core::InboxQuery;
1394/// use adk_core::principal::SubjectRef;
1395///
1396/// let query = InboxQuery::for_approver(SubjectRef::human("ana"), ["finance"]).with_limit(10);
1397/// assert_eq!(query.limit, 10);
1398/// ```
1399#[derive(Debug, Clone, PartialEq, Eq)]
1400#[non_exhaustive]
1401pub struct InboxQuery {
1402    /// The approver whose inbox to list.
1403    pub approver: Option<SubjectRef>,
1404    /// Groups the approver belongs to, or groups whose queue to list.
1405    pub groups: Vec<String>,
1406    /// States to list; empty means pending only.
1407    pub states: Vec<ApprovalState>,
1408    /// Only requests from this application.
1409    pub app_name: Option<String>,
1410    /// Only requests of this user ([`ApprovalScope::user_id`]) (spec 3.3 §10 C1).
1411    pub user_id: Option<String>,
1412    /// Only requests from sessions with this ID ([`ApprovalScope::session_id`]). A session
1413    /// is an application's, user's and session ID together: set
1414    /// [`app_name`](Self::app_name) and [`user_id`](Self::user_id) too, or use
1415    /// [`with_session`](Self::with_session), to select exactly one (spec 3.3 §10 C1).
1416    pub session_id: Option<String>,
1417    /// The page token from the previous page.
1418    pub cursor: Option<String>,
1419    /// Page size.
1420    pub limit: usize,
1421}
1422
1423impl Default for InboxQuery {
1424    fn default() -> Self {
1425        Self {
1426            approver: None,
1427            groups: Vec::new(),
1428            states: Vec::new(),
1429            app_name: None,
1430            user_id: None,
1431            session_id: None,
1432            cursor: None,
1433            limit: 50,
1434        }
1435    }
1436}
1437
1438impl InboxQuery {
1439    /// The pending requests `approver`, a member of `groups`, may decide.
1440    pub fn for_approver(
1441        approver: SubjectRef,
1442        groups: impl IntoIterator<Item = impl Into<String>>,
1443    ) -> Self {
1444        Self {
1445            approver: Some(approver),
1446            groups: groups.into_iter().map(Into::into).collect(),
1447            ..Self::default()
1448        }
1449    }
1450
1451    /// The pending requests members of `group` may decide.
1452    pub fn for_group(group: impl Into<String>) -> Self {
1453        Self { groups: vec![group.into()], ..Self::default() }
1454    }
1455
1456    /// Lists requests in `states` instead of pending ones.
1457    #[must_use]
1458    pub fn with_states(mut self, states: impl IntoIterator<Item = ApprovalState>) -> Self {
1459        self.states = states.into_iter().collect();
1460        self
1461    }
1462
1463    /// Only requests from `app_name`.
1464    #[must_use]
1465    pub fn with_app_name(mut self, app_name: impl Into<String>) -> Self {
1466        self.app_name = Some(app_name.into());
1467        self
1468    }
1469
1470    /// Only requests from sessions with ID `session_id`, in any application and of any
1471    /// user unless those are set too (spec 3.3 §10 C1).
1472    ///
1473    /// # Example
1474    ///
1475    /// ```rust
1476    /// use adk_core::InboxQuery;
1477    /// use adk_core::principal::SubjectRef;
1478    ///
1479    /// let query = InboxQuery::for_approver(SubjectRef::human("ana"), ["finance"])
1480    ///     .with_app_name("shop")
1481    ///     .with_user_id("alice")
1482    ///     .with_session_id("s-1");
1483    /// assert_eq!(query.session_id.as_deref(), Some("s-1"));
1484    /// ```
1485    #[must_use]
1486    pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
1487        self.session_id = Some(session_id.into());
1488        self
1489    }
1490
1491    /// Only requests of the user `user_id` (spec 3.3 §10 C1).
1492    #[must_use]
1493    pub fn with_user_id(mut self, user_id: impl Into<String>) -> Self {
1494        self.user_id = Some(user_id.into());
1495        self
1496    }
1497
1498    /// Only requests from the one session `scope` names — its application, user and
1499    /// session ID — such as the decisions one thread is waiting on (spec 3.3 §10 C1).
1500    ///
1501    /// # Example
1502    ///
1503    /// ```rust
1504    /// use adk_core::{ApprovalScope, InboxQuery};
1505    /// use adk_core::principal::SubjectRef;
1506    ///
1507    /// let query = InboxQuery::for_approver(SubjectRef::human("ana"), ["finance"])
1508    ///     .with_session(&ApprovalScope::new("shop", "alice", "s-1"));
1509    /// assert_eq!(query.user_id.as_deref(), Some("alice"));
1510    /// ```
1511    #[must_use]
1512    pub fn with_session(self, scope: &ApprovalScope) -> Self {
1513        self.with_app_name(scope.app_name.clone())
1514            .with_user_id(scope.user_id.clone())
1515            .with_session_id(scope.session_id.clone())
1516    }
1517
1518    /// Continues from a page token.
1519    #[must_use]
1520    pub fn with_cursor(mut self, cursor: Option<String>) -> Self {
1521        self.cursor = cursor;
1522        self
1523    }
1524
1525    /// Sets the page size.
1526    #[must_use]
1527    pub fn with_limit(mut self, limit: usize) -> Self {
1528        self.limit = limit;
1529        self
1530    }
1531}
1532
1533/// One page of an inbox.
1534#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1535#[serde(rename_all = "camelCase")]
1536pub struct InboxPage {
1537    /// The requests, oldest first.
1538    pub items: Vec<ApprovalRequest>,
1539    /// The token for the next page, when there may be one.
1540    #[serde(default, skip_serializing_if = "Option::is_none")]
1541    pub next_cursor: Option<String>,
1542}
1543
1544// ---------------------------------------------------------------------------
1545// Notification
1546// ---------------------------------------------------------------------------
1547
1548/// Why an [`ApprovalNotification`] was sent.
1549#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1550#[serde(rename_all = "camelCase")]
1551#[non_exhaustive]
1552pub enum ApprovalEventKind {
1553    /// A request was submitted.
1554    Submitted,
1555    /// An escalation step fired.
1556    Escalated,
1557    /// An approver decided.
1558    Decided,
1559    /// The request resolved: approved, rejected, or answered.
1560    Resolved,
1561    /// The request expired.
1562    Expired,
1563    /// The request was cancelled.
1564    Cancelled,
1565}
1566
1567/// What an [`ApprovalNotifier`] receives.
1568#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1569#[serde(rename_all = "camelCase")]
1570pub struct ApprovalNotification {
1571    /// Unique per change of the request: its ID and version. Repeats of one change carry
1572    /// the same ID, so receivers can drop duplicates.
1573    pub id: String,
1574    /// Why it was sent.
1575    pub kind: ApprovalEventKind,
1576    /// The request after the change.
1577    pub request: ApprovalRequest,
1578    /// The decision, for [`Decided`](ApprovalEventKind::Decided).
1579    #[serde(default, skip_serializing_if = "Option::is_none")]
1580    pub decision: Option<ApprovalDecision>,
1581    /// The step's position, from zero, for [`Escalated`](ApprovalEventKind::Escalated).
1582    #[serde(default, skip_serializing_if = "Option::is_none")]
1583    pub escalation_step: Option<u32>,
1584    /// When it happened.
1585    pub at: DateTime<Utc>,
1586}
1587
1588/// Tells people about approval requests: on submission, escalation, decision,
1589/// resolution, expiry, and cancellation.
1590///
1591/// Notification is best effort: the service logs a notifier's failure and carries on,
1592/// because the request's state in the store is the source of truth.
1593/// `adk_server::approvals::WebhookApprovalNotifier` delivers signed webhooks; chat,
1594/// e-mail, and paging integrations implement this trait.
1595///
1596/// # Example
1597///
1598/// ```rust
1599/// use adk_core::{ApprovalNotification, ApprovalNotifier, Result, async_trait};
1600///
1601/// #[derive(Debug)]
1602/// struct LogNotifier;
1603///
1604/// #[async_trait]
1605/// impl ApprovalNotifier for LogNotifier {
1606///     async fn notify(&self, notification: &ApprovalNotification) -> Result<()> {
1607///         tracing::info!(approval.id = %notification.request.id, "approval event");
1608///         Ok(())
1609///     }
1610/// }
1611/// ```
1612#[async_trait]
1613pub trait ApprovalNotifier: fmt::Debug + Send + Sync {
1614    /// Delivers one notification.
1615    async fn notify(&self, notification: &ApprovalNotification) -> Result<()>;
1616}
1617
1618/// Work a decided request's outcome waits for: it runs once the decision that resolved the
1619/// request is recorded, and before the outcome reaches the held call or wakes a run parked on
1620/// it.
1621///
1622/// A host uses it for what the call it lets run must already see, such as the standing rule
1623/// "Always allow" makes, which the resumed turn's next call is checked against (spec 3.3
1624/// §7.2). A hook reports its own failures; the outcome applies whatever it does.
1625///
1626/// # Example
1627///
1628/// ```rust
1629/// use adk_core::{
1630///     ApprovalDecision, ApprovalRequest, ApprovalResolution, ApprovalState, async_trait,
1631/// };
1632///
1633/// #[derive(Debug)]
1634/// struct GrantOnApproval;
1635///
1636/// #[async_trait]
1637/// impl ApprovalResolution for GrantOnApproval {
1638///     async fn resolving(&self, request: &ApprovalRequest, decision: &ApprovalDecision) {
1639///         if request.state == ApprovalState::Approved {
1640///             tracing::info!(approval.id = %request.id, approver = %decision.approver.id, "approved");
1641///         }
1642///     }
1643/// }
1644/// ```
1645#[async_trait]
1646pub trait ApprovalResolution: fmt::Debug + Send + Sync {
1647    /// Runs for `request`, just resolved by `decision`, before its outcome applies.
1648    async fn resolving(&self, request: &ApprovalRequest, decision: &ApprovalDecision);
1649}
1650
1651// ---------------------------------------------------------------------------
1652// Routing calls held by the governed path
1653// ---------------------------------------------------------------------------
1654
1655/// A call the governed path held for approval, offered to
1656/// [`ApprovalService::submit_call`].
1657#[derive(Debug, Clone, PartialEq)]
1658pub struct ApprovalCall {
1659    /// The session the call belongs to.
1660    pub scope: ApprovalScope,
1661    /// The held call, with its final arguments.
1662    pub request: ToolConfirmationRequest,
1663    /// Why the call needs approval, as reported to the model.
1664    pub reason: String,
1665    /// The agent that made the call.
1666    pub agent_name: String,
1667    /// The invocation the call was made in.
1668    pub invocation_id: String,
1669    /// The durable run executing the invocation, if any.
1670    pub run_id: Option<String>,
1671    /// The agent's acting context, if any.
1672    pub acting: Option<ActingContext>,
1673}
1674
1675/// How an [`ApprovalRouter`] wants a held call presented to approvers.
1676#[derive(Debug, Clone, PartialEq)]
1677pub struct ApprovalRoute {
1678    /// Who must approve.
1679    pub policy: ApprovalPolicy,
1680    /// The summary; defaults to the governed path's reason.
1681    pub summary: Option<String>,
1682    /// The risk.
1683    pub risk: ApprovalRisk,
1684    /// The arguments shown to approvers; defaults to the call's.
1685    pub redacted_args: Option<Value>,
1686    /// What approvers may do; defaults to every action.
1687    pub allowed_actions: Option<Vec<ApprovalAction>>,
1688    /// Evidence shown to approvers after the call's own, such as an overlay the router drew.
1689    /// The decision binds only to the call's own evidence
1690    /// ([`ToolConfirmationRequest::evidence`]).
1691    pub evidence: Vec<crate::Evidence>,
1692}
1693
1694impl ApprovalRoute {
1695    /// A route under `policy`.
1696    pub fn new(policy: ApprovalPolicy) -> Self {
1697        Self {
1698            policy,
1699            summary: None,
1700            risk: ApprovalRisk::default(),
1701            redacted_args: None,
1702            allowed_actions: None,
1703            evidence: Vec::new(),
1704        }
1705    }
1706
1707    /// Sets the summary.
1708    #[must_use]
1709    pub fn with_summary(mut self, summary: impl Into<String>) -> Self {
1710        self.summary = Some(summary.into());
1711        self
1712    }
1713
1714    /// Sets the risk.
1715    #[must_use]
1716    pub fn with_risk(mut self, risk: ApprovalRisk) -> Self {
1717        self.risk = risk;
1718        self
1719    }
1720
1721    /// Shows approvers `args` in place of the call's.
1722    #[must_use]
1723    pub fn with_redacted_args(mut self, args: Value) -> Self {
1724        self.redacted_args = Some(args);
1725        self
1726    }
1727
1728    /// Restricts what approvers may do.
1729    #[must_use]
1730    pub fn with_allowed_actions(
1731        mut self,
1732        actions: impl IntoIterator<Item = ApprovalAction>,
1733    ) -> Self {
1734        self.allowed_actions = Some(actions.into_iter().collect());
1735        self
1736    }
1737
1738    /// Shows approvers `evidence` after the call's own.
1739    #[must_use]
1740    pub fn with_evidence(mut self, evidence: impl IntoIterator<Item = crate::Evidence>) -> Self {
1741        self.evidence.extend(evidence);
1742        self
1743    }
1744}
1745
1746/// Decides how a held call becomes an [`ApprovalRequest`], or that it does not.
1747///
1748/// An [`ApprovalPolicy`] is a router that applies itself to every call; a closure
1749/// `Fn(&ApprovalCall) -> Option<ApprovalRoute>` is one too.
1750///
1751/// # Example
1752///
1753/// ```rust
1754/// use adk_core::{ApprovalCall, ApprovalPolicy, ApprovalRisk, ApprovalRoute, ApproverSelector};
1755///
1756/// let router = |call: &ApprovalCall| {
1757///     let amount = call.request.args["amount"].as_f64().unwrap_or(0.0);
1758///     let approvers = ApprovalPolicy::new([ApproverSelector::group("finance")]);
1759///     Some(if amount > 1_000.0 {
1760///         ApprovalRoute::new(approvers.with_quorum(2)).with_risk(ApprovalRisk::High)
1761///     } else {
1762///         ApprovalRoute::new(approvers)
1763///     })
1764/// };
1765/// # let _ = router;
1766/// ```
1767pub trait ApprovalRouter: Send + Sync {
1768    /// The route for `call`, or `None` to leave it held in the store only.
1769    fn route(&self, call: &ApprovalCall) -> Option<ApprovalRoute>;
1770}
1771
1772impl ApprovalRouter for ApprovalPolicy {
1773    fn route(&self, _call: &ApprovalCall) -> Option<ApprovalRoute> {
1774        Some(ApprovalRoute::new(self.clone()))
1775    }
1776}
1777
1778impl<F> ApprovalRouter for F
1779where
1780    F: Fn(&ApprovalCall) -> Option<ApprovalRoute> + Send + Sync,
1781{
1782    fn route(&self, call: &ApprovalCall) -> Option<ApprovalRoute> {
1783        self(call)
1784    }
1785}
1786
1787// ---------------------------------------------------------------------------
1788// The service
1789// ---------------------------------------------------------------------------
1790
1791/// What one [`ApprovalService::tick`] did.
1792#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1793#[serde(rename_all = "camelCase")]
1794pub struct ApprovalTick {
1795    /// Requests that expired.
1796    pub expired: Vec<String>,
1797    /// Escalation steps that fired, as request ID and step position.
1798    pub escalated: Vec<(String, u32)>,
1799    /// Resolved requests whose outcome was applied after an earlier attempt failed.
1800    pub reapplied: Vec<String>,
1801}
1802
1803/// An inbox of approval requests with quorum, delegation, escalation, and expiry.
1804///
1805/// See the [module documentation](self) for the lifecycle. [`StoreApprovalService`] is
1806/// the implementation over any [`ApprovalStore`].
1807#[async_trait]
1808pub trait ApprovalService: fmt::Debug + Send + Sync {
1809    /// Submits a request. Submitting an ID that exists returns the stored request
1810    /// unchanged, so retries are safe.
1811    ///
1812    /// # Errors
1813    ///
1814    /// Returns `approval.invalid_policy` or `approval.invalid_request` for a request
1815    /// that can never be resolved, or a store error.
1816    async fn submit(&self, request: ApprovalRequest) -> Result<ApprovalRequest>;
1817
1818    /// Submits the request for a call the governed path held, as the service's router
1819    /// presents it. Returns `None` when the service routes no request for the call.
1820    ///
1821    /// A call held again while its request is still pending gets that request back, never
1822    /// a second one (spec 3.3 §7.3).
1823    ///
1824    /// # Errors
1825    ///
1826    /// Returns a store error.
1827    async fn submit_call(&self, call: ApprovalCall) -> Result<Option<ApprovalRequest>>;
1828
1829    /// Reads a request.
1830    ///
1831    /// # Errors
1832    ///
1833    /// Returns a store error.
1834    async fn get(&self, id: &str) -> Result<Option<ApprovalRequest>>;
1835
1836    /// Lists one page of an inbox. See [`InboxQuery`].
1837    ///
1838    /// # Errors
1839    ///
1840    /// Returns `approval.invalid_cursor` or a store error.
1841    async fn inbox(&self, query: InboxQuery) -> Result<InboxPage>;
1842
1843    /// Records `decision` on the request at `expected_version`, resolving it when the
1844    /// decision completes the quorum, rejects, or responds.
1845    ///
1846    /// # Errors
1847    ///
1848    /// | Code | Category | When |
1849    /// |------|----------|------|
1850    /// | `approval.not_found` | NotFound | No request has `id` |
1851    /// | `approval.version_conflict` | Conflict | The request changed since `expected_version`; re-read it and decide again |
1852    /// | `approval.already_resolved` | Conflict | The request is no longer pending |
1853    /// | `approval.expired` | Conflict | The request is past its expiry |
1854    /// | `approval.already_decided` | Conflict | The approver's authority already counts toward the quorum |
1855    /// | `approval.not_an_approver` | Forbidden | The approver is not eligible, directly or by delegation |
1856    /// | `approval.delegation_inactive` | Forbidden | The only delegation that would make them eligible is outside its window |
1857    /// | `approval.self_approval` | Forbidden | The policy forbids self-approval and the approver, or their delegator, is the requester or acting agent |
1858    /// | `approval.action_not_allowed` | InvalidInput | The request does not allow the action, or an edit or response lacks its content |
1859    async fn decide(
1860        &self,
1861        id: &str,
1862        expected_version: u64,
1863        decision: ApprovalDecision,
1864    ) -> Result<ApprovalRequest>;
1865
1866    /// Grants a delegation.
1867    ///
1868    /// # Errors
1869    ///
1870    /// Returns `approval.invalid_delegation` for an empty window or a self-delegation,
1871    /// or a store error.
1872    async fn delegate(&self, delegation: ApprovalDelegation) -> Result<ApprovalDelegation>;
1873
1874    /// Revokes a delegation. Returns whether one was revoked.
1875    ///
1876    /// # Errors
1877    ///
1878    /// Returns a store error.
1879    async fn revoke_delegation(&self, id: &str) -> Result<bool>;
1880
1881    /// Lists the delegations granted to `to`.
1882    ///
1883    /// # Errors
1884    ///
1885    /// Returns a store error.
1886    async fn delegations_to(&self, to: &SubjectRef) -> Result<Vec<ApprovalDelegation>>;
1887
1888    /// Cancels a pending request, denying the call.
1889    ///
1890    /// # Errors
1891    ///
1892    /// Returns `approval.not_found`, `approval.already_resolved`, or
1893    /// `approval.version_conflict` when it changed concurrently.
1894    async fn cancel(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest>;
1895
1896    /// Withdraws a pending request whose call was decided another way, such as by the run's
1897    /// confirmation handler: the request is closed as cancelled, but no outcome is written
1898    /// to the store and no run is woken, so the decision that closed the call stands
1899    /// (spec 3.3 §7.3).
1900    ///
1901    /// The default cancels the request, which denies the call; [`StoreApprovalService`]
1902    /// writes nothing.
1903    ///
1904    /// # Errors
1905    ///
1906    /// As [`cancel`](Self::cancel): `approval.not_found`, `approval.already_resolved`, or
1907    /// `approval.version_conflict` when it changed concurrently.
1908    async fn withdraw(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest> {
1909        self.cancel(id, reason).await
1910    }
1911
1912    /// Expires overdue requests and fires due escalation steps, as of `now`, and
1913    /// applies resolutions an earlier failure left unapplied.
1914    ///
1915    /// Safe to call from several processes at once: each change is a compare-and-swap,
1916    /// so each expiry and each escalation step happens once.
1917    ///
1918    /// # Errors
1919    ///
1920    /// Returns a store error.
1921    async fn tick(&self, now: DateTime<Utc>) -> Result<ApprovalTick>;
1922
1923    /// The store decisions are written to, for the governed path to take them from.
1924    fn approval_store(&self) -> Option<Arc<dyn ApprovalStore>> {
1925        None
1926    }
1927
1928    /// Files held calls under `router` when the service has no router of its own, so a host
1929    /// that decides calls in an inbox, such as a kernel, receives every call the governed
1930    /// path holds. A router the service was built with keeps deciding, including to leave a
1931    /// call in the store only. Returns whether held calls reach the inbox afterwards.
1932    ///
1933    /// The default files none and answers `false`; a wrapper forwards it to the service it
1934    /// wraps.
1935    ///
1936    /// # Example
1937    ///
1938    /// ```rust
1939    /// use std::sync::Arc;
1940    /// use adk_core::{
1941    ///     ApprovalPolicy, ApprovalService, ApproverSelector, InMemoryApprovalStore,
1942    ///     StoreApprovalService,
1943    /// };
1944    ///
1945    /// let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()));
1946    /// let operator = ApprovalPolicy::new([ApproverSelector::group("operator")]);
1947    /// assert!(service.route_unrouted(Arc::new(operator)));
1948    /// ```
1949    fn route_unrouted(&self, router: Arc<dyn ApprovalRouter>) -> bool {
1950        let _ = router;
1951        false
1952    }
1953
1954    /// Adds `notifier` to a service already built, for a host built after it, such as a
1955    /// kernel that publishes each request on its event bus. Returns whether the service took
1956    /// it.
1957    ///
1958    /// The default takes none and answers `false`; a wrapper forwards it to the service it
1959    /// wraps.
1960    ///
1961    /// # Example
1962    ///
1963    /// ```rust
1964    /// use std::sync::Arc;
1965    /// use adk_core::{
1966    ///     ApprovalNotification, ApprovalNotifier, ApprovalService, InMemoryApprovalStore,
1967    ///     StoreApprovalService, async_trait,
1968    /// };
1969    ///
1970    /// #[derive(Debug)]
1971    /// struct Log;
1972    ///
1973    /// #[async_trait]
1974    /// impl ApprovalNotifier for Log {
1975    ///     async fn notify(&self, notification: &ApprovalNotification) -> adk_core::Result<()> {
1976    ///         tracing::info!(approval.id = %notification.request.id, "approval event");
1977    ///         Ok(())
1978    ///     }
1979    /// }
1980    ///
1981    /// let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()));
1982    /// assert!(service.add_notifier(Arc::new(Log)));
1983    /// ```
1984    fn add_notifier(&self, notifier: Arc<dyn ApprovalNotifier>) -> bool {
1985        let _ = notifier;
1986        false
1987    }
1988
1989    /// Adds `hook`, which runs for each request a decision resolves, after the decision is
1990    /// recorded and before the outcome applies ([`ApprovalResolution`]). Returns whether the
1991    /// service took it.
1992    ///
1993    /// The default takes none and answers `false`; a wrapper forwards it to the service it
1994    /// wraps.
1995    ///
1996    /// # Example
1997    ///
1998    /// ```rust
1999    /// use std::sync::Arc;
2000    /// use adk_core::{
2001    ///     ApprovalDecision, ApprovalRequest, ApprovalResolution, ApprovalService,
2002    ///     InMemoryApprovalStore, StoreApprovalService, async_trait,
2003    /// };
2004    ///
2005    /// #[derive(Debug)]
2006    /// struct Log;
2007    ///
2008    /// #[async_trait]
2009    /// impl ApprovalResolution for Log {
2010    ///     async fn resolving(&self, request: &ApprovalRequest, _decision: &ApprovalDecision) {
2011    ///         tracing::info!(approval.id = %request.id, "resolving");
2012    ///     }
2013    /// }
2014    ///
2015    /// let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()));
2016    /// assert!(service.add_resolution(Arc::new(Log)));
2017    /// ```
2018    fn add_resolution(&self, hook: Arc<dyn ApprovalResolution>) -> bool {
2019        let _ = hook;
2020        false
2021    }
2022
2023    /// Files a call a [`ToolReviewer`](crate::ToolReviewer) approved or denied in the run as
2024    /// a request it decided, so the inbox's history shows the decision and who made it
2025    /// (`decided_by: model:<id>` for a [`ModelApprover`](crate::ModelApprover)). Returns
2026    /// `None` when the service routes no request for the call.
2027    ///
2028    /// The run applies the verdict itself, so the request is created resolved, with its
2029    /// outcome applied: nothing is written to the store and no run is woken. Notifiers hear
2030    /// [`Decided`](ApprovalEventKind::Decided) and [`Resolved`](ApprovalEventKind::Resolved).
2031    ///
2032    /// The default files nothing and answers `None`; a wrapper forwards it to the service
2033    /// it wraps.
2034    ///
2035    /// # Errors
2036    ///
2037    /// Returns a store error, or the audit trail's when the service records decisions.
2038    ///
2039    /// # Example
2040    ///
2041    /// ```rust
2042    /// use std::sync::Arc;
2043    /// use adk_core::principal::SubjectRef;
2044    /// use adk_core::{
2045    ///     ApprovalCall, ApprovalDecision, ApprovalPolicy, ApprovalScope, ApprovalService,
2046    ///     ApprovalState, ApproverSelector, InMemoryApprovalStore, StoreApprovalService,
2047    ///     ToolConfirmationRequest,
2048    /// };
2049    /// use serde_json::json;
2050    ///
2051    /// # futures::executor::block_on(async {
2052    /// let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
2053    ///     .with_router(ApprovalPolicy::new([ApproverSelector::group("operator")]));
2054    /// let call = ApprovalCall {
2055    ///     scope: ApprovalScope::new("app", "u", "s"),
2056    ///     request: ToolConfirmationRequest::new("bash", json!({ "command": "cargo test" })),
2057    ///     reason: "host commands wait for approval".into(),
2058    ///     agent_name: "harness".into(),
2059    ///     invocation_id: "inv-1".into(),
2060    ///     run_id: None,
2061    ///     acting: None,
2062    /// };
2063    /// let reviewer = SubjectRef::service("model:claude-sonnet-5-5");
2064    /// let filed = service
2065    ///     .record_review(call, ApprovalDecision::approve(reviewer.clone()))
2066    ///     .await?
2067    ///     .unwrap();
2068    /// assert_eq!(filed.state, ApprovalState::Approved);
2069    /// assert_eq!(filed.decisions[0].approver, reviewer);
2070    /// assert!(filed.outcome_applied);
2071    /// # Ok::<(), adk_core::AdkError>(())
2072    /// # }).unwrap();
2073    /// ```
2074    async fn record_review(
2075        &self,
2076        call: ApprovalCall,
2077        decision: ApprovalDecision,
2078    ) -> Result<Option<ApprovalRequest>> {
2079        let _ = (call, decision);
2080        Ok(None)
2081    }
2082}
2083
2084/// Who belongs to which approver group, as the deployment knows it.
2085///
2086/// A [`StoreApprovalService`] with a directory takes every approver's and delegator's
2087/// membership of the groups the directory [governs](Self::governs) from it, and ignores a
2088/// caller's claim to one, so a surface cannot claim a group, such as a role in a charter,
2089/// for the person deciding. Groups the directory does not govern, such as an operator scope
2090/// the caller's authentication established, are kept as asserted. Without a directory the
2091/// service trusts every asserted group.
2092///
2093/// # Example
2094///
2095/// ```rust
2096/// use std::sync::Arc;
2097/// use adk_core::principal::SubjectRef;
2098/// use adk_core::{ApprovalRequest, ApproverDirectory, InMemoryApprovalStore, StoreApprovalService};
2099/// use async_trait::async_trait;
2100///
2101/// struct Roles;
2102///
2103/// #[async_trait]
2104/// impl ApproverDirectory for Roles {
2105///     async fn groups(
2106///         &self,
2107///         subject: &SubjectRef,
2108///         _request: &ApprovalRequest,
2109///     ) -> adk_core::Result<Vec<String>> {
2110///         Ok(match subject.id.as_str() {
2111///             "eva" => vec!["role:editor".to_string()],
2112///             _ => Vec::new(),
2113///         })
2114///     }
2115/// }
2116///
2117/// let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
2118///     .with_directory(Arc::new(Roles));
2119/// # let _ = service;
2120/// ```
2121#[async_trait]
2122pub trait ApproverDirectory: Send + Sync {
2123    /// The groups `subject` belongs to when deciding `request`.
2124    ///
2125    /// # Errors
2126    ///
2127    /// The directory's error; the service refuses the decision with it.
2128    async fn groups(&self, subject: &SubjectRef, request: &ApprovalRequest) -> Result<Vec<String>>;
2129
2130    /// Whether the directory decides membership of `group`, so a caller's claim to it is
2131    /// ignored; every group by default.
2132    fn governs(&self, group: &str) -> bool {
2133        let _ = group;
2134        true
2135    }
2136}
2137
2138/// The [`ApprovalService`] over an [`ApprovalStore`].
2139///
2140/// Durability and cross-process atomicity come from the store: on a durable backend
2141/// requests survive restarts and every process deciding through the same database sees
2142/// one winner per version.
2143///
2144/// # Example
2145///
2146/// ```rust
2147/// use std::sync::Arc;
2148/// use adk_core::{
2149///     ApprovalPolicy, ApproverSelector, InMemoryApprovalStore, RunConfig, StoreApprovalService,
2150/// };
2151///
2152/// let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
2153///     .with_router(ApprovalPolicy::new([ApproverSelector::group("ops")]));
2154/// let config = RunConfig::builder().approval_service(Arc::new(service)).build();
2155/// assert!(config.approval_store.is_some());
2156/// ```
2157pub struct StoreApprovalService {
2158    store: Arc<dyn ApprovalStore>,
2159    clock: Arc<dyn Clock>,
2160    notifiers: Vec<Arc<dyn ApprovalNotifier>>,
2161    run_store: Option<Arc<dyn DurableRunStore>>,
2162    router: Option<Arc<dyn ApprovalRouter>>,
2163    audit: Option<crate::audit_log::AuditTrail>,
2164    directory: Option<Arc<dyn ApproverDirectory>>,
2165    /// The router a host gave a service built without one (`route_unrouted`).
2166    fallback_router: std::sync::OnceLock<Arc<dyn ApprovalRouter>>,
2167    /// Notifiers a host added after the service was built (`add_notifier`).
2168    late_notifiers: std::sync::RwLock<Vec<Arc<dyn ApprovalNotifier>>>,
2169    /// What a resolved outcome waits for (`add_resolution`).
2170    resolutions: std::sync::RwLock<Vec<Arc<dyn ApprovalResolution>>>,
2171}
2172
2173impl fmt::Debug for StoreApprovalService {
2174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2175        f.debug_struct("StoreApprovalService")
2176            .field("store", &self.store)
2177            .field("clock", &self.clock)
2178            .field("notifiers", &self.notifiers)
2179            .field("run_store", &self.run_store.is_some())
2180            .field("router", &self.router.is_some())
2181            .field("fallback_router", &self.fallback_router.get().is_some())
2182            .field(
2183                "late_notifiers",
2184                &self.late_notifiers.read().unwrap_or_else(|e| e.into_inner()).len(),
2185            )
2186            .field("audit", &self.audit)
2187            .field("directory", &self.directory.is_some())
2188            .field("resolutions", &self.resolutions.read().unwrap_or_else(|e| e.into_inner()).len())
2189            .finish()
2190    }
2191}
2192
2193impl StoreApprovalService {
2194    /// A service over `store`, reading the system clock, with no notifiers, run store,
2195    /// or router. Without a router held calls stay in the store only, unless a host such
2196    /// as a kernel gives it one ([`ApprovalService::route_unrouted`]).
2197    pub fn new(store: Arc<dyn ApprovalStore>) -> Self {
2198        Self {
2199            store,
2200            clock: Arc::new(SystemClock),
2201            notifiers: Vec::new(),
2202            run_store: None,
2203            router: None,
2204            audit: None,
2205            directory: None,
2206            fallback_router: std::sync::OnceLock::new(),
2207            late_notifiers: std::sync::RwLock::new(Vec::new()),
2208            resolutions: std::sync::RwLock::new(Vec::new()),
2209        }
2210    }
2211
2212    /// Reads time from `clock`.
2213    #[must_use]
2214    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
2215        self.clock = clock;
2216        self
2217    }
2218
2219    /// Adds a notifier.
2220    #[must_use]
2221    pub fn with_notifier(mut self, notifier: Arc<dyn ApprovalNotifier>) -> Self {
2222        self.notifiers.push(notifier);
2223        self
2224    }
2225
2226    /// Wakes runs in `run_store` when their request resolves: the run the request names and
2227    /// every run of its session parked on the call
2228    /// ([`RunCheckpointRef::AwaitingApproval`](crate::RunCheckpointRef::AwaitingApproval)
2229    /// naming its fingerprint; spec 3.3 §7.3).
2230    #[must_use]
2231    pub fn with_run_store(mut self, run_store: Arc<dyn DurableRunStore>) -> Self {
2232        self.run_store = Some(run_store);
2233        self
2234    }
2235
2236    /// Routes calls held by the governed path into requests.
2237    #[must_use]
2238    pub fn with_router(mut self, router: impl ApprovalRouter + 'static) -> Self {
2239        self.router = Some(Arc::new(router));
2240        self
2241    }
2242
2243    /// Records every approver's decision in `audit` before it takes effect.
2244    ///
2245    /// The record's actor is the approver, with the delegator they acted for in the
2246    /// delegation chain; it carries the digest of the arguments shown to approvers and
2247    /// of any edited arguments, never the arguments. Under
2248    /// [`AuditFailureMode::Block`](crate::audit_log::AuditFailureMode::Block) a decision
2249    /// whose record cannot be written is refused with `audit.record_failed`.
2250    ///
2251    /// # Example
2252    ///
2253    /// ```rust
2254    /// use std::sync::Arc;
2255    /// use adk_core::audit_log::{AuditTrail, InMemoryAuditRecorder};
2256    /// use adk_core::{InMemoryApprovalStore, StoreApprovalService};
2257    ///
2258    /// let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
2259    ///     .with_audit(AuditTrail::new(Arc::new(InMemoryAuditRecorder::new())));
2260    /// # let _ = service;
2261    /// ```
2262    #[must_use]
2263    pub fn with_audit(mut self, audit: crate::audit_log::AuditTrail) -> Self {
2264        self.audit = Some(audit);
2265        self
2266    }
2267
2268    /// Takes approvers' and delegators' groups from `directory`, ignoring the groups
2269    /// callers assert (see [`ApproverDirectory`]).
2270    #[must_use]
2271    pub fn with_directory(mut self, directory: Arc<dyn ApproverDirectory>) -> Self {
2272        self.directory = Some(directory);
2273        self
2274    }
2275
2276    /// The groups of `subject` for `request`: the directory's, with the `asserted` groups it
2277    /// does not govern, when the service has one; otherwise `asserted`.
2278    async fn groups_of(
2279        &self,
2280        subject: &SubjectRef,
2281        asserted: &[String],
2282        request: &ApprovalRequest,
2283    ) -> Result<Vec<String>> {
2284        let Some(directory) = &self.directory else { return Ok(asserted.to_vec()) };
2285        let mut groups: Vec<String> =
2286            asserted.iter().filter(|group| !directory.governs(group)).cloned().collect();
2287        for group in directory.groups(subject, request).await? {
2288            if !groups.contains(&group) {
2289                groups.push(group);
2290            }
2291        }
2292        Ok(groups)
2293    }
2294
2295    async fn notify(
2296        &self,
2297        kind: ApprovalEventKind,
2298        request: &ApprovalRequest,
2299        decision: Option<&ApprovalDecision>,
2300        escalation_step: Option<u32>,
2301    ) {
2302        let late = self.late_notifiers.read().unwrap_or_else(|e| e.into_inner()).clone();
2303        if self.notifiers.is_empty() && late.is_empty() {
2304            return;
2305        }
2306        let notification = ApprovalNotification {
2307            id: format!("{}:{}", request.id, request.version),
2308            kind,
2309            request: request.clone(),
2310            decision: decision.cloned(),
2311            escalation_step,
2312            at: self.clock.now(),
2313        };
2314        for notifier in self.notifiers.iter().chain(&late) {
2315            if let Err(error) = notifier.notify(&notification).await {
2316                tracing::warn!(
2317                    approval.id = %request.id,
2318                    approval.event = ?kind,
2319                    error = %error,
2320                    "approval notifier failed"
2321                );
2322            }
2323        }
2324    }
2325
2326    /// Writes a resolved request's outcome to the store, wakes its run, and marks it
2327    /// applied. Returns the request as it now stands.
2328    ///
2329    /// A `recovering` apply writes the outcome only while the call is still pending in
2330    /// the store: `decide` clears the pending entry in the same atomic step that records
2331    /// the decision, so a missing entry means the outcome was written — and possibly
2332    /// already consumed — and must not be written twice.
2333    async fn apply(&self, request: ApprovalRequest, recovering: bool) -> Result<ApprovalRequest> {
2334        let Some(outcome) = request.outcome() else {
2335            return Ok(request);
2336        };
2337        if request.outcome_applied {
2338            return Ok(request);
2339        }
2340        let write = !recovering
2341            || self
2342                .store
2343                .pending(&request.scope)
2344                .await?
2345                .iter()
2346                .any(|entry| entry.fingerprint == request.fingerprint);
2347        if write {
2348            self.store.decide(&request.scope, &request.fingerprint, outcome).await?;
2349        }
2350        if let Some(runs) = &self.run_store {
2351            // The run the request names, and every run of the session parked on the call: a
2352            // run that held the call again while the request was open got this request back
2353            // under the earlier run's id (spec 3.3 §7.3).
2354            let mut waiting: Vec<String> = request.run_id.iter().cloned().collect();
2355            let parked = crate::RunFilter::default()
2356                .app_name(request.scope.app_name.clone())
2357                .user_id(request.scope.user_id.clone())
2358                .session_id(request.scope.session_id.clone())
2359                .states([crate::RunState::Waiting]);
2360            match runs.list(parked).await {
2361                Ok(parked) => waiting.extend(
2362                    parked
2363                        .into_iter()
2364                        .filter(|run| {
2365                            matches!(
2366                                &run.checkpoint,
2367                                Some(crate::RunCheckpointRef::AwaitingApproval { fingerprints, .. })
2368                                    if fingerprints.contains(&request.fingerprint)
2369                            )
2370                        })
2371                        .map(|run| run.run_id)
2372                        .filter(|run_id| request.run_id.as_ref() != Some(run_id)),
2373                ),
2374                Err(error) => {
2375                    tracing::warn!(approval.id = %request.id, error = %error, "could not list the runs parked on an approval");
2376                }
2377            }
2378            for run_id in waiting {
2379                if let Err(error) = runs.wake(&run_id).await {
2380                    // The decision is in the store, so the run's next attempt still takes it.
2381                    tracing::warn!(approval.id = %request.id, run.id = %run_id, error = %error, "could not wake the run waiting for an approval");
2382                }
2383            }
2384        }
2385        let mut applied = request.clone();
2386        applied.outcome_applied = true;
2387        applied.version = request.version + 1;
2388        if self.store.replace_request(&applied, request.version).await? {
2389            Ok(applied)
2390        } else {
2391            // Another process applied it first; the outcome it wrote is the same.
2392            Ok(self.store.get_request(&request.id).await?.unwrap_or(applied))
2393        }
2394    }
2395
2396    /// Writes `next` over the request at `expected` or reports the conflict.
2397    async fn swap(&self, next: &ApprovalRequest, expected: u64) -> Result<()> {
2398        if self.store.replace_request(next, expected).await? {
2399            return Ok(());
2400        }
2401        let current = self.store.get_request(&next.id).await?;
2402        Err(match current {
2403            Some(current) => version_conflict(&next.id, expected, current.version),
2404            None => not_found(&next.id),
2405        })
2406    }
2407
2408    async fn live_delegations(
2409        &self,
2410        to: &SubjectRef,
2411        at: DateTime<Utc>,
2412    ) -> Result<Vec<ApprovalDelegation>> {
2413        Ok(self
2414            .store
2415            .delegations_to(to)
2416            .await?
2417            .into_iter()
2418            .filter(|delegation| delegation.window.contains(at))
2419            .collect())
2420    }
2421
2422    /// The delegator `approver` decides `request` for at `at`, if any, and the groups of
2423    /// the decision's authority; or why the approver may not decide.
2424    async fn authority(
2425        &self,
2426        request: &ApprovalRequest,
2427        decision: &ApprovalDecision,
2428        at: DateTime<Utc>,
2429    ) -> Result<(Option<SubjectRef>, Vec<String>)> {
2430        let approver = &decision.approver;
2431        if approver.kind == SubjectKind::Visitor {
2432            return Err(forbidden(
2433                "approval.visitor_not_allowed",
2434                "a visitor cannot decide an approval request; approvers are identified subjects",
2435            ));
2436        }
2437        let forbid_self = request.policy.forbid_self_approval;
2438        if forbid_self && request.is_self(approver) {
2439            return Err(forbidden(
2440                "approval.self_approval",
2441                format!("'{}' may not approve their own call; ask another approver", approver.id),
2442            ));
2443        }
2444        let direct = request.is_eligible(approver, &decision.approver_groups);
2445        if direct && decision.via_delegation.is_none() {
2446            return Ok((None, decision.approver_groups.clone()));
2447        }
2448        let mut candidates: Vec<(ApprovalDelegation, Vec<String>)> = Vec::new();
2449        for delegation in self.store.delegations_to(approver).await? {
2450            if decision.via_delegation.as_ref().is_some_and(|from| *from != delegation.from)
2451                || !delegation.scope.covers(request)
2452            {
2453                continue;
2454            }
2455            let groups = self.groups_of(&delegation.from, &delegation.from_groups, request).await?;
2456            if request.is_eligible(&delegation.from, &groups) {
2457                candidates.push((delegation, groups));
2458            }
2459        }
2460        if let Some((live, groups)) =
2461            candidates.iter().find(|(delegation, _)| delegation.window.contains(at))
2462        {
2463            if forbid_self && request.is_self(&live.from) {
2464                return Err(forbidden(
2465                    "approval.self_approval",
2466                    format!(
2467                        "'{}' may not approve on behalf of '{}', the requester",
2468                        approver.id, live.from.id
2469                    ),
2470                ));
2471            }
2472            return Ok((Some(live.from.clone()), groups.clone()));
2473        }
2474        if !candidates.is_empty() {
2475            return Err(forbidden(
2476                "approval.delegation_inactive",
2477                format!(
2478                    "the delegation that lets '{}' approve this request is outside its window",
2479                    approver.id
2480                ),
2481            ));
2482        }
2483        Err(forbidden(
2484            "approval.not_an_approver",
2485            format!("'{}' is not an approver of request '{}'", approver.id, request.id),
2486        ))
2487    }
2488
2489    /// Whether the inbox `query` asks for, with the approver's `delegations`, holds
2490    /// `request` at `at`.
2491    async fn in_inbox(
2492        &self,
2493        request: &ApprovalRequest,
2494        query: &InboxQuery,
2495        delegations: &[ApprovalDelegation],
2496        at: DateTime<Utc>,
2497    ) -> Result<bool> {
2498        let forbid_self = request.policy.forbid_self_approval;
2499        let Some(approver) = query.approver.as_ref() else {
2500            return Ok(query.groups.is_empty()
2501                || request.eligible_approvers().any(|selector| {
2502                    matches!(selector, ApproverSelector::Group(group) if query.groups.contains(group))
2503                }));
2504        };
2505        if forbid_self && request.is_self(approver) {
2506            return Ok(false);
2507        }
2508        let groups = self.groups_of(approver, &query.groups, request).await?;
2509        if request.is_eligible(approver, &groups) {
2510            return Ok(true);
2511        }
2512        for delegation in delegations {
2513            if !delegation.window.contains(at)
2514                || !delegation.scope.covers(request)
2515                || (forbid_self && request.is_self(&delegation.from))
2516            {
2517                continue;
2518            }
2519            let groups = self.groups_of(&delegation.from, &delegation.from_groups, request).await?;
2520            if request.is_eligible(&delegation.from, &groups) {
2521                return Ok(true);
2522            }
2523        }
2524        Ok(false)
2525    }
2526}
2527
2528#[async_trait]
2529impl ApprovalService for StoreApprovalService {
2530    async fn submit(&self, mut request: ApprovalRequest) -> Result<ApprovalRequest> {
2531        request.policy.validate()?;
2532        if request.id.is_empty() {
2533            return Err(invalid("approval.invalid_request", "an approval request needs an id"));
2534        }
2535        if request.allowed_actions.is_empty() {
2536            return Err(invalid(
2537                "approval.invalid_request",
2538                "an approval request must allow at least one action",
2539            ));
2540        }
2541        let now = self.clock.now();
2542        request.created_at = now;
2543        if request.expires_at.is_none()
2544            && let Some(ttl) = request.policy.expires_after
2545        {
2546            let ttl = chrono::Duration::from_std(ttl).unwrap_or(chrono::Duration::MAX);
2547            request.expires_at =
2548                Some(now.checked_add_signed(ttl).unwrap_or(DateTime::<Utc>::MAX_UTC));
2549        }
2550        request.version = 1;
2551        request.state = ApprovalState::Pending;
2552        request.decisions.clear();
2553        request.escalations_fired = 0;
2554        request.resolved_at = None;
2555        request.note = None;
2556        request.outcome_applied = false;
2557        let stored = self.store.create_request(&request).await?;
2558        if stored == request {
2559            tracing::info!(approval.id = %request.id, tool.name = %request.tool_name, "approval request submitted");
2560            self.notify(ApprovalEventKind::Submitted, &stored, None, None).await;
2561        }
2562        Ok(stored)
2563    }
2564
2565    async fn submit_call(&self, call: ApprovalCall) -> Result<Option<ApprovalRequest>> {
2566        let router = self.router.as_ref().or_else(|| self.fallback_router.get());
2567        let Some(route) = router.and_then(|router| router.route(&call)) else {
2568            return Ok(None);
2569        };
2570        self.store.record_pending(&call.scope, &call.request).await?;
2571        let fingerprint = call.request.fingerprint();
2572        let Some(held) = self
2573            .store
2574            .pending(&call.scope)
2575            .await?
2576            .into_iter()
2577            .find(|entry| entry.fingerprint == fingerprint)
2578        else {
2579            // Decided between the hold and now; the next run takes the decision.
2580            return Ok(None);
2581        };
2582        // One request per held call: a call held again keeps the request still open for it,
2583        // even when its pending entry was recorded anew (spec 3.3 §7.3).
2584        let mut open = ApprovalRequestQuery::default()
2585            .with_session(&call.scope)
2586            .with_states([ApprovalState::Pending]);
2587        loop {
2588            let batch = self.store.list_requests(&open).await?;
2589            if let Some(existing) = batch.iter().find(|request| request.fingerprint == fingerprint)
2590            {
2591                return Ok(Some(existing.clone()));
2592            }
2593            if batch.len() < open.limit {
2594                break;
2595            }
2596            open = open.with_after(batch.last().map(ApprovalRequest::cursor));
2597        }
2598        let id = ApprovalRequest::id_for_call(&call.scope, &fingerprint, held.requested_at);
2599        let mut request = ApprovalRequest::new(id, call.scope.clone(), &call.request, route.policy)
2600            .with_summary(route.summary.unwrap_or(call.reason))
2601            .with_risk(route.risk);
2602        if let Some(args) = route.redacted_args {
2603            request = request.with_redacted_args(args);
2604        }
2605        if let Some(actions) = route.allowed_actions {
2606            request = request.with_allowed_actions(actions);
2607        }
2608        request = request.with_evidence(route.evidence);
2609        if let Some(acting) = call.acting {
2610            request = request.with_acting(acting);
2611        }
2612        if request.requester.is_none() {
2613            request = request.with_requester(SubjectRef::human(call.scope.user_id.clone()));
2614        }
2615        if let Some(run_id) = call.run_id {
2616            request = request.with_run_id(run_id);
2617        }
2618        self.submit(request).await.map(Some)
2619    }
2620
2621    async fn get(&self, id: &str) -> Result<Option<ApprovalRequest>> {
2622        self.store.get_request(id).await
2623    }
2624
2625    async fn inbox(&self, query: InboxQuery) -> Result<InboxPage> {
2626        let now = self.clock.now();
2627        let delegations = match &query.approver {
2628            Some(approver) => self.live_delegations(approver, now).await?,
2629            None => Vec::new(),
2630        };
2631        let states = if query.states.is_empty() {
2632            vec![ApprovalState::Pending]
2633        } else {
2634            query.states.clone()
2635        };
2636        let limit = query.limit.max(1);
2637        let mut after = query.cursor.as_deref().map(ApprovalCursor::decode).transpose()?;
2638        let mut items = Vec::new();
2639        loop {
2640            let mut store_query = ApprovalRequestQuery::default()
2641                .with_states(states.iter().copied())
2642                .with_after(after.clone())
2643                .with_limit(DEFAULT_APPROVAL_PAGE);
2644            store_query.app_name = query.app_name.clone();
2645            store_query.user_id = query.user_id.clone();
2646            store_query.session_id = query.session_id.clone();
2647            let batch = self.store.list_requests(&store_query).await?;
2648            let exhausted = batch.len() < DEFAULT_APPROVAL_PAGE;
2649            for request in batch {
2650                after = Some(request.cursor());
2651                if self.in_inbox(&request, &query, &delegations, now).await? {
2652                    items.push(request);
2653                    if items.len() == limit {
2654                        return Ok(InboxPage {
2655                            items,
2656                            next_cursor: after.map(|cursor| cursor.encode()),
2657                        });
2658                    }
2659                }
2660            }
2661            if exhausted {
2662                return Ok(InboxPage { items, next_cursor: None });
2663            }
2664        }
2665    }
2666
2667    async fn decide(
2668        &self,
2669        id: &str,
2670        expected_version: u64,
2671        mut decision: ApprovalDecision,
2672    ) -> Result<ApprovalRequest> {
2673        let now = self.clock.now();
2674        let request = self.store.get_request(id).await?.ok_or_else(|| not_found(id))?;
2675        if request.version != expected_version {
2676            return Err(version_conflict(id, expected_version, request.version));
2677        }
2678        if request.state.is_terminal() {
2679            return Err(conflict(
2680                "approval.already_resolved",
2681                format!("approval request '{id}' is already {}", request.state.as_str()),
2682            ));
2683        }
2684        if request.expires_at.is_some_and(|at| at <= now) {
2685            return Err(conflict(
2686                "approval.expired",
2687                format!("approval request '{id}' expired; the call is denied"),
2688            ));
2689        }
2690        if !request.allowed_actions.contains(&decision.kind) {
2691            return Err(invalid(
2692                "approval.action_not_allowed",
2693                format!("approval request '{id}' does not allow {:?}", decision.kind),
2694            ));
2695        }
2696        match decision.kind {
2697            ApprovalAction::Edit if decision.edited_args.is_none() => {
2698                return Err(invalid(
2699                    "approval.action_not_allowed",
2700                    "an edit must carry the edited arguments",
2701                ));
2702            }
2703            ApprovalAction::Respond
2704                if decision.reason.as_deref().is_none_or(|text| text.trim().is_empty()) =>
2705            {
2706                return Err(invalid(
2707                    "approval.action_not_allowed",
2708                    "a response must carry the text to report to the model",
2709                ));
2710            }
2711            ApprovalAction::Approve | ApprovalAction::Reject => decision.edited_args = None,
2712            ApprovalAction::Edit | ApprovalAction::Respond => {}
2713        }
2714        decision.approver_groups =
2715            self.groups_of(&decision.approver, &decision.approver_groups, &request).await?;
2716        (decision.via_delegation, decision.authority_groups) =
2717            self.authority(&request, &decision, now).await?;
2718        decision.decided_at = now;
2719        if matches!(decision.kind, ApprovalAction::Approve)
2720            && request.quorum_progress().0.contains(decision.authority())
2721        {
2722            return Err(conflict(
2723                "approval.already_decided",
2724                format!(
2725                    "'{}' already approved request '{id}'; another approver must decide",
2726                    decision.authority().id
2727                ),
2728            ));
2729        }
2730
2731        if let Some(trail) = &self.audit {
2732            use crate::audit_log::{AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind};
2733            let audited = match decision.kind {
2734                ApprovalAction::Approve | ApprovalAction::Edit => AuditDecision::Approved,
2735                ApprovalAction::Reject | ApprovalAction::Respond => AuditDecision::Rejected,
2736            };
2737            let mut actor = AuditActor::subject(decision.approver.clone());
2738            actor.delegation_chain.extend(decision.via_delegation.clone());
2739            let action = serde_json::to_value(decision.kind).unwrap_or(Value::Null);
2740            let mut draft = AuditRecordDraft::new(AuditRecordKind::Approval, &request.tool_name)
2741                .actor(actor)
2742                .args_digest(trail.digest(&request.args_redacted))
2743                .decision(audited)
2744                .ext("source", Value::String("approval_service".to_string()))
2745                .ext("approvalId", Value::String(id.to_string()))
2746                .ext("approvalAction", action)
2747                .ext("version", Value::from(expected_version + 1))
2748                .ext("sessionId", Value::String(request.scope.session_id.clone()));
2749            if let Some(acting) = &request.acting {
2750                draft = draft.ext("actingAgent", Value::String(acting.agent.id.to_string()));
2751            }
2752            // The images the decision was made on, by digest.
2753            if !request.evidence.is_empty() {
2754                let digests = request.evidence.iter().map(|item| Value::from(item.digest()));
2755                draft = draft.ext("evidenceDigests", Value::Array(digests.collect()));
2756            }
2757            if let Some(edited) = &decision.edited_args {
2758                draft = draft.ext("editedArgsDigest", Value::String(trail.digest(edited)));
2759            }
2760            trail.record(draft).await?;
2761        }
2762
2763        let mut next = request.clone();
2764        next.decisions.push(decision.clone());
2765        next.version = expected_version + 1;
2766        next.state = match decision.kind {
2767            ApprovalAction::Reject => ApprovalState::Rejected,
2768            ApprovalAction::Respond => ApprovalState::Responded,
2769            ApprovalAction::Approve | ApprovalAction::Edit => {
2770                let approvals = next.quorum_progress().0.len();
2771                if approvals >= usize::try_from(next.policy.quorum).unwrap_or(usize::MAX)
2772                    && next.open_slots().is_empty()
2773                {
2774                    ApprovalState::Approved
2775                } else {
2776                    ApprovalState::Pending
2777                }
2778            }
2779        };
2780        if next.state.is_terminal() {
2781            next.resolved_at = Some(now);
2782        }
2783        self.swap(&next, expected_version).await?;
2784        tracing::info!(
2785            approval.id = %id,
2786            approval.action = ?decision.kind,
2787            approval.state = next.state.as_str(),
2788            "approval decision recorded"
2789        );
2790        if !next.state.is_terminal() {
2791            self.notify(ApprovalEventKind::Decided, &next, Some(&decision), None).await;
2792            return Ok(next);
2793        }
2794        // What the call must already see, such as the standing rule an answer made, is in
2795        // place before the outcome reaches it (spec 3.3 §7.2).
2796        let resolutions = self.resolutions.read().unwrap_or_else(|e| e.into_inner()).clone();
2797        for hook in resolutions {
2798            hook.resolving(&next, &decision).await;
2799        }
2800        // The outcome is written before any notifier runs, so a call that is decided
2801        // another way meanwhile waits for it no longer than the store write (spec 3.3 §7.3).
2802        let applied = self.apply(next.clone(), false).await?;
2803        self.notify(ApprovalEventKind::Decided, &next, Some(&decision), None).await;
2804        self.notify(ApprovalEventKind::Resolved, &applied, None, None).await;
2805        Ok(applied)
2806    }
2807
2808    async fn delegate(&self, mut delegation: ApprovalDelegation) -> Result<ApprovalDelegation> {
2809        if delegation.window.not_after <= delegation.window.not_before {
2810            return Err(invalid(
2811                "approval.invalid_delegation",
2812                "a delegation window must end after it starts",
2813            ));
2814        }
2815        if delegation.from == delegation.to {
2816            return Err(invalid(
2817                "approval.invalid_delegation",
2818                "a subject cannot delegate to itself",
2819            ));
2820        }
2821        if delegation.id.is_empty() {
2822            return Err(invalid("approval.invalid_delegation", "a delegation needs an id"));
2823        }
2824        delegation.created_at = self.clock.now();
2825        self.store.put_delegation(&delegation).await?;
2826        tracing::info!(
2827            delegation.id = %delegation.id,
2828            delegation.from = %delegation.from.id,
2829            delegation.to = %delegation.to.id,
2830            "approval delegation granted"
2831        );
2832        Ok(delegation)
2833    }
2834
2835    async fn revoke_delegation(&self, id: &str) -> Result<bool> {
2836        self.store.delete_delegation(id).await
2837    }
2838
2839    async fn delegations_to(&self, to: &SubjectRef) -> Result<Vec<ApprovalDelegation>> {
2840        self.store.delegations_to(to).await
2841    }
2842
2843    async fn cancel(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest> {
2844        let request = self.store.get_request(id).await?.ok_or_else(|| not_found(id))?;
2845        if request.state.is_terminal() {
2846            return Err(conflict(
2847                "approval.already_resolved",
2848                format!("approval request '{id}' is already {}", request.state.as_str()),
2849            ));
2850        }
2851        let mut next = request.clone();
2852        next.state = ApprovalState::Cancelled;
2853        next.version = request.version + 1;
2854        next.resolved_at = Some(self.clock.now());
2855        next.note = reason;
2856        self.swap(&next, request.version).await?;
2857        let applied = self.apply(next, false).await?;
2858        self.notify(ApprovalEventKind::Cancelled, &applied, None, None).await;
2859        Ok(applied)
2860    }
2861
2862    async fn withdraw(&self, id: &str, reason: Option<String>) -> Result<ApprovalRequest> {
2863        let request = self.store.get_request(id).await?.ok_or_else(|| not_found(id))?;
2864        if request.state.is_terminal() {
2865            return Err(conflict(
2866                "approval.already_resolved",
2867                format!("approval request '{id}' is already {}", request.state.as_str()),
2868            ));
2869        }
2870        let mut next = request.clone();
2871        next.state = ApprovalState::Cancelled;
2872        next.version = request.version + 1;
2873        next.resolved_at = Some(self.clock.now());
2874        next.note = reason;
2875        // The call was decided another way: there is no outcome to write or run to wake.
2876        next.outcome_applied = true;
2877        self.swap(&next, request.version).await?;
2878        self.notify(ApprovalEventKind::Cancelled, &next, None, None).await;
2879        Ok(next)
2880    }
2881
2882    async fn tick(&self, now: DateTime<Utc>) -> Result<ApprovalTick> {
2883        let mut report = ApprovalTick::default();
2884        let mut after = None;
2885        loop {
2886            let query = ApprovalRequestQuery::default().open_only().with_after(after.clone());
2887            let batch = self.store.list_requests(&query).await?;
2888            let exhausted = batch.len() < query.limit;
2889            for request in batch {
2890                after = Some(request.cursor());
2891                if request.state.is_terminal() {
2892                    let grace = chrono::Duration::from_std(APPROVAL_REAPPLY_GRACE)
2893                        .unwrap_or(chrono::Duration::MAX);
2894                    let settled = request
2895                        .resolved_at
2896                        .and_then(|at| at.checked_add_signed(grace))
2897                        .is_none_or(|at| at <= now);
2898                    if settled {
2899                        let applied = self.apply(request, true).await?;
2900                        report.reapplied.push(applied.id);
2901                    }
2902                    continue;
2903                }
2904                if request.expires_at.is_some_and(|at| at <= now) {
2905                    let mut next = request.clone();
2906                    next.state = ApprovalState::Expired;
2907                    next.version = request.version + 1;
2908                    next.resolved_at = Some(now);
2909                    if !self.store.replace_request(&next, request.version).await? {
2910                        continue;
2911                    }
2912                    tracing::info!(approval.id = %next.id, "approval request expired; denying the call");
2913                    let applied = self.apply(next, false).await?;
2914                    self.notify(ApprovalEventKind::Expired, &applied, None, None).await;
2915                    report.expired.push(applied.id);
2916                    continue;
2917                }
2918                let due = request
2919                    .policy
2920                    .escalation
2921                    .iter()
2922                    .take_while(|step| {
2923                        chrono::Duration::from_std(step.after)
2924                            .ok()
2925                            .and_then(|after| request.created_at.checked_add_signed(after))
2926                            .is_some_and(|at| at <= now)
2927                    })
2928                    .count();
2929                let due = u32::try_from(due).unwrap_or(u32::MAX);
2930                if due <= request.escalations_fired {
2931                    continue;
2932                }
2933                let mut next = request.clone();
2934                next.escalations_fired = due;
2935                next.version = request.version + 1;
2936                if !self.store.replace_request(&next, request.version).await? {
2937                    continue;
2938                }
2939                for step in request.escalations_fired..due {
2940                    tracing::info!(approval.id = %next.id, approval.escalation_step = step, "approval request escalated");
2941                    self.notify(ApprovalEventKind::Escalated, &next, None, Some(step)).await;
2942                    report.escalated.push((next.id.clone(), step));
2943                }
2944            }
2945            if exhausted {
2946                return Ok(report);
2947            }
2948        }
2949    }
2950
2951    fn approval_store(&self) -> Option<Arc<dyn ApprovalStore>> {
2952        Some(self.store.clone())
2953    }
2954
2955    async fn record_review(
2956        &self,
2957        call: ApprovalCall,
2958        mut decision: ApprovalDecision,
2959    ) -> Result<Option<ApprovalRequest>> {
2960        let router = self.router.as_ref().or_else(|| self.fallback_router.get());
2961        let Some(route) = router.and_then(|router| router.route(&call)) else {
2962            return Ok(None);
2963        };
2964        route.policy.validate()?;
2965        let now = self.clock.now();
2966        let fingerprint = call.request.fingerprint();
2967        let id = ApprovalRequest::id_for_call(&call.scope, &fingerprint, now);
2968        let mut request = ApprovalRequest::new(id, call.scope.clone(), &call.request, route.policy)
2969            .with_summary(route.summary.unwrap_or(call.reason))
2970            .with_risk(route.risk);
2971        if let Some(args) = route.redacted_args {
2972            request = request.with_redacted_args(args);
2973        }
2974        if let Some(actions) = route.allowed_actions {
2975            request = request.with_allowed_actions(actions);
2976        }
2977        request = request.with_evidence(route.evidence);
2978        if let Some(acting) = call.acting {
2979            request = request.with_acting(acting);
2980        }
2981        if request.requester.is_none() {
2982            request = request.with_requester(SubjectRef::human(call.scope.user_id.clone()));
2983        }
2984        if let Some(run_id) = call.run_id {
2985            request = request.with_run_id(run_id);
2986        }
2987        decision.decided_at = now;
2988        request.created_at = now;
2989        request.state = match decision.kind {
2990            ApprovalAction::Approve | ApprovalAction::Edit => ApprovalState::Approved,
2991            ApprovalAction::Reject => ApprovalState::Rejected,
2992            ApprovalAction::Respond => ApprovalState::Responded,
2993        };
2994        request.decisions = vec![decision.clone()];
2995        request.resolved_at = Some(now);
2996        // The run applied the verdict itself: there is no outcome to write and no run to wake.
2997        request.outcome_applied = true;
2998
2999        if let Some(trail) = &self.audit {
3000            use crate::audit_log::{AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind};
3001            let audited = match decision.kind {
3002                ApprovalAction::Approve | ApprovalAction::Edit => AuditDecision::Approved,
3003                ApprovalAction::Reject | ApprovalAction::Respond => AuditDecision::Rejected,
3004            };
3005            let action = serde_json::to_value(decision.kind).unwrap_or(Value::Null);
3006            let mut draft = AuditRecordDraft::new(AuditRecordKind::Approval, &request.tool_name)
3007                .actor(AuditActor::subject(decision.approver.clone()))
3008                .args_digest(trail.digest(&request.args_redacted))
3009                .decision(audited)
3010                .ext("source", Value::String(crate::REVIEW_SOURCE.to_string()))
3011                .ext("approvalId", Value::String(request.id.clone()))
3012                .ext("approvalAction", action)
3013                .ext("version", Value::from(request.version))
3014                .ext("sessionId", Value::String(request.scope.session_id.clone()));
3015            if let Some(acting) = &request.acting {
3016                draft = draft.ext("actingAgent", Value::String(acting.agent.id.to_string()));
3017            }
3018            // The images the decision was made on, by digest.
3019            if !request.evidence.is_empty() {
3020                let digests = request.evidence.iter().map(|item| Value::from(item.digest()));
3021                draft = draft.ext("evidenceDigests", Value::Array(digests.collect()));
3022            }
3023            trail.record(draft).await?;
3024        }
3025
3026        let stored = self.store.create_request(&request).await?;
3027        tracing::info!(
3028            approval.id = %stored.id,
3029            tool.name = %stored.tool_name,
3030            approval.state = stored.state.as_str(),
3031            reviewer.id = %decision.approver.id,
3032            "approval request decided by a reviewer"
3033        );
3034        if stored == request {
3035            self.notify(ApprovalEventKind::Decided, &stored, Some(&decision), None).await;
3036            self.notify(ApprovalEventKind::Resolved, &stored, None, None).await;
3037        }
3038        Ok(Some(stored))
3039    }
3040
3041    fn route_unrouted(&self, router: Arc<dyn ApprovalRouter>) -> bool {
3042        if self.router.is_none() {
3043            // The first host's router stays: a second has nothing to add.
3044            let _ = self.fallback_router.set(router);
3045        }
3046        true
3047    }
3048
3049    fn add_notifier(&self, notifier: Arc<dyn ApprovalNotifier>) -> bool {
3050        self.late_notifiers.write().unwrap_or_else(|e| e.into_inner()).push(notifier);
3051        true
3052    }
3053
3054    fn add_resolution(&self, hook: Arc<dyn ApprovalResolution>) -> bool {
3055        self.resolutions.write().unwrap_or_else(|e| e.into_inner()).push(hook);
3056        true
3057    }
3058}
3059
3060// ---------------------------------------------------------------------------
3061// Errors
3062// ---------------------------------------------------------------------------
3063
3064fn error(category: ErrorCategory, code: &'static str, message: impl Into<String>) -> AdkError {
3065    AdkError::new(ErrorComponent::Agent, category, code, message.into())
3066}
3067
3068fn invalid(code: &'static str, message: impl Into<String>) -> AdkError {
3069    error(ErrorCategory::InvalidInput, code, message)
3070}
3071
3072fn forbidden(code: &'static str, message: impl Into<String>) -> AdkError {
3073    error(ErrorCategory::Forbidden, code, message)
3074}
3075
3076fn conflict(code: &'static str, message: impl Into<String>) -> AdkError {
3077    error(ErrorCategory::Conflict, code, message)
3078}
3079
3080fn not_found(id: &str) -> AdkError {
3081    error(ErrorCategory::NotFound, "approval.not_found", format!("no approval request '{id}'"))
3082}
3083
3084fn version_conflict(id: &str, expected: u64, current: u64) -> AdkError {
3085    let mut details = ErrorDetails::default();
3086    details.metadata.insert("current_version".to_string(), current.into());
3087    conflict(
3088        "approval.version_conflict",
3089        format!(
3090            "approval request '{id}' is at version {current}, not {expected}; another decision \
3091             landed first, so re-read the request and decide again"
3092        ),
3093    )
3094    .with_details(details)
3095}
3096
3097/// The error a store method reports when the backend does not implement it.
3098pub(crate) fn store_unsupported(operation: &str) -> AdkError {
3099    error(
3100        ErrorCategory::Unsupported,
3101        "approval.store_unsupported",
3102        format!(
3103            "this approval store does not implement `{operation}`, which the approval service \
3104             needs; use a store from adk-core or adk-session, or implement the method"
3105        ),
3106    )
3107}
3108
3109mod duration_secs {
3110    use serde::{Deserialize, Deserializer, Serializer};
3111    use std::time::Duration;
3112
3113    pub fn serialize<S: Serializer>(value: &Duration, serializer: S) -> Result<S::Ok, S::Error> {
3114        serializer.serialize_u64(value.as_secs())
3115    }
3116
3117    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Duration, D::Error> {
3118        u64::deserialize(deserializer).map(Duration::from_secs)
3119    }
3120}
3121
3122mod option_duration_secs {
3123    use serde::{Deserialize, Deserializer, Serializer};
3124    use std::time::Duration;
3125
3126    #[allow(clippy::ref_option)] // serde's `with` passes the field by reference
3127    pub fn serialize<S: Serializer>(
3128        value: &Option<Duration>,
3129        serializer: S,
3130    ) -> Result<S::Ok, S::Error> {
3131        match value {
3132            Some(duration) => serializer.serialize_some(&duration.as_secs()),
3133            None => serializer.serialize_none(),
3134        }
3135    }
3136
3137    pub fn deserialize<'de, D: Deserializer<'de>>(
3138        deserializer: D,
3139    ) -> Result<Option<Duration>, D::Error> {
3140        Ok(Option::<u64>::deserialize(deserializer)?.map(Duration::from_secs))
3141    }
3142}
3143
3144#[cfg(test)]
3145mod tests {
3146    use super::*;
3147    use serde_json::json;
3148
3149    #[test]
3150    fn a_person_and_a_service_with_one_id_are_the_same_party() {
3151        let call = ToolConfirmationRequest::new("pay", json!({}));
3152        let request = ApprovalRequest::new(
3153            "req-1",
3154            ApprovalScope::new("ap", "controller", "s"),
3155            &call,
3156            ApprovalPolicy::new([ApproverSelector::group("finance")]),
3157        )
3158        .with_acting(
3159            ActingContext::new(crate::AgentPrincipal::derived("ap", "clerk"))
3160                .on_behalf_of(SubjectRef::service("controller")),
3161        );
3162        assert!(request.is_self(&SubjectRef::human("controller")));
3163        assert!(request.is_self(&SubjectRef::service("controller")));
3164        assert!(!request.is_self(&SubjectRef::human("cfo")));
3165        assert!(!request.is_self(&SubjectRef::new(SubjectKind::Agent, "controller")));
3166        assert!(
3167            request.is_self(&SubjectRef::agent(&crate::AgentPrincipal::derived("ap", "clerk").id))
3168        );
3169    }
3170
3171    #[test]
3172    fn policies_serialize_in_camel_case_with_whole_seconds() {
3173        let policy = ApprovalPolicy::new([ApproverSelector::group("finance")])
3174            .with_quorum(2)
3175            .escalate_after(Duration::from_secs(900), [ApproverSelector::human("cfo")])
3176            .expires_after(Duration::from_secs(3_600));
3177        let value = serde_json::to_value(&policy).unwrap();
3178        assert_eq!(
3179            value,
3180            json!({
3181                "approvers": [{ "group": "finance" }],
3182                "quorum": 2,
3183                "forbidSelfApproval": true,
3184                "escalation": [{
3185                    "afterSecs": 900,
3186                    "to": [{ "subject": { "kind": "human", "id": "cfo" } }]
3187                }],
3188                "onExpiry": "deny",
3189                "expiresAfterSecs": 3600
3190            })
3191        );
3192        assert_eq!(serde_json::from_value::<ApprovalPolicy>(value).unwrap(), policy);
3193    }
3194
3195    #[test]
3196    fn cursors_round_trip_ids_containing_colons() {
3197        let cursor = ApprovalCursor { created_at: Utc::now(), id: "a:b/ü".into() };
3198        let decoded = ApprovalCursor::decode(&cursor.encode()).unwrap();
3199        assert_eq!(decoded.id, cursor.id);
3200        assert_eq!(decoded.created_at.timestamp_micros(), cursor.created_at.timestamp_micros());
3201        assert_eq!(ApprovalCursor::decode("nope").unwrap_err().code, "approval.invalid_cursor");
3202    }
3203
3204    #[test]
3205    fn call_ids_change_with_the_hold_time() {
3206        let scope = ApprovalScope::new("app", "u", "s");
3207        let at = Utc::now();
3208        let id = ApprovalRequest::id_for_call(&scope, "fp", at);
3209        assert_eq!(id, ApprovalRequest::id_for_call(&scope, "fp", at));
3210        assert_ne!(
3211            id,
3212            ApprovalRequest::id_for_call(&scope, "fp", at + chrono::Duration::seconds(1))
3213        );
3214        assert!(id.starts_with("apr_"));
3215    }
3216
3217    #[test]
3218    fn invalid_policies_are_refused() {
3219        assert!(ApprovalPolicy::new([]).validate().is_err());
3220        let zero = ApprovalPolicy::new([ApproverSelector::group("g")]).with_quorum(0);
3221        assert_eq!(zero.validate().unwrap_err().code, "approval.invalid_policy");
3222        let unordered = ApprovalPolicy::new([ApproverSelector::group("g")])
3223            .escalate_after(Duration::from_secs(60), [])
3224            .escalate_after(Duration::from_secs(30), []);
3225        assert!(unordered.validate().is_err());
3226    }
3227
3228    #[tokio::test]
3229    async fn resolving_a_request_wakes_its_waiting_run() {
3230        use crate::{
3231            ApprovalStore, DurableRunStore, InMemoryApprovalStore, InMemoryRunStore, NewRun,
3232            RunState,
3233        };
3234
3235        let runs = Arc::new(InMemoryRunStore::new());
3236        let enqueued =
3237            runs.enqueue(NewRun::new("q", "app", "u", "agent", json!({}))).await.unwrap();
3238        let run_id = enqueued.record().unwrap().run_id.clone();
3239        let claimed = runs.claim("q", "worker", Duration::from_secs(60)).await.unwrap().unwrap();
3240        // The worker parks the run until the approval arrives.
3241        runs.wait(&run_id, claimed.epoch, None).await.unwrap();
3242        assert_eq!(runs.get(&run_id).await.unwrap().unwrap().state, RunState::Waiting);
3243
3244        let store = Arc::new(InMemoryApprovalStore::new());
3245        let service = StoreApprovalService::new(store.clone()).with_run_store(runs.clone());
3246        let call = ToolConfirmationRequest {
3247            tool_name: "pay".into(),
3248            function_call_id: Some("c1".into()),
3249            args: json!({ "amount": 5 }),
3250            origin: None,
3251            acting: None,
3252            evidence: Vec::new(),
3253        };
3254        let scope = ApprovalScope::new("app", "u", "s");
3255        let request = service
3256            .submit(
3257                ApprovalRequest::new(
3258                    "req",
3259                    scope.clone(),
3260                    &call,
3261                    ApprovalPolicy::new([ApproverSelector::human("ana")]),
3262                )
3263                .with_run_id(run_id.clone()),
3264            )
3265            .await
3266            .unwrap();
3267        service
3268            .decide(
3269                &request.id,
3270                request.version,
3271                ApprovalDecision::approve(SubjectRef::human("ana")),
3272            )
3273            .await
3274            .unwrap();
3275
3276        assert!(store.has_decision(&scope, &call.fingerprint()).await.unwrap());
3277        let woken = runs.claim("q", "worker", Duration::from_secs(60)).await.unwrap();
3278        assert_eq!(
3279            woken.map(|claim| claim.record.run_id),
3280            Some(run_id),
3281            "the decision woke the run"
3282        );
3283    }
3284
3285    /// Wave 2 review finding 3 (spec 3.3 §7.3): a run that held the call again while its
3286    /// request was still open — after the run the request names was cancelled — is woken
3287    /// when the request resolves.
3288    #[tokio::test]
3289    async fn resolving_a_request_wakes_a_later_run_parked_on_the_call() {
3290        use crate::{DurableRunStore, InMemoryApprovalStore, InMemoryRunStore, NewRun, RunState};
3291
3292        let runs = Arc::new(InMemoryRunStore::new());
3293        let scope = ApprovalScope::new("app", "u", "s-1");
3294        let call = ToolConfirmationRequest::new("pay", json!({ "cents": 500 }));
3295        let park = |runs: Arc<InMemoryRunStore>| {
3296            let fingerprint = call.fingerprint();
3297            async move {
3298                let new = NewRun::new("q", "app", "u", "agent", json!({})).with_session_id("s-1");
3299                let run_id = runs.enqueue(new).await.unwrap().record().unwrap().run_id.clone();
3300                let claim = runs.claim("q", "w", Duration::from_secs(60)).await.unwrap().unwrap();
3301                let checkpoint = crate::RunCheckpointRef::AwaitingApproval {
3302                    session_id: "s-1".into(),
3303                    invocation_id: None,
3304                    fingerprints: vec![fingerprint],
3305                    expires_at: None,
3306                };
3307                runs.set_checkpoint(&run_id, claim.epoch, checkpoint).await.unwrap();
3308                runs.wait(&run_id, claim.epoch, None).await.unwrap();
3309                run_id
3310            }
3311        };
3312        let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
3313            .with_run_store(runs.clone())
3314            .with_router(ApprovalPolicy::new([ApproverSelector::human("ana")]));
3315        let held_by = |run_id: &str| ApprovalCall {
3316            scope: scope.clone(),
3317            request: call.clone(),
3318            reason: "pay".into(),
3319            agent_name: "agent".into(),
3320            invocation_id: "inv".into(),
3321            run_id: Some(run_id.to_string()),
3322            acting: None,
3323        };
3324
3325        let first = park(runs.clone()).await;
3326        let request = service.submit_call(held_by(&first)).await.unwrap().unwrap();
3327        runs.request_cancel(&first).await.unwrap();
3328        let second = park(runs.clone()).await;
3329        let again = service.submit_call(held_by(&second)).await.unwrap().unwrap();
3330        assert_eq!(again.id, request.id, "the call held again keeps its request");
3331
3332        service
3333            .decide(
3334                &request.id,
3335                request.version,
3336                ApprovalDecision::approve(SubjectRef::human("ana")),
3337            )
3338            .await
3339            .unwrap();
3340        assert_eq!(runs.get(&first).await.unwrap().unwrap().state, RunState::Cancelled);
3341        let woken = runs.claim("q", "w", Duration::from_secs(60)).await.unwrap();
3342        assert_eq!(woken.map(|claim| claim.record.run_id), Some(second), "the later run wakes");
3343    }
3344
3345    /// Wave 2 review finding 14 (spec 3.3 §7.3): the outcome of a decision is in the store
3346    /// before any notifier hears of it, so a call decided another way meanwhile waits for it
3347    /// no longer than the store write.
3348    #[tokio::test]
3349    async fn a_resolved_outcome_is_in_the_store_before_the_notifiers_run() {
3350        use crate::{ApprovalStore, InMemoryApprovalStore};
3351
3352        #[derive(Debug)]
3353        struct Witness {
3354            store: Arc<InMemoryApprovalStore>,
3355            seen: std::sync::Mutex<Vec<(ApprovalEventKind, bool, bool)>>,
3356        }
3357        #[async_trait::async_trait]
3358        impl ApprovalNotifier for Witness {
3359            async fn notify(&self, notification: &ApprovalNotification) -> Result<()> {
3360                let request = &notification.request;
3361                let decided = self.store.has_decision(&request.scope, &request.fingerprint).await?;
3362                let waiting = self
3363                    .store
3364                    .pending(&request.scope)
3365                    .await?
3366                    .iter()
3367                    .any(|entry| entry.fingerprint == request.fingerprint);
3368                self.seen.lock().unwrap().push((notification.kind, decided, waiting));
3369                Ok(())
3370            }
3371        }
3372
3373        let store = Arc::new(InMemoryApprovalStore::new());
3374        let witness = Arc::new(Witness { store: store.clone(), seen: Default::default() });
3375        let service = StoreApprovalService::new(store.clone())
3376            .with_notifier(witness.clone())
3377            .with_router(ApprovalPolicy::new([ApproverSelector::human("ana")]));
3378        let call = ApprovalCall {
3379            scope: ApprovalScope::new("app", "u", "s"),
3380            request: ToolConfirmationRequest::new("pay", json!({ "cents": 500 })),
3381            reason: "pay".into(),
3382            agent_name: "agent".into(),
3383            invocation_id: "inv".into(),
3384            run_id: None,
3385            acting: None,
3386        };
3387        let request = service.submit_call(call).await.unwrap().unwrap();
3388        service
3389            .decide(
3390                &request.id,
3391                request.version,
3392                ApprovalDecision::approve(SubjectRef::human("ana")),
3393            )
3394            .await
3395            .unwrap();
3396        assert_eq!(
3397            *witness.seen.lock().unwrap(),
3398            vec![
3399                (ApprovalEventKind::Submitted, false, true),
3400                (ApprovalEventKind::Decided, true, false),
3401                (ApprovalEventKind::Resolved, true, false),
3402            ]
3403        );
3404    }
3405
3406    /// A resolution hook runs once the deciding answer is recorded and before the outcome
3407    /// reaches the call or wakes its run, so what the hook stores, such as the standing rule
3408    /// "Always allow" makes, is there when the run resumes (spec 3.3 §7.2).
3409    #[tokio::test]
3410    async fn a_resolution_hook_runs_before_the_outcome_reaches_the_call_or_its_run() {
3411        use crate::{
3412            ApprovalStore, DurableRunStore, InMemoryApprovalStore, InMemoryRunStore, NewRun,
3413            RunState,
3414        };
3415
3416        /// The request's state, the approver, whether the call was decided, and the run's state.
3417        type Seen = (ApprovalState, String, bool, Option<RunState>);
3418
3419        #[derive(Debug)]
3420        struct Witness {
3421            store: Arc<InMemoryApprovalStore>,
3422            runs: Arc<InMemoryRunStore>,
3423            run_id: String,
3424            seen: std::sync::Mutex<Vec<Seen>>,
3425        }
3426        #[async_trait::async_trait]
3427        impl ApprovalResolution for Witness {
3428            async fn resolving(&self, request: &ApprovalRequest, decision: &ApprovalDecision) {
3429                let applied =
3430                    self.store.has_decision(&request.scope, &request.fingerprint).await.unwrap();
3431                let run = self.runs.get(&self.run_id).await.unwrap().map(|run| run.state);
3432                self.seen.lock().unwrap().push((
3433                    request.state,
3434                    decision.approver.id.clone(),
3435                    applied,
3436                    run,
3437                ));
3438            }
3439        }
3440
3441        let store = Arc::new(InMemoryApprovalStore::new());
3442        let runs = Arc::new(InMemoryRunStore::new());
3443        let new = NewRun::new("q", "app", "u", "agent", json!({})).with_session_id("s");
3444        let run_id = runs.enqueue(new).await.unwrap().record().unwrap().run_id.clone();
3445        let claim = runs.claim("q", "w", Duration::from_secs(60)).await.unwrap().unwrap();
3446        let call = ToolConfirmationRequest::new("pay", json!({ "cents": 500 }));
3447        let checkpoint = crate::RunCheckpointRef::AwaitingApproval {
3448            session_id: "s".into(),
3449            invocation_id: None,
3450            fingerprints: vec![call.fingerprint()],
3451            expires_at: None,
3452        };
3453        runs.set_checkpoint(&run_id, claim.epoch, checkpoint).await.unwrap();
3454        runs.wait(&run_id, claim.epoch, None).await.unwrap();
3455        let witness = Arc::new(Witness {
3456            store: store.clone(),
3457            runs: runs.clone(),
3458            run_id: run_id.clone(),
3459            seen: Default::default(),
3460        });
3461        let service = StoreApprovalService::new(store.clone())
3462            .with_run_store(runs.clone())
3463            .with_router(ApprovalPolicy::new([ApproverSelector::human("ana")]));
3464        assert!(service.add_resolution(witness.clone()));
3465        let held = ApprovalCall {
3466            scope: ApprovalScope::new("app", "u", "s"),
3467            request: call,
3468            reason: "pay".into(),
3469            agent_name: "agent".into(),
3470            invocation_id: "inv".into(),
3471            run_id: Some(run_id.clone()),
3472            acting: None,
3473        };
3474        let request = service.submit_call(held).await.unwrap().unwrap();
3475        service
3476            .decide(
3477                &request.id,
3478                request.version,
3479                ApprovalDecision::approve(SubjectRef::human("ana")),
3480            )
3481            .await
3482            .unwrap();
3483
3484        assert_eq!(
3485            *witness.seen.lock().unwrap(),
3486            vec![(ApprovalState::Approved, "ana".to_string(), false, Some(RunState::Waiting))],
3487            "the hook saw the recorded yes, the call not yet decided and its run still asleep"
3488        );
3489        assert!(store.has_decision(&request.scope, &request.fingerprint).await.unwrap());
3490        let woken = runs.claim("q", "w", Duration::from_secs(60)).await.unwrap();
3491        assert_eq!(woken.map(|claim| claim.record.run_id), Some(run_id), "then the run wakes");
3492    }
3493
3494    #[tokio::test]
3495    async fn an_approver_decision_is_audited_before_it_takes_effect() {
3496        use crate::audit_log::{
3497            AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditRecorder,
3498            AuditTrail, InMemoryAuditRecorder,
3499        };
3500        use crate::{ApprovalStore, InMemoryApprovalStore};
3501
3502        #[derive(Debug)]
3503        struct Broken;
3504        #[async_trait::async_trait]
3505        impl AuditRecorder for Broken {
3506            fn digest(&self, value: &Value) -> String {
3507                crate::json_digest(value)
3508            }
3509            async fn record(&self, _draft: AuditRecordDraft) -> Result<()> {
3510                Err(crate::AdkError::session("audit store down"))
3511            }
3512        }
3513
3514        let call = ToolConfirmationRequest {
3515            tool_name: "pay".into(),
3516            function_call_id: Some("c1".into()),
3517            args: json!({ "to": "acct-secret", "amount": 5 }),
3518            origin: None,
3519            acting: None,
3520            evidence: Vec::new(),
3521        };
3522        let scope = ApprovalScope::new("app", "u", "s");
3523        let request = |id: &str| {
3524            ApprovalRequest::new(
3525                id,
3526                scope.clone(),
3527                &call,
3528                ApprovalPolicy::new([ApproverSelector::human("ana")]),
3529            )
3530        };
3531
3532        let recorder = InMemoryAuditRecorder::new();
3533        let store = Arc::new(InMemoryApprovalStore::new());
3534        let service = StoreApprovalService::new(store.clone())
3535            .with_audit(AuditTrail::new(Arc::new(recorder.clone())));
3536        let submitted = service.submit(request("req")).await.unwrap();
3537        service
3538            .decide(
3539                &submitted.id,
3540                submitted.version,
3541                ApprovalDecision::approve(SubjectRef::human("ana")),
3542            )
3543            .await
3544            .unwrap();
3545        assert_eq!(
3546            recorder.records(),
3547            vec![
3548                AuditRecordDraft::new(AuditRecordKind::Approval, "pay")
3549                    .actor(AuditActor::subject(SubjectRef::human("ana")))
3550                    .args_digest(recorder.digest(&submitted.args_redacted))
3551                    .decision(AuditDecision::Approved)
3552                    .ext("source", json!("approval_service"))
3553                    .ext("approvalId", json!(submitted.id))
3554                    .ext("approvalAction", json!("approve"))
3555                    .ext("version", json!(submitted.version + 1))
3556                    .ext("sessionId", json!("s"))
3557            ]
3558        );
3559
3560        let blocked_store = Arc::new(InMemoryApprovalStore::new());
3561        let blocked = StoreApprovalService::new(blocked_store.clone())
3562            .with_audit(AuditTrail::new(Arc::new(Broken)));
3563        let submitted = blocked.submit(request("req-2")).await.unwrap();
3564        let error = blocked
3565            .decide(
3566                &submitted.id,
3567                submitted.version,
3568                ApprovalDecision::approve(SubjectRef::human("ana")),
3569            )
3570            .await
3571            .unwrap_err();
3572        assert_eq!(error.code, "audit.record_failed");
3573        assert!(!blocked_store.has_decision(&scope, &call.fingerprint()).await.unwrap());
3574        assert_eq!(
3575            blocked.get(&submitted.id).await.unwrap().unwrap().state,
3576            ApprovalState::Pending
3577        );
3578    }
3579
3580    fn verb_origin() -> ToolOrigin {
3581        ToolOrigin::new(
3582            "verbs:adk-rust",
3583            &json!({ "name": "verb_snooze", "parameters": { "type": "object" } }),
3584            None,
3585        )
3586    }
3587
3588    /// Spec 3.3 §7.1: the request a held call becomes names who publishes the tool, so a
3589    /// surface can tell one origin's cards from another's without parsing the fingerprint.
3590    #[tokio::test]
3591    async fn a_submitted_call_keeps_its_tools_origin() {
3592        use crate::InMemoryApprovalStore;
3593
3594        let policy = ApprovalPolicy::new([ApproverSelector::human("ana")]);
3595        let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
3596            .with_router(policy.clone());
3597        let scope = ApprovalScope::new("adk-rust", "ana", "s-1");
3598        let mut held = ToolConfirmationRequest::new("verb_snooze", json!({ "item": "agenda-7" }));
3599        held.function_call_id = Some("call-1".into());
3600        held.origin = Some(verb_origin());
3601        let call = ApprovalCall {
3602            scope: scope.clone(),
3603            request: held.clone(),
3604            reason: "Move News digest to 19:00".into(),
3605            agent_name: "finance".into(),
3606            invocation_id: "inv".into(),
3607            run_id: None,
3608            acting: None,
3609        };
3610
3611        let request = service.submit_call(call).await.unwrap().unwrap();
3612        let mut expected = ApprovalRequest::new(request.id.clone(), scope, &held, policy)
3613            .with_summary("Move News digest to 19:00")
3614            .with_requester(SubjectRef::human("ana"));
3615        expected.created_at = request.created_at;
3616        assert_eq!(request, expected);
3617        assert_eq!(expected.origin, Some(verb_origin()));
3618        assert_eq!(service.get(&request.id).await.unwrap(), Some(request));
3619    }
3620
3621    #[test]
3622    fn with_origin_names_the_tools_publisher() {
3623        let call = ToolConfirmationRequest::new("pay", json!({}));
3624        let policy = ApprovalPolicy::new([ApproverSelector::human("ana")]);
3625        let request =
3626            ApprovalRequest::new("apr-1", ApprovalScope::new("a", "u", "s"), &call, policy);
3627        assert_eq!(request.origin, None);
3628        let named = request.clone().with_origin(verb_origin());
3629        assert_eq!(named, ApprovalRequest { origin: Some(verb_origin()), ..request });
3630    }
3631
3632    /// A request stored before the field existed reads with no origin, and a request without
3633    /// one writes no `origin` key, so stores keep reading what they wrote (spec 3.3 §7.1).
3634    #[test]
3635    fn a_record_without_an_origin_reads_as_none() {
3636        let call = ToolConfirmationRequest::new("pay", json!({ "cents": 500 }));
3637        let policy = ApprovalPolicy::new([ApproverSelector::human("ana")]);
3638        let request =
3639            ApprovalRequest::new("apr-1", ApprovalScope::new("a", "u", "s"), &call, policy);
3640        let written = serde_json::to_value(&request).unwrap();
3641        assert_eq!(written.get("origin"), None);
3642        let read: ApprovalRequest = serde_json::from_value(written).unwrap();
3643        assert_eq!(read, request);
3644
3645        let named = request.with_origin(verb_origin());
3646        let written = serde_json::to_value(&named).unwrap();
3647        assert_eq!(
3648            written["origin"],
3649            json!({ "source": "verbs:adk-rust", "declarationDigest": verb_origin().declaration_digest })
3650        );
3651        assert_eq!(serde_json::from_value::<ApprovalRequest>(written).unwrap(), named);
3652    }
3653
3654    /// A host routes and hears the held calls of a service built without a router or
3655    /// notifiers; a router the service was built with keeps its own decisions.
3656    #[tokio::test]
3657    async fn a_host_routes_and_hears_a_service_built_without_a_router() {
3658        use crate::InMemoryApprovalStore;
3659
3660        #[derive(Debug, Default)]
3661        struct Heard(std::sync::Mutex<Vec<(ApprovalEventKind, ApprovalState)>>);
3662
3663        #[async_trait]
3664        impl ApprovalNotifier for Heard {
3665            async fn notify(&self, notification: &ApprovalNotification) -> Result<()> {
3666                let heard = (notification.kind, notification.request.state);
3667                self.0.lock().unwrap().push(heard);
3668                Ok(())
3669            }
3670        }
3671
3672        let call = |args: Value| ApprovalCall {
3673            scope: ApprovalScope::new("app", "ana", "s-1"),
3674            request: ToolConfirmationRequest::new("bash", args),
3675            reason: "needs approval".into(),
3676            agent_name: "agent".into(),
3677            invocation_id: "inv".into(),
3678            run_id: Some("run-1".into()),
3679            acting: None,
3680        };
3681        let operator = || -> Arc<dyn ApprovalRouter> {
3682            Arc::new(
3683                ApprovalPolicy::new([ApproverSelector::group("operator")]).allow_self_approval(),
3684            )
3685        };
3686
3687        let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()));
3688        assert_eq!(service.submit_call(call(json!({ "command": "ls" }))).await.unwrap(), None);
3689        let heard = Arc::new(Heard::default());
3690        assert!(service.route_unrouted(operator()));
3691        assert!(service.add_notifier(heard.clone()));
3692        let filed = service.submit_call(call(json!({ "command": "date" }))).await.unwrap();
3693        let filed = filed.expect("the host's router files the call");
3694        assert_eq!(filed.policy.approvers, vec![ApproverSelector::group("operator")]);
3695        let decision =
3696            ApprovalDecision::approve(SubjectRef::human("ana")).with_groups(["operator"]);
3697        service.decide(&filed.id, filed.version, decision).await.unwrap();
3698        assert_eq!(
3699            *heard.0.lock().unwrap(),
3700            vec![
3701                (ApprovalEventKind::Submitted, ApprovalState::Pending),
3702                (ApprovalEventKind::Decided, ApprovalState::Approved),
3703                (ApprovalEventKind::Resolved, ApprovalState::Approved),
3704            ]
3705        );
3706
3707        // A service's own router may leave a call in the store only; a host's does not
3708        // replace it.
3709        let declines = |_: &ApprovalCall| -> Option<ApprovalRoute> { None };
3710        let own =
3711            StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new())).with_router(declines);
3712        assert!(own.route_unrouted(operator()));
3713        assert_eq!(own.submit_call(call(json!({ "command": "ls" }))).await.unwrap(), None);
3714    }
3715}