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
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 95 on 2026-10-04 22:31 UTC
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9 " align="top"></a> 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.
<details><summary><strong>Artifacts</strong></summary><br />
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.
<a href="https://app.greptile.com/trex/runs/29202617 /artifacts?artifact=9085d17a -bcdd-4659-8cf5-e5c8e928d83c "> <picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewArtifactsDark.svg?v=4"> <source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewArtifacts.svg?v=4"> <img alt="View artifacts" src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewArtifacts.svg?v=4"> </picture></a>
</details>
<sub><a href="https://www.greptile.com/trex"> <img alt="T-Rex" src="https://greptile-static-assets.s3.amazonaws.com/trex/trex_green.svg " height="14" align="absmiddle"></a> Ran code and verified through T-Rex</sub>
<details><summary>Prompt To Fix With AI</summary>
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.
</details>
<a href="https://app.greptile.com/ide/claude-code?prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0APath%3A%20crates%2Faien-mcp%2Fsrc%2Fapproval.rs%0ALine%3A%2095%0A%0AComment%3A%0A**Approval%20records%20accumulate**%0A%0AIssuing%20a%20grant%20adds%20a%20record%20that%20remains%20after%20the%20grant%20is%20spent%20or%20expires.%20A%20long-running%20broker%20therefore%20uses%20more%20memory%20with%20each%20approval%2C%20including%20approvals%20that%20can%20no%20longer%20be%20spent.%20This%20is%20a%20non-blocking%20retention%20concern%3B%20add%20bounded%20cleanup%20without%20breaking%20valid%20receipt%20replays.%0A%0A---%0A%0AFor%20each%20issue%20above%2C%20determine%20whether%20it%20is%20valid%20and%20should%20be%20fixed.%20If%20so%2C%20fix%20it%20directly.&repo=aien-dev%2Faien-sovereign-core&pr=204&platform=github"> <picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/FixInClaudeDark.svg?v=7"> <source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/FixInClaude.svg?v=7"> <img alt="Fix in Claude Code" src="https://greptile-static-assets.s3.amazonaws.com/badges/FixInClaude.svg?v=7"> </picture></a>
greptile-apps[bot] reviewed (COMMENTED) on 2026-10-04 22:31 UTC
greptile-apps[bot] wrote on 2026-10-04 22:31 UTC
<h2><a href="https://app.greptile.com/api/retrigger?id=74510736 "> <picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/RetriggerDark.svg?v=2"> <source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"> <img alt="Retrigger" src="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2 " align="right"></picture></a>Confidence Score: 2/5</h2>
[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.
<h2><a href="https://app.greptile.com/ide/claude-code?prompt=%23%23%23%20Issue%201%0Acrates%2Faien-mcp%2Fsrc%2Fapproval.rs%3A91-94%0ATwo%20brokers%20issuing%20a%20grant%20for%20the%20same%20intent%20and%20key%20produce%20the%20same%20grant%20ID.%20Once%20broker%20B%20has%20issued%20its%20matching%20grant%2C%20presenting%20broker%20A's%20grant%20to%20B%20executes%20B's%20effect%20and%20consumes%20B's%20approval.%20Bind%20grant%20IDs%20to%20their%20issuing%20broker%20before%20merging.%0A%0A**How%20this%20was%20verified%3A**%20A%20grant%20issued%20by%20broker%20A%20executed%20broker%20B's%20tool%20after%20B%20issued%20a%20matching%20grant.%0A%0A%23%23%23%20Issue%202%0Acrates%2Faien-mcp%2Fsrc%2Fbroker.rs%3A379-380%0AA%20grant%20can%20be%20spent%20by%20minting%20an%20effect%20without%20executing%20it.%20If%20a%20different%20effect%20completes%20under%20the%20same%20idempotency%20key%2C%20replaying%20the%20approved%20request%20returns%20that%20effect's%20receipt.%20The%20approved%20effect%20never%20ran%2C%20yet%20its%20caller%20receives%20a%20success%20result.%20Verify%20the%20completed%20effect's%20identity%20before%20returning%20its%20receipt%3B%20this%20must%20be%20fixed%20before%20merging.%0A%0A%23%23%23%20Issue%203%0Acrates%2Faien-mcp%2Fsrc%2Fbroker.rs%3A358-361%0AAfter%20an%20approved%20effect%20completes%2C%20replay%20returns%20its%20old%20receipt%20even%20when%20the%20authority%20now%20says%20Deny%20or%20Contain%2C%20or%20the%20catalog%20has%20changed.%20The%20provider%20does%20not%20run%20again%2C%20but%20callers%20receive%20a%20success%20result%20where%20ordinary%20authorization%20reports%20a%20refusal.%20This%20non-blocking%20inconsistency%20makes%20the%20current%20request%20status%20misleading.%0A%0A%23%23%23%20Issue%204%0Acrates%2Faien-mcp%2Fsrc%2Fapproval.rs%3A95%0AIssuing%20a%20grant%20adds%20a%20record%20that%20remains%20after%20the%20grant%20is%20spent%20or%20expires.%20A%20long-running%20broker%20therefore%20uses%20more%20memory%20with%20each%20approval%2C%20including%20approvals%20that%20can%20no%20longer%20be%20spent.%20This%20is%20a%20non-blocking%20retention%20concern%3B%20add%20bounded%20cleanup%20without%20breaking%20valid%20receipt%20replays.%0A%0A%23%23%23%20Issue%205%0Acrates%2Faien-mcp%2Ftests%2Fapproval.rs%3A39%0AThe%20new%20helper%20is%20named%20%60harness%60%2C%20a%20word%20forbidden%20by%20the%20repository's%20Sovereign%20Voice%20directive.%20Rename%20the%20helper%20and%20its%20uses%20to%20satisfy%20this%20repository%20requirement%20before%20merging.%0A%0ANote%3A%20If%20this%20suggestion%20doesn't%20match%20your%20team's%20coding%20style%2C%20reply%20to%20this%20and%20let%20me%20know.%20I'll%20remember%20it%20for%20next%20time!%0A%0A---%0A%0AFor%20each%20issue%20above%2C%20determine%20whether%20it%20is%20valid%20and%20should%20be%20fixed.%20If%20so%2C%20fix%20it%20directly.&repo=aien-dev%2Faien-sovereign-core&pr=204&platform=github"> <picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/FixAllInClaudeDark.svg?v=7"> <source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/FixAllInClaude.svg?v=7"> <img alt="Fix All in Claude Code" src="https://greptile-static-assets.s3.amazonaws.com/badges/FixAllInClaude.svg?v=7 " align="right"></picture></a>Findings</h2>
<img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9 " align="top"> <img alt="Security" src="https://greptile-static-assets.s3.amazonaws.com/badges/Security.svg?v=2 " align="top"> Grants can cross brokers <a href="https://github.com/aien-dev/aien-sovereign-core/pull/204#discussion_r4179615352">▶ </a>
<img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9 " align="top"> Replay returns wrong receipt <a href="https://github.com/aien-dev/aien-sovereign-core/pull/204#discussion_r4179615357">▶ </a>
<img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9 " align="top"> Replay ignores current refusals <a href="https://github.com/aien-dev/aien-sovereign-core/pull/204#discussion_r4179615362">▶ </a>
<img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9 " align="top"> Approval records accumulate <a href="https://github.com/aien-dev/aien-sovereign-core/pull/204#discussion_r4179615369">▶ </a>
<img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9 " align="top"> Rename the test helper <a href="https://github.com/aien-dev/aien-sovereign-core/pull/204#discussion_r4179615376">▶ </a>
<details><summary>Fix with agent prompt</summary>
### 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.
</details>
<details open><summary>Summary</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.
</details>
<sub>Reviews (1) · Last reviewed commit: "feat(aien-mcp): single-use approval cons..." </sub>
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<String>),
- /// 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<String, McpSession>,
ledger: HashMap<EffectId, LedgerEntry>,
+ pub(crate) approvals: HashMap<Digest32, ApprovalRecord>,
+ 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<AuthorizedEffect<EffectIntent>, 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<AuthorizedEffect<EffectIntent>, 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<AuthorizedEffect<EffectIntent>, 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<EffectReceipt, AuthorityOutcome> {
+ 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<Result<EffectReceipt, Error>> {
+ 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<EffectIntent>,
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<dyn McpWire>) -> 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<AtomicUsize>,
+ 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 { .. }));
+}