Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-mcp/src/approval.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-mcp / src / approval.rs` 297 lines ยท 11553 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Single-use approvals for the host-owned authority seam. 17 //! 18 //! When an [`crate::EffectAuthority`] answers `RequireApproval`, a host approver (a human or an 19 //! approval service, holding an [`ApprovalDesk`]) may issue one [`ApprovalGrant`]. The grant is 20 //! bound to one effect identity: the intent digest (tool, arguments, catalog), the idempotency 21 //! key, the world and the winning J-node. Spending is two-phase: 22 //! 23 //! 1. [`crate::EffectLane::authorize_approved`] *reserves* the grant when it mints the 24 //! `AuthorizedEffect`. While reserved, no other mint can use it ([`ApprovalError::Reserved`]). 25 //! 2. [`crate::EffectLane::execute_effect`] *commits* the reservation just before the provider is 26 //! called: the grant is now spent for good ([`ApprovalError::Consumed`]). 27 //! 3. If the `AuthorizedEffect` is dropped without running, or cancelled with 28 //! [`crate::AuthorizedEffect::cancel`], the reservation is *released*: the grant is available 29 //! again, and expiry, revocation and the effect binding are re-checked at the next mint. 30 //! 31 //! Limit: the broker keeps grant state in memory only. A restart forgets every grant (each is 32 //! `Unknown` afterwards), so a reserved or spent grant can never run twice across a restart; the 33 //! approver must issue a new one. 34 //! 35 //! Replay of a finished request does not need a second approval: the existing effect ledger 36 //! (keyed by the idempotency key) already returns the original receipt, and 37 //! [`crate::EffectLane::authorize_and_execute_approved`] consults it for a spent grant that is 38 //! bound to the same effect. 39 //! 40 //! A grant that has not been spent can be withdrawn with [`ApprovalDesk::revoke`]; after that 41 //! it is refused with [`ApprovalError::Revoked`] and cannot be spent. 42 //! 43 //! Expiry uses a host-supplied `now` and `expires_at` in the same unit. The crate reads no clock. 44 45 use std::sync::atomic::{AtomicBool, Ordering}; 46 47 use aien_capability::{Digest32, EffectId, JNodeId, WorldId}; 48 49 use crate::authority::{intent_digest, EffectScope}; 50 use crate::broker::{Inner, McpBroker}; 51 use crate::EffectIntent; 52 53 /// Why an approval could not be spent. 54 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 55 pub enum ApprovalError { 56 /// The grant was not issued by this broker's desk. 57 Unknown, 58 /// The grant is bound to a different effect than the one presented. Nothing is spent. 59 Mismatch, 60 /// The grant was already spent: an effect minted from it reached `execute_effect`. 61 Consumed, 62 /// The grant is reserved by a live `AuthorizedEffect` that has not run yet. It becomes 63 /// usable again if that effect is dropped or cancelled un-executed. 64 Reserved, 65 /// `now` is at or past `expires_at`. Nothing is spent. 66 Expired, 67 /// The approver withdrew the grant with [`ApprovalDesk::revoke`] before it was spent. 68 Revoked, 69 } 70 71 /// Proof that a host approver approved exactly one effect. Fields are private and only an 72 /// [`ApprovalDesk`] can create one. Cloning does not duplicate it: spending is tracked by the 73 /// broker, not by the value. 74 #[derive(Clone, Debug)] 75 pub struct ApprovalGrant { 76 id: Digest32, 77 } 78 79 #[derive(Debug)] 80 pub(crate) struct ApprovalRecord { 81 pub(crate) intent_digest: Digest32, 82 pub(crate) idempotency_key: EffectId, 83 pub(crate) world_id: WorldId, 84 pub(crate) winning_jnode: JNodeId, 85 pub(crate) expires_at: u64, 86 pub(crate) state: GrantState, 87 pub(crate) revoked: bool, 88 pub(crate) release_reason: Option, 89 } 90 91 impl ApprovalRecord { 92 pub(crate) fn binds(&self, intent: &EffectIntent, scope: &EffectScope) -> bool { 93 self.intent_digest == intent_digest(intent) 94 && self.idempotency_key == scope.idempotency_key 95 && self.world_id == scope.world_id 96 && self.winning_jnode == scope.winning_jnode 97 } 98 } 99 100 impl ApprovalGrant { 101 pub(crate) fn id(&self) -> Digest32 { 102 self.id 103 } 104 } 105 106 /// The approver's handle. Held by the host's approval service, not by J-Space or the effect 107 /// lane's callers. Limit: any code holding a `McpBroker` or `SessionManager` can obtain one, so 108 /// the separation is by handle discipline, not by type. 109 #[derive(Clone)] 110 pub struct ApprovalDesk { 111 broker: McpBroker, 112 } 113 114 impl ApprovalDesk { 115 pub fn new(broker: McpBroker) -> Self { 116 Self { broker } 117 } 118 119 /// Issue one grant for exactly this intent and scope, valid while `now < expires_at`. 120 pub fn issue( 121 &self, 122 intent: &EffectIntent, 123 scope: EffectScope, 124 expires_at: u64, 125 ) -> ApprovalGrant { 126 let mut inner = self.broker.lock(); 127 inner.next_approval = inner.next_approval.saturating_add(1); 128 let digest = intent_digest(intent); 129 let mut bytes = inner.next_approval.to_le_bytes().to_vec(); 130 bytes.extend_from_slice(&digest.0); 131 bytes.extend_from_slice(&scope.idempotency_key.0); 132 let id = Digest32::of(&bytes); 133 inner.approvals.insert( 134 id, 135 ApprovalRecord { 136 intent_digest: digest, 137 idempotency_key: scope.idempotency_key, 138 world_id: scope.world_id, 139 winning_jnode: scope.winning_jnode, 140 expires_at, 141 state: GrantState::Available, 142 revoked: false, 143 release_reason: None, 144 }, 145 ); 146 ApprovalGrant { id } 147 } 148 149 /// Withdraw a grant that has not been spent. Returns `true` if the grant is now dead. 150 /// A grant that was already spent (an effect may have been minted or run), or that this 151 /// desk never issued, returns `false` and nothing changes. Revoking twice is `true` both times. 152 pub fn revoke(&self, grant: &ApprovalGrant) -> bool { 153 let mut inner = self.broker.lock(); 154 match inner.approvals.get_mut(&grant.id()) { 155 Some(record) if record.state == GrantState::Available => { 156 record.revoked = true; 157 true 158 } 159 _ => false, 160 } 161 } 162 } 163 164 /// Where a grant is in its life. Private: hosts see [`GrantStatus`]. 165 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 166 pub(crate) enum GrantState { 167 Available, 168 /// Held by the `AuthorizedEffect` carrying this reservation token. 169 Reserved(u64), 170 Spent, 171 } 172 173 /// What a host can ask about a grant with [`ApprovalDesk::status`]. 174 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 175 pub enum GrantStatus { 176 /// Unspent and unreserved. It may still be expired; expiry is judged at mint against the 177 /// host's `now`. 178 Available, 179 /// A live `AuthorizedEffect` holds it and has not run. 180 Reserved, 181 /// An effect minted from it reached `execute_effect`. Final. 182 Spent, 183 /// The approver withdrew it before it was spent. 184 Revoked, 185 } 186 187 /// The broker-side hold a minted effect carries. Shared by clones of the effect (`Arc`), so the 188 /// grant is released when the last clone is dropped un-executed, or when any clone cancels. 189 pub(crate) struct Reservation { 190 broker: McpBroker, 191 grant: Digest32, 192 token: u64, 193 finished: AtomicBool, 194 } 195 196 impl std::fmt::Debug for Reservation { 197 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 198 f.debug_struct("Reservation") 199 .field("token", &self.token) 200 .finish_non_exhaustive() 201 } 202 } 203 204 impl Reservation { 205 pub(crate) fn new(broker: McpBroker, grant: Digest32, token: u64) -> Self { 206 Self { 207 broker, 208 grant, 209 token, 210 finished: AtomicBool::new(false), 211 } 212 } 213 214 pub(crate) fn grant_id(&self) -> Digest32 { 215 self.grant 216 } 217 218 /// Make the spend final. The caller already holds the broker lock (`inner`). Fails if the 219 /// reservation was released (cancelled) first. 220 pub(crate) fn commit_locked( 221 &self, 222 inner: &mut Inner, 223 now: Option, 224 ) -> Result<(), crate::Error> { 225 match inner.approvals.get_mut(&self.grant) { 226 Some(r) if r.state == GrantState::Reserved(self.token) => { 227 // Fail closed: without a clock expiry cannot be checked, so an approved effect 228 // does not run. The grant is given back. 229 let Some(now) = now else { 230 r.state = GrantState::Available; 231 r.release_reason = Some("no clock: expiry cannot be checked".to_string()); 232 self.finished.store(true, Ordering::SeqCst); 233 return Err(crate::Error::ApprovalClockMissing); 234 }; 235 if now >= r.expires_at { 236 // Fail closed: give the grant back (a later mint refuses it as Expired). 237 r.state = GrantState::Available; 238 r.release_reason = Some("expired before execute".to_string()); 239 self.finished.store(true, Ordering::SeqCst); 240 return Err(crate::Error::ApprovalExpired); 241 } 242 r.state = GrantState::Spent; 243 self.finished.store(true, Ordering::SeqCst); 244 Ok(()) 245 } 246 _ => Err(crate::Error::ApprovalNotReserved), 247 } 248 } 249 250 /// Give the grant back. Idempotent; a no-op after commit or an earlier release. 251 pub(crate) fn release(&self, reason: &str) { 252 if self.finished.swap(true, Ordering::SeqCst) { 253 return; 254 } 255 let mut inner = self.broker.lock(); 256 if let Some(r) = inner.approvals.get_mut(&self.grant) { 257 if r.state == GrantState::Reserved(self.token) { 258 r.state = GrantState::Available; 259 r.release_reason = Some(reason.to_string()); 260 } 261 } 262 } 263 } 264 265 impl Drop for Reservation { 266 fn drop(&mut self) { 267 self.release("dropped before execute_effect"); 268 } 269 } 270 271 impl ApprovalGrant { 272 /// Stable id of this grant (a digest). Hosts may use it as a correlation handle; it carries 273 /// no authority, since spending needs the broker's own record. 274 pub fn approval_id(&self) -> Digest32 { 275 self.id 276 } 277 } 278 279 impl ApprovalDesk { 280 /// Current status of `grant`, or `None` if this desk never issued it. 281 pub fn status(&self, grant: &ApprovalGrant) -> Option { 282 let inner = self.broker.lock(); 283 let r = inner.approvals.get(&grant.id())?; 284 Some(match r.state { 285 GrantState::Spent => GrantStatus::Spent, 286 GrantState::Reserved(_) => GrantStatus::Reserved, 287 GrantState::Available if r.revoked => GrantStatus::Revoked, 288 GrantState::Available => GrantStatus::Available, 289 }) 290 } 291 292 /// Why the grant was last released (`None` if it never was, or this desk did not issue it). 293 pub fn release_reason(&self, grant: &ApprovalGrant) -> Option { 294 let inner = self.broker.lock(); 295 inner.approvals.get(&grant.id())?.release_reason.clone() 296 } 297 }