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/patches/10edf1aa6413903b
# 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
## GitHub aien-dev/aien-sovereign-core-mv#204 (code only)
closed derived `10edf1aa6413903b` #204
Imported from GitHub aien-dev/aien-sovereign-core-mv#204 (code only)
GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).
Base `2a968bfc2770c012b4d53cfb1669f97594d2ff31` · Head `4474603dfa81c80d9484dfd8502a483a4557b1d3`
greptile-apps[bot] commented on `crates/aien-mcp/src/approval.rs` line 94 on 2026-10-04 22:31 UTC
Grants can cross brokers
Two brokers issuing a grant for the same intent and key produce the same grant ID. Once broker B has issued its matching grant, presenting broker A's grant to B executes B's effect and consumes B's approval. Bind grant IDs to their issuing broker before merging.
How this was verified: A grant issued by broker A executed broker B's tool after B issued a matching grant.
Artifacts
Cross-broker grant test source
- The authored tests issue real broker grants and call the public authorization and execution APIs, reproducing cross-broker approval spending.
Cross-broker grant test command
- The script temporarily installs the test, runs both Cargo commands, captures their output, and removes the temporary test file.
Foreign grant before B issues approval
- The executed Rust test shows broker B returning `Approval(Unknown)` for A’s grant with zero B tool calls.
Foreign grant after B issues approval
- The executed Rust test shows A’s grant producing B’s receipt and consuming B’s own grant, confirming the approval-boundary failure.
Ran code and verified through T-RexPrompt To Fix With AI
```
This is a comment left during a code review.
Path: crates/aien-mcp/src/approval.rs
Line: 91-94
Comment:
**Grants can cross brokers**
Two brokers issuing a grant for the same intent and key produce the same grant ID. Once broker B has issued its matching grant, presenting broker A's grant to B executes B's effect and consumes B's approval. Bind grant IDs to their issuing broker before merging.
**How this was verified:** A grant issued by broker A executed broker B's tool after B issued a matching grant.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
```
greptile-apps[bot] commented on `crates/aien-mcp/src/broker.rs` line 380 on 2026-10-04 22:31 UTC
Replay returns wrong receipt
A grant can be spent by minting an effect without executing it. If a different effect completes under the same idempotency key, replaying the approved request returns that effect's receipt. The approved effect never ran, yet its caller receives a success result. Verify the completed effect's identity before returning its receipt; this must be fixed before merging.
Artifacts
Wrong-receipt replay test source
- The public-API test spends a grant without execution, executes a different intent with the shared key, and asserts that replay cannot claim its receipt.
Captured replay test source
- The numbered source was captured by a command with its working directory and exit code, showing the exact test used.
Replay result against PR code
- The Rust test exited 101 because approved replay returned the different effect's receipt; the claimed path is reachable.
Replay result with identity check
- The same Rust test exited 0 and replay returned `Err(Approval(Consumed))`; checking the recorded intent prevents the receipt mix-up.
Ran code and verified through T-RexPrompt To Fix With AI
```
This is a comment left during a code review.
Path: crates/aien-mcp/src/broker.rs
Line: 379-380
Comment:
**Replay returns wrong receipt**
A grant can be spent by minting an effect without executing it. If a different effect completes under the same idempotency key, replaying the approved request returns that effect's receipt. The approved effect never ran, yet its caller receives a success result. Verify the completed effect's identity before returning its receipt; this must be fixed before merging.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
```
greptile-apps[bot] commented on `crates/aien-mcp/src/broker.rs` line 361 on 2026-10-04 22:31 UTC
Replay ignores current refusals
After an approved effect completes, replay returns its old receipt even when the authority now says Deny or Contain, or the catalog has changed. The provider does not run again, but callers receive a success result where ordinary authorization reports a refusal. This non-blocking inconsistency makes the current request status misleading.
Artifacts
Current-refusal replay test source
- Captured the Rust test source used for both runs, showing the three policy and catalog changes and the comparison call.
Replay without early return
- Ran the test with lines 358–360 removed in a temporary worktree; both service calls refused each changed-condition replay.
Replay with PR early return
- Ran the same test against the PR code; approved replays returned the original receipt while ordinary authorization refused them.
Ran code and verified through T-RexPrompt To Fix With AI
```
This is a comment left during a code review.
Path: crates/aien-mcp/src/broker.rs
Line: 358-361
Comment:
**Replay ignores current refusals**
After an approved effect completes, replay returns its old receipt even when the authority now says Deny or Contain, or the catalog has changed. The provider does not run again, but callers receive a success result where ordinary authorization reports a refusal. This non-blocking inconsistency makes the current request status misleading.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
```
greptile-apps[bot] commented on `crates/aien-mcp/src/approval.rs` line 95 on 2026-10-04 22:31 UTC
Approval records accumulate
Issuing a grant adds a record that remains after the grant is spent or expires. A long-running broker therefore uses more memory with each approval, including approvals that can no longer be spent. This is a non-blocking retention concern; add bounded cleanup without breaking valid receipt replays.
Artifacts
Approval retention test command
- This authored command copied the committed source into a temporary workspace and ran both focused tests without changing tracked files.
Approval retention test source
- This authored Rust test exercised issuance, execution, spending, expiry rejection, further issuance, and direct inspection of the broker's approval map.
Initial approval record count
- The first executed test counted two issued records before spending or further issuance.
Record count after spending and expiry
- The second executed test found 1,002 records and confirmed that the original spent and expired records were still present.
Ran code and verified through T-RexPrompt To Fix With AI
```
This is a comment left during a code review.
Path: crates/aien-mcp/src/approval.rs
Line: 95
Comment:
**Approval records accumulate**
Issuing a grant adds a record that remains after the grant is spent or expires. A long-running broker therefore uses more memory with each approval, including approvals that can no longer be spent. This is a non-blocking retention concern; add bounded cleanup without breaking valid receipt replays.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
```
greptile-apps[bot] commented on `crates/aien-mcp/tests/approval.rs` line 39 on 2026-10-04 22:31 UTC
Rename the test helper
The new helper is named `harness`, a word forbidden by the repository's Sovereign Voice directive. Rename the helper and its uses to satisfy this repository requirement before merging.
Context Used: AGENTS.md (source )
Prompt To Fix With AI
```
This is a comment left during a code review.
Path: crates/aien-mcp/tests/approval.rs
Line: 39
Comment:
**Rename the test helper**
The new helper is named `harness`, a word forbidden by the repository's Sovereign Voice directive. Rename the helper and its uses to satisfy this repository requirement before merging.
**Context Used:** AGENTS.md ([source](https://github.com/aien-dev/aien-sovereign-core/blob/main/AGENTS.md))
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
```
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
greptile-apps[bot] reviewed (COMMENTED) on 2026-10-04 22:31 UTC
greptile-apps[bot] wrote on 2026-10-04 22:31 UTC
Confidence Score: 2/5
[Critical risk] Adds approval-gate mechanism to effect authorization.
Do not merge until cross-broker grant use, incorrect replay receipts, and the repository naming violation are fixed. The replay-status and record-retention concerns are non-blocking.
Findings
- Grants can cross brokers ▶
- Replay returns wrong receipt ▶
- Replay ignores current refusals ▶
- Approval records accumulate ▶
- Rename the test helper ▶ Fix with agent prompt
```
### Issue 1
crates/aien-mcp/src/approval.rs:91-94
Two brokers issuing a grant for the same intent and key produce the same grant ID. Once broker B has issued its matching grant, presenting broker A's grant to B executes B's effect and consumes B's approval. Bind grant IDs to their issuing broker before merging.
**How this was verified:** A grant issued by broker A executed broker B's tool after B issued a matching grant.
### Issue 2
crates/aien-mcp/src/broker.rs:379-380
A grant can be spent by minting an effect without executing it. If a different effect completes under the same idempotency key, replaying the approved request returns that effect's receipt. The approved effect never ran, yet its caller receives a success result. Verify the completed effect's identity before returning its receipt; this must be fixed before merging.
### Issue 3
crates/aien-mcp/src/broker.rs:358-361
After an approved effect completes, replay returns its old receipt even when the authority now says Deny or Contain, or the catalog has changed. The provider does not run again, but callers receive a success result where ordinary authorization reports a refusal. This non-blocking inconsistency makes the current request status misleading.
### Issue 4
crates/aien-mcp/src/approval.rs:95
Issuing a grant adds a record that remains after the grant is spent or expires. A long-running broker therefore uses more memory with each approval, including approvals that can no longer be spent. This is a non-blocking retention concern; add bounded cleanup without breaking valid receipt replays.
### Issue 5
crates/aien-mcp/tests/approval.rs:39
The new helper is named `harness`, a word forbidden by the repository's Sovereign Voice directive. Rename the helper and its uses to satisfy this repository requirement before merging.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
```
Summary
The PR adds single-use approval grants and an approved execution path. Matching grants can cross broker boundaries, and an approved replay can return a receipt for an effect that never ran. Those failures block merging. Replay also reports success after current refusal conditions change, and approval records accumulate. The new test helper must be renamed to meet a repository requirement before merging. Reviews (1) · Last reviewed commit: "feat(aien-mcp): single-use approval cons..."
### Apply it
```
git checkout -b patch-10edf1aa6413903b 2a968bfc2770c012b4d53cfb1669f97594d2ff31
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/10edf1aa6413903b.patch | git am
```
Raw patch (mbox) · Diff
### Provenance
This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:
```
github-import 1
aien-dev/aien-sovereign-core-mv
204
4474603dfa81c80d9484dfd8502a483a4557b1d3
```
```
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":204,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/204","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:17Z","metadata":"unavailable","state_derived":true}
```
### Changes
```
diff --git a/.crumb b/.crumb
index 0c24acf6..091aca72 100644
--- a/.crumb
+++ b/.crumb
@@ -77,14 +77,14 @@
}
],
"children_root": "sha256:dfcfd805db0c30c667bc5682364bd3acb3383d494967dcae39f2420739723d7d",
- "compiled_at": "2026-10-04T20:38:05Z",
+ "compiled_at": "2026-10-04T22:24:32Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:6d499cbb26f7041353de10fd948cdbfa3013d648c58da39dc6395cc409b898a9",
+ "digest": "sha256:ccab54027d46c9733e848bd4fad0fb4c072c942a2177128415f989770ff742c5",
"evidence_files": 20,
"evidence_root": "sha256:1ef4526f6fe1ba0cee21a89c3313d37bf2e94e1aa2e9bd1a364225e52882d170",
- "files": 677,
- "generated_at_commit": "8c60f97ed5d702df3bd1966a8d0691e0b9c113c9",
- "source_tree": "sha256:6edde9bdd6a59719ac31631c16a3520139a9b6cc61ac8f9e122a16b26a9610c0"
+ "files": 680,
+ "generated_at_commit": "2a968bfc2770c012b4d53cfb1669f97594d2ff31",
+ "source_tree": "sha256:ac6c6dfb3cb4d1e232093b035d8caa741ae9e5844d1c418a2b18aa4f13eebf6c"
}
},
"history": [],
diff --git a/crates/aien-mcp/src/approval.rs b/crates/aien-mcp/src/approval.rs
new file mode 100644
index 00000000..ab8d2330
--- /dev/null
+++ b/crates/aien-mcp/src/approval.rs
@@ -0,0 +1,108 @@
+//! Single-use approvals for the host-owned authority seam.
+//!
+//! When an [`crate::EffectAuthority`] answers `RequireApproval`, a host approver (a human or an
+//! approval service, holding an [`ApprovalDesk`]) may issue one [`ApprovalGrant`]. The grant is
+//! bound to one effect identity: the intent digest (tool, arguments, catalog), the idempotency
+//! key, the world and the winning J-node. [`crate::EffectLane::authorize_approved`] spends the
+//! grant when it mints the `AuthorizedEffect`. A second mint with the same grant is refused.
+//!
+//! Replay of a finished request does not need a second approval: the existing effect ledger
+//! (keyed by the idempotency key) already returns the original receipt, and
+//! [`crate::EffectLane::authorize_and_execute_approved`] consults it for a spent grant that is
+//! bound to the same effect.
+//!
+//! Expiry uses a host-supplied `now` and `expires_at` in the same unit. The crate reads no clock.
+
+use aien_capability::{Digest32, EffectId, JNodeId, WorldId};
+
+use crate::authority::{intent_digest, EffectScope};
+use crate::broker::McpBroker;
+use crate::EffectIntent;
+
+/// Why an approval could not be spent.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ApprovalError {
+ /// The grant was not issued by this broker's desk.
+ Unknown,
+ /// The grant is bound to a different effect than the one presented. Nothing is spent.
+ Mismatch,
+ /// The grant was already spent by an earlier mint.
+ Consumed,
+ /// `now` is at or past `expires_at`. Nothing is spent.
+ Expired,
+}
+
+/// Proof that a host approver approved exactly one effect. Fields are private and only an
+/// [`ApprovalDesk`] can create one. Cloning does not duplicate it: spending is tracked by the
+/// broker, not by the value.
+#[derive(Clone, Debug)]
+pub struct ApprovalGrant {
+ id: Digest32,
+}
+
+#[derive(Debug)]
+pub(crate) struct ApprovalRecord {
+ pub(crate) intent_digest: Digest32,
+ pub(crate) idempotency_key: EffectId,
+ pub(crate) world_id: WorldId,
+ pub(crate) winning_jnode: JNodeId,
+ pub(crate) expires_at: u64,
+ pub(crate) consumed: bool,
+}
+
+impl ApprovalRecord {
+ pub(crate) fn binds(&self, intent: &EffectIntent, scope: &EffectScope) -> bool {
+ self.intent_digest == intent_digest(intent)
+ && self.idempotency_key == scope.idempotency_key
+ && self.world_id == scope.world_id
+ && self.winning_jnode == scope.winning_jnode
+ }
+}
+
+impl ApprovalGrant {
+ pub(crate) fn id(&self) -> Digest32 {
+ self.id
+ }
+}
+
+/// The approver's handle. Held by the host's approval service, not by J-Space or the effect
+/// lane's callers. Limit: any code holding a `McpBroker` or `SessionManager` can obtain one, so
+/// the separation is by handle discipline, not by type.
+#[derive(Clone)]
+pub struct ApprovalDesk {
+ broker: McpBroker,
+}
+
+impl ApprovalDesk {
+ pub fn new(broker: McpBroker) -> Self {
+ Self { broker }
+ }
+
+ /// Issue one grant for exactly this intent and scope, valid while `now < expires_at`.
+ pub fn issue(
+ &self,
+ intent: &EffectIntent,
+ scope: EffectScope,
+ expires_at: u64,
+ ) -> ApprovalGrant {
+ let mut inner = self.broker.lock();
+ inner.next_approval = inner.next_approval.saturating_add(1);
+ let digest = intent_digest(intent);
+ let mut bytes = inner.next_approval.to_le_bytes().to_vec();
+ bytes.extend_from_slice(&digest.0);
+ bytes.extend_from_slice(&scope.idempotency_key.0);
+ let id = Digest32::of(&bytes);
+ inner.approvals.insert(
+ id,
+ ApprovalRecord {
+ intent_digest: digest,
+ idempotency_key: scope.idempotency_key,
+ world_id: scope.world_id,
+ winning_jnode: scope.winning_jnode,
+ expires_at,
+ consumed: false,
+ },
+ );
+ ApprovalGrant { id }
+ }
+}
diff --git a/crates/aien-mcp/src/authority.rs b/crates/aien-mcp/src/authority.rs
index a1868578..004779b7 100644
--- a/crates/aien-mcp/src/authority.rs
+++ b/crates/aien-mcp/src/authority.rs
@@ -17,6 +17,7 @@
use aien_capability::{Digest32, EffectId, JNodeId, ToolDescriptor, ToolEffects, WorldId};
+use crate::approval::ApprovalError;
use crate::{EffectIntent, Error};
/// Verdict of an [`EffectAuthority`]. Same five variants as aegis-runtime `DoctrineDecision`.
@@ -25,7 +26,7 @@ pub enum AuthorityDecision {
Allow,
/// Allowed under the listed restrictions (recorded in the policy digest).
AllowRestricted(Vec),
- /// A human or approval authority must decide. Nothing runs and nothing is consumed.
+ /// A human or approval authority must decide. Nothing runs and nothing is consumed until an approval is spent.
RequireApproval(String),
Deny(String),
Contain(String),
@@ -83,11 +84,13 @@ pub trait EffectAuthority {
#[derive(Debug, PartialEq, Eq)]
pub enum AuthorityOutcome {
/// Approval is required. Nothing executed. `intent_digest` names the intent to approve.
- /// No approval record is created or consumed by aien-mcp.
+ /// Issue one with [`crate::ApprovalDesk`] and spend it with [`crate::EffectLane::authorize_approved`].
Pending {
intent_digest: Digest32,
reason: String,
},
+ /// Approval was presented but could not be spent. See [`ApprovalError`].
+ Approval(ApprovalError),
Denied(String),
Contained(String),
/// Authorization succeeded but the effect lane failed (stale catalog, provider error, ...).
diff --git a/crates/aien-mcp/src/broker.rs b/crates/aien-mcp/src/broker.rs
index db0e3aa4..e55baa89 100644
--- a/crates/aien-mcp/src/broker.rs
+++ b/crates/aien-mcp/src/broker.rs
@@ -7,6 +7,7 @@ use aien_capability::{
};
use serde_json::Value;
+use crate::approval::{ApprovalError, ApprovalGrant, ApprovalRecord};
use crate::authority::{
intent_digest, AuthorityContext, AuthorityDecision, AuthorityOutcome, EffectAuthority,
EffectScope,
@@ -33,9 +34,11 @@ enum LedgerEntry {
Uncertain,
}
-struct Inner {
+pub(crate) struct Inner {
sessions: HashMap,
ledger: HashMap,
+ pub(crate) approvals: HashMap,
+ pub(crate) next_approval: u64,
}
/// Owns admitted MCP sessions and the idempotency ledger.
@@ -50,6 +53,8 @@ impl McpBroker {
inner: Arc::new(Mutex::new(Inner {
sessions: HashMap::new(),
ledger: HashMap::new(),
+ approvals: HashMap::new(),
+ next_approval: 0,
})),
}
}
@@ -90,7 +95,7 @@ impl McpBroker {
Ok(())
}
- fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
+ pub(crate) fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
self.inner
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
@@ -234,13 +239,40 @@ impl EffectLane {
///
/// The lane, not the caller, reads the live descriptor for the authority. A stale intent
/// (digest differs from the live catalog) is denied before the authority is asked.
- /// `RequireApproval` returns `Pending` with the intent digest; no approval is created or
- /// consumed here. `Deny` and `Contain` return errors.
+ /// `RequireApproval` returns `Pending` with the intent digest; no approval is consumed here
+ /// (see [`Self::authorize_approved`]). `Deny` and `Contain` return errors.
pub fn authorize(
&self,
intent: EffectIntent,
scope: EffectScope,
authority: &dyn EffectAuthority,
+ ) -> Result, AuthorityOutcome> {
+ self.authorize_inner(intent, scope, authority, None)
+ }
+
+ /// Like [`Self::authorize`], but a `RequireApproval` verdict is satisfied by spending `grant`.
+ ///
+ /// The grant must have been issued by an [`crate::ApprovalDesk`] for exactly this intent and
+ /// scope, must be unspent and unexpired (`now < expires_at`). A refused grant is not spent
+ /// unless it was already spent. `Deny` and `Contain` stay refused whatever the grant says,
+ /// and an `Allow` verdict never touches the grant.
+ pub fn authorize_approved(
+ &self,
+ intent: EffectIntent,
+ scope: EffectScope,
+ authority: &dyn EffectAuthority,
+ grant: &ApprovalGrant,
+ now: u64,
+ ) -> Result, AuthorityOutcome> {
+ self.authorize_inner(intent, scope, authority, Some((grant, now)))
+ }
+
+ fn authorize_inner(
+ &self,
+ intent: EffectIntent,
+ scope: EffectScope,
+ authority: &dyn EffectAuthority,
+ approval: Option<(&ApprovalGrant, u64)>,
) -> Result, AuthorityOutcome> {
let (descriptor, live) = {
let inner = self.broker.lock();
@@ -274,10 +306,24 @@ impl EffectLane {
live,
scope.idempotency_key,
)),
- AuthorityDecision::RequireApproval(reason) => Err(AuthorityOutcome::Pending {
- intent_digest: intent_digest(&intent),
- reason,
- }),
+ AuthorityDecision::RequireApproval(reason) => {
+ let Some((grant, now)) = approval else {
+ return Err(AuthorityOutcome::Pending {
+ intent_digest: intent_digest(&intent),
+ reason,
+ });
+ };
+ self.spend(grant, &intent, &scope, now)
+ .map_err(AuthorityOutcome::Approval)?;
+ Ok(mint(
+ intent,
+ scope.world_id,
+ scope.winning_jnode,
+ policy_digest,
+ live,
+ scope.idempotency_key,
+ ))
+ }
AuthorityDecision::Deny(reason) => Err(AuthorityOutcome::Denied(reason)),
AuthorityDecision::Contain(reason) => Err(AuthorityOutcome::Contained(reason)),
}
@@ -296,6 +342,73 @@ impl EffectLane {
.map_err(AuthorityOutcome::Execution)
}
+ /// `authorize_approved`, then `execute_effect`.
+ ///
+ /// If `grant` is already spent for this same effect (same intent, key, world, J-node), the
+ /// request is a replay: the ledger's existing outcome is returned and nothing is minted.
+ /// Any other use of a spent grant is refused with `ApprovalError::Consumed`.
+ pub async fn authorize_and_execute_approved(
+ &self,
+ intent: EffectIntent,
+ scope: EffectScope,
+ authority: &dyn EffectAuthority,
+ grant: &ApprovalGrant,
+ now: u64,
+ ) -> Result {
+ if let Some(existing) = self.replay_of(grant, &intent, &scope) {
+ return existing.map_err(AuthorityOutcome::Execution);
+ }
+ let effect = self.authorize_approved(intent, scope, authority, grant, now)?;
+ self.execute_effect(effect)
+ .await
+ .map_err(AuthorityOutcome::Execution)
+ }
+
+ /// Ledger outcome for a spent grant presented again for the effect it was spent on.
+ fn replay_of(
+ &self,
+ grant: &ApprovalGrant,
+ intent: &EffectIntent,
+ scope: &EffectScope,
+ ) -> Option> {
+ let inner = self.broker.lock();
+ let record = inner.approvals.get(&grant.id())?;
+ if !record.consumed || !record.binds(intent, scope) {
+ return None;
+ }
+ match inner.ledger.get(&scope.idempotency_key)? {
+ LedgerEntry::Completed(receipt) => Some(Ok(receipt.clone())),
+ LedgerEntry::Uncertain => Some(Err(Error::ReconciliationRequired)),
+ LedgerEntry::InFlight => Some(Err(Error::EffectInFlight)),
+ }
+ }
+
+ /// Check and spend `grant` atomically under the broker lock.
+ fn spend(
+ &self,
+ grant: &ApprovalGrant,
+ intent: &EffectIntent,
+ scope: &EffectScope,
+ now: u64,
+ ) -> Result<(), ApprovalError> {
+ let mut inner = self.broker.lock();
+ let record = inner
+ .approvals
+ .get_mut(&grant.id())
+ .ok_or(ApprovalError::Unknown)?;
+ if !record.binds(intent, scope) {
+ return Err(ApprovalError::Mismatch);
+ }
+ if record.consumed {
+ return Err(ApprovalError::Consumed);
+ }
+ if now >= record.expires_at {
+ return Err(ApprovalError::Expired);
+ }
+ record.consumed = true;
+ Ok(())
+ }
+
pub async fn execute_effect(
&self,
effect: AuthorizedEffect,
diff --git a/crates/aien-mcp/src/lib.rs b/crates/aien-mcp/src/lib.rs
index 1a03a777..dd2d890a 100644
--- a/crates/aien-mcp/src/lib.rs
+++ b/crates/aien-mcp/src/lib.rs
@@ -4,6 +4,7 @@
//! and may invoke only speculation-safe tools. An irreversible `tools/call`
//! runs only when the Effect Broker presents an [`AuthorizedEffect`].
+mod approval;
mod authority;
mod broker;
mod effect;
@@ -23,6 +24,7 @@ mod transport_tests;
#[cfg(test)]
pub(crate) use effect::authorize_for_test;
+pub use approval::{ApprovalDesk, ApprovalError, ApprovalGrant};
pub use authority::{
intent_digest, AuthorityContext, AuthorityDecision, AuthorityOutcome, EffectAuthority,
EffectClassAuthority, EffectScope,
diff --git a/crates/aien-mcp/src/session.rs b/crates/aien-mcp/src/session.rs
index 481d054d..3c0b7ede 100644
--- a/crates/aien-mcp/src/session.rs
+++ b/crates/aien-mcp/src/session.rs
@@ -8,7 +8,7 @@ use rmcp::service::RoleClient;
use rmcp::transport::IntoTransport;
use crate::transport::RmcpClientWire;
-use crate::{EffectLane, Error, McpBroker, McpWire, SpeculativeLane};
+use crate::{ApprovalDesk, EffectLane, Error, McpBroker, McpWire, SpeculativeLane};
/// Admits MCP providers and hands out the two lanes.
///
@@ -34,6 +34,11 @@ impl SessionManager {
EffectLane::new(self.broker.clone())
}
+ /// The approver's handle. Keep it away from callers of the effect lane.
+ pub fn approval_desk(&self) -> ApprovalDesk {
+ ApprovalDesk::new(self.broker.clone())
+ }
+
/// Enroll a provider that is already on an [`McpWire`].
pub async fn enroll(&self, provider: ProviderId, wire: Arc) -> Result<(), Error> {
self.broker.admit(provider, wire).await
diff --git a/crates/aien-mcp/tests/approval.rs b/crates/aien-mcp/tests/approval.rs
new file mode 100644
index 00000000..c7bad812
--- /dev/null
+++ b/crates/aien-mcp/tests/approval.rs
@@ -0,0 +1,281 @@
+//! Single-use approval consumption, through the public API only.
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use aien_capability::{
+ Digest32, EffectId, JNodeId, ProviderId, ToolDescriptor, ToolEffects, WorldId,
+};
+use aien_mcp::memory::MemoryWire;
+use aien_mcp::{
+ ApprovalDesk, ApprovalError, AuthorityContext, AuthorityDecision, AuthorityOutcome,
+ CallOutcome, EffectAuthority, EffectClassAuthority, EffectIntent, EffectLane, EffectScope,
+ McpBroker, SpeculativeLane,
+};
+use serde_json::json;
+
+struct Fixed(AuthorityDecision);
+impl EffectAuthority for Fixed {
+ fn authorize(&self, _: &EffectIntent, _: &AuthorityContext) -> AuthorityDecision {
+ self.0.clone()
+ }
+}
+
+struct H {
+ broker: McpBroker,
+ lane: EffectLane,
+ desk: ApprovalDesk,
+ calls: Arc,
+ intent: EffectIntent,
+}
+
+fn scope(label: &str) -> EffectScope {
+ EffectScope {
+ world_id: WorldId(1),
+ winning_jnode: JNodeId(1),
+ idempotency_key: EffectId::from_label(label),
+ }
+}
+
+async fn harness() -> H {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let c = calls.clone();
+ let tool = ToolDescriptor::new("t", ToolEffects::WORLD_MUTATION, Digest32::of(b"t"));
+ let wire = MemoryWire::new(vec![tool], move |_, _| {
+ c.fetch_add(1, Ordering::SeqCst);
+ CallOutcome::Finished(json!({"done": true}))
+ });
+ let broker = McpBroker::new();
+ let provider = ProviderId::new("p");
+ broker
+ .admit(provider.clone(), Arc::new(wire))
+ .await
+ .unwrap();
+ let live = SpeculativeLane::new(broker.clone())
+ .discovery_snapshot(&provider)
+ .await
+ .unwrap()
+ .catalog_digest;
+ let intent = EffectIntent {
+ provider,
+ tool_name: "t".into(),
+ arguments: json!({"a": 1}),
+ capability_digest: live,
+ };
+ H {
+ lane: EffectLane::new(broker.clone()),
+ desk: ApprovalDesk::new(broker.clone()),
+ broker,
+ calls,
+ intent,
+ }
+}
+
+fn approval(e: AuthorityOutcome) -> ApprovalError {
+ match e {
+ AuthorityOutcome::Approval(a) => a,
+ other => panic!("expected Approval, got {other:?}"),
+ }
+}
+
+#[tokio::test]
+async fn first_use_mints_and_runs_once() {
+ let h = harness().await;
+ let g = h.desk.issue(&h.intent, scope("a"), 100);
+ let r = h
+ .lane
+ .authorize_and_execute_approved(h.intent.clone(), scope("a"), &EffectClassAuthority, &g, 1)
+ .await
+ .unwrap();
+ assert_eq!(r.output, json!({"done": true}));
+ assert_eq!(h.calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn second_mint_with_the_same_grant_is_refused() {
+ let h = harness().await;
+ let g = h.desk.issue(&h.intent, scope("b"), 100);
+ let a = EffectClassAuthority;
+ assert!(h
+ .lane
+ .authorize_approved(h.intent.clone(), scope("b"), &a, &g, 1)
+ .is_ok());
+ let err = h
+ .lane
+ .authorize_approved(h.intent.clone(), scope("b"), &a, &g, 1)
+ .unwrap_err();
+ assert_eq!(approval(err), ApprovalError::Consumed);
+ // A cloned grant is the same grant.
+ let err = h
+ .lane
+ .authorize_approved(h.intent.clone(), scope("b"), &a, &g.clone(), 1)
+ .unwrap_err();
+ assert_eq!(approval(err), ApprovalError::Consumed);
+}
+
+#[tokio::test]
+async fn replay_after_completion_returns_the_existing_receipt() {
+ let h = harness().await;
+ let g = h.desk.issue(&h.intent, scope("r"), 100);
+ let a = EffectClassAuthority;
+ let first = h
+ .lane
+ .authorize_and_execute_approved(h.intent.clone(), scope("r"), &a, &g, 1)
+ .await
+ .unwrap();
+ // Even after the grant has expired, the same logical request gets the same outcome.
+ let again = h
+ .lane
+ .authorize_and_execute_approved(h.intent.clone(), scope("r"), &a, &g, 10_000)
+ .await
+ .unwrap();
+ assert_eq!(first, again);
+ assert_eq!(h.calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn spent_grant_cannot_run_a_different_request_under_the_same_key() {
+ let h = harness().await;
+ let g = h.desk.issue(&h.intent, scope("k"), 100);
+ let a = EffectClassAuthority;
+ h.lane
+ .authorize_and_execute_approved(h.intent.clone(), scope("k"), &a, &g, 1)
+ .await
+ .unwrap();
+ let mut other = h.intent.clone();
+ other.arguments = json!({"a": 2});
+ let err = h
+ .lane
+ .authorize_and_execute_approved(other, scope("k"), &a, &g, 1)
+ .await
+ .unwrap_err();
+ assert_eq!(approval(err), ApprovalError::Mismatch);
+ assert_eq!(h.calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn grant_for_a_different_effect_is_refused_and_not_spent() {
+ let h = harness().await;
+ let g = h.desk.issue(&h.intent, scope("x"), 100);
+ let a = EffectClassAuthority;
+ let mut other = h.intent.clone();
+ other.arguments = json!({"a": 2});
+ let e = h
+ .lane
+ .authorize_approved(other, scope("x"), &a, &g, 1)
+ .unwrap_err();
+ assert_eq!(approval(e), ApprovalError::Mismatch);
+ let e = h
+ .lane
+ .authorize_approved(h.intent.clone(), scope("y"), &a, &g, 1)
+ .unwrap_err();
+ assert_eq!(approval(e), ApprovalError::Mismatch);
+ let mut w = scope("x");
+ w.world_id = WorldId(2);
+ let e = h
+ .lane
+ .authorize_approved(h.intent.clone(), w, &a, &g, 1)
+ .unwrap_err();
+ assert_eq!(approval(e), ApprovalError::Mismatch);
+ // The mismatches burned nothing: the right request still works.
+ assert!(h
+ .lane
+ .authorize_approved(h.intent.clone(), scope("x"), &a, &g, 1)
+ .is_ok());
+ assert_eq!(h.calls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn expired_grant_is_refused_and_not_spent() {
+ let h = harness().await;
+ let g = h.desk.issue(&h.intent, scope("e"), 50);
+ let a = EffectClassAuthority;
+ let e = h
+ .lane
+ .authorize_approved(h.intent.clone(), scope("e"), &a, &g, 50)
+ .unwrap_err();
+ assert_eq!(approval(e), ApprovalError::Expired);
+ assert!(h
+ .lane
+ .authorize_approved(h.intent.clone(), scope("e"), &a, &g, 49)
+ .is_ok());
+}
+
+#[tokio::test]
+async fn catalog_change_makes_the_grant_stale() {
+ let h = harness().await;
+ let g = h.desk.issue(&h.intent, scope("c"), 100);
+ let provider = h.intent.provider.clone();
+ let changed = vec![
+ ToolDescriptor::new("t", ToolEffects::WORLD_MUTATION, Digest32::of(b"t")),
+ ToolDescriptor::new("u", ToolEffects::PURE, Digest32::of(b"u")),
+ ];
+ h.broker.replace_catalog(&provider, changed).await.unwrap();
+ let e = h
+ .lane
+ .authorize_approved(h.intent.clone(), scope("c"), &EffectClassAuthority, &g, 1)
+ .unwrap_err();
+ assert!(matches!(e, AuthorityOutcome::Denied(_)));
+ assert_eq!(h.calls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn deny_and_contain_stay_refused_and_keep_the_grant() {
+ let h = harness().await;
+ let g = h.desk.issue(&h.intent, scope("d"), 100);
+ let deny = Fixed(AuthorityDecision::Deny("no".into()));
+ let e = h
+ .lane
+ .authorize_and_execute_approved(h.intent.clone(), scope("d"), &deny, &g, 1)
+ .await
+ .unwrap_err();
+ assert_eq!(e, AuthorityOutcome::Denied("no".into()));
+ let contain = Fixed(AuthorityDecision::Contain("box".into()));
+ let e = h
+ .lane
+ .authorize_approved(h.intent.clone(), scope("d"), &contain, &g, 1)
+ .unwrap_err();
+ assert_eq!(e, AuthorityOutcome::Contained("box".into()));
+ assert_eq!(h.calls.load(Ordering::SeqCst), 0);
+ // Grant untouched by the refusals.
+ assert!(h
+ .lane
+ .authorize_approved(h.intent.clone(), scope("d"), &EffectClassAuthority, &g, 1)
+ .is_ok());
+}
+
+#[tokio::test]
+async fn allow_does_not_spend_the_grant() {
+ let h = harness().await;
+ let g = h.desk.issue(&h.intent, scope("l"), 100);
+ let allow = Fixed(AuthorityDecision::Allow);
+ assert!(h
+ .lane
+ .authorize_approved(h.intent.clone(), scope("l"), &allow, &g, 1)
+ .is_ok());
+ assert!(h
+ .lane
+ .authorize_approved(h.intent.clone(), scope("l"), &EffectClassAuthority, &g, 1)
+ .is_ok());
+}
+
+#[tokio::test]
+async fn grant_from_another_broker_is_unknown() {
+ let h = harness().await;
+ let other = harness().await;
+ let g = other.desk.issue(&other.intent, scope("z"), 100);
+ let e = h
+ .lane
+ .authorize_approved(h.intent.clone(), scope("z"), &EffectClassAuthority, &g, 1)
+ .unwrap_err();
+ assert_eq!(approval(e), ApprovalError::Unknown);
+}
+
+#[tokio::test]
+async fn unapproved_request_is_still_pending() {
+ let h = harness().await;
+ let e = h
+ .lane
+ .authorize(h.intent.clone(), scope("n"), &EffectClassAuthority)
+ .unwrap_err();
+ assert!(matches!(e, AuthorityOutcome::Pending { .. }));
+}
```