interplane.Get Omega
Read in your language

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

GitHub aien-dev/aien-sovereign-core-mv#208 (code only)

closed derived 76806294c98e8b84 #208

Imported from GitHub aien-dev/aien-sovereign-core-mv#208 (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 0c1d249f2d119c7c2d726a2d252dc913e6185d28 · Head 6a2d38411e88d6b88e43a5ef1133330f034d6941

greptile-apps[bot] reviewed (COMMENTED) on 2026-10-05 03:30 UTC

aien-dev has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

Apply it

git checkout -b patch-76806294c98e8b84 0c1d249f2d119c7c2d726a2d252dc913e6185d28
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/76806294c98e8b84.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
208
6a2d38411e88d6b88e43a5ef1133330f034d6941
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":208,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/208","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:18Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/.crumb b/.crumb
index fbe9db86..0955e282 100644
--- a/.crumb
+++ b/.crumb
@@ -65,26 +65,26 @@
       "children": [
         {
           "digest": "e8767d4b3fd08dac77adeaabdeff6a58bca1cc927c7c89db68bd5d2c6b49fead",
-          "last_commit": "6554aac",
+          "last_commit": "91fba8f",
           "name": "scripts",
           "purpose": ""
         },
         {
           "digest": "ef1840de79311e5684993b0e0b66e0a9fce42a2d7966506201686ae5f8084a98",
-          "last_commit": "6554aac",
+          "last_commit": "8b5caed",
           "name": "skills",
           "purpose": ""
         }
       ],
       "children_root": "sha256:dfcfd805db0c30c667bc5682364bd3acb3383d494967dcae39f2420739723d7d",
-      "compiled_at": "2026-10-04T23:26:49Z",
+      "compiled_at": "2026-10-05T03:29:46Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:9cf477ea2340abc3b6f965013672ffeccd166342cc0ef91b37b7c90cb5d0064a",
+      "digest": "sha256:fdf5d407a9877d6809387c3ca7fe1614d7168c893ed649963fef9ed2417e3a41",
       "evidence_files": 20,
       "evidence_root": "sha256:1ef4526f6fe1ba0cee21a89c3313d37bf2e94e1aa2e9bd1a364225e52882d170",
       "files": 682,
-      "generated_at_commit": "6554aac7d81b04c91202e6bb0c90d258c8a07f04",
-      "source_tree": "sha256:d504bb7eb8876de92c3f930c975a388389f7bfba6261936c9879497d0f2426a4"
+      "generated_at_commit": "0c1d249f2d119c7c2d726a2d252dc913e6185d28",
+      "source_tree": "sha256:ac8216c1b39db4cb1b51653b10501c13a5b99be770556bb7c3357f398f38cc5b"
     }
   },
   "history": [],
diff --git a/crates/aien-mcp/src/approval.rs b/crates/aien-mcp/src/approval.rs
index ab8d2330..6faf72d9 100644
--- a/crates/aien-mcp/src/approval.rs
+++ b/crates/aien-mcp/src/approval.rs
@@ -11,6 +11,9 @@
 //! [`crate::EffectLane::authorize_and_execute_approved`] consults it for a spent grant that is
 //! bound to the same effect.
 //!
+//! A grant that has not been spent can be withdrawn with [`ApprovalDesk::revoke`]; after that
+//! it is refused with [`ApprovalError::Revoked`] and cannot be spent.
+//!
 //! 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};
@@ -30,6 +33,8 @@ pub enum ApprovalError {
     Consumed,
     /// `now` is at or past `expires_at`. Nothing is spent.
     Expired,
+    /// The approver withdrew the grant with [`ApprovalDesk::revoke`] before it was spent.
+    Revoked,
 }
 
 /// Proof that a host approver approved exactly one effect. Fields are private and only an
@@ -48,6 +53,7 @@ pub(crate) struct ApprovalRecord {
     pub(crate) winning_jnode: JNodeId,
     pub(crate) expires_at: u64,
     pub(crate) consumed: bool,
+    pub(crate) revoked: bool,
 }
 
 impl ApprovalRecord {
@@ -101,8 +107,23 @@ impl ApprovalDesk {
                 winning_jnode: scope.winning_jnode,
                 expires_at,
                 consumed: false,
+                revoked: false,
             },
         );
         ApprovalGrant { id }
     }
+
+    /// Withdraw a grant that has not been spent. Returns `true` if the grant is now dead.
+    /// A grant that was already spent (an effect may have been minted or run), or that this
+    /// desk never issued, returns `false` and nothing changes. Revoking twice is `true` both times.
+    pub fn revoke(&self, grant: &ApprovalGrant) -> bool {
+        let mut inner = self.broker.lock();
+        match inner.approvals.get_mut(&grant.id()) {
+            Some(record) if !record.consumed => {
+                record.revoked = true;
+                true
+            }
+            _ => false,
+        }
+    }
 }
diff --git a/crates/aien-mcp/src/broker.rs b/crates/aien-mcp/src/broker.rs
index 558a6370..dc00adac 100644
--- a/crates/aien-mcp/src/broker.rs
+++ b/crates/aien-mcp/src/broker.rs
@@ -3,7 +3,8 @@ use std::sync::{Arc, Mutex};
 use std::time::{Duration, SystemTime};
 
 use aien_capability::{
-    catalog_digest, speculation_safe, Digest32, EffectId, ProviderId, ToolDescriptor, ToolEffects,
+    catalog_digest, speculation_safe, Digest32, EffectId, JNodeId, ProviderId, ToolDescriptor,
+    ToolEffects, WorldId,
 };
 use serde_json::Value;
 
@@ -34,9 +35,24 @@ enum LedgerEntry {
     Uncertain,
 }
 
+/// Which effect owns a ledger key: the intent digest (provider, tool, arguments, catalog), the
+/// world and the winning J-node. The same four things an approval binds, so a key cannot be
+/// replayed as a receipt for a different effect.
+#[derive(Clone, Copy, PartialEq, Eq)]
+struct EffectIdentity {
+    intent: Digest32,
+    world_id: WorldId,
+    winning_jnode: JNodeId,
+}
+
+struct LedgerRow {
+    identity: EffectIdentity,
+    entry: LedgerEntry,
+}
+
 pub(crate) struct Inner {
     sessions: HashMap<String, McpSession>,
-    ledger: HashMap<EffectId, LedgerEntry>,
+    ledger: HashMap<EffectId, LedgerRow>,
     pub(crate) approvals: HashMap<Digest32, ApprovalRecord>,
     pub(crate) next_approval: u64,
 }
@@ -267,7 +283,7 @@ impl EffectLane {
     /// 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
+    /// scope, must be unspent, unrevoked 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(
@@ -390,7 +406,11 @@ impl EffectLane {
         if !record.consumed || !record.binds(intent, scope) {
             return None;
         }
-        match inner.ledger.get(&scope.idempotency_key)? {
+        let row = inner.ledger.get(&scope.idempotency_key)?;
+        if row.identity != identity(intent, scope.world_id, scope.winning_jnode) {
+            return Some(Err(Error::IdempotencyConflict));
+        }
+        match &row.entry {
             LedgerEntry::Completed(receipt) => Some(Ok(receipt.clone())),
             LedgerEntry::Uncertain => Some(Err(Error::ReconciliationRequired)),
             LedgerEntry::InFlight => Some(Err(Error::EffectInFlight)),
@@ -416,6 +436,9 @@ impl EffectLane {
         if record.consumed {
             return Err(ApprovalError::Consumed);
         }
+        if record.revoked {
+            return Err(ApprovalError::Revoked);
+        }
         if now >= record.expires_at {
             return Err(ApprovalError::Expired);
         }
@@ -431,11 +454,17 @@ impl EffectLane {
         let provider = effect.intent().provider.clone();
         let tool_name = effect.intent().tool_name.clone();
         let arguments = effect.intent().arguments.clone();
-        let intent_digest = effect.intent().capability_digest;
+        let staged_catalog = effect.intent().capability_digest;
+        let who = identity(effect.intent(), effect.world_id(), effect.winning_jnode());
         let wire = {
             let mut inner = self.broker.lock();
             if let Some(existing) = inner.ledger.get(&key) {
-                return match existing {
+                // A key names one effect. A request for another effect under the same key did not
+                // run and must not be answered with the first effect's receipt.
+                if existing.identity != who {
+                    return Err(Error::IdempotencyConflict);
+                }
+                return match &existing.entry {
                     LedgerEntry::Completed(receipt) => Ok(receipt.clone()),
                     LedgerEntry::Uncertain => Err(Error::ReconciliationRequired),
                     LedgerEntry::InFlight => Err(Error::EffectInFlight),
@@ -447,7 +476,7 @@ impl EffectLane {
                     .get(provider.as_str())
                     .ok_or_else(|| Error::NotAdmitted(provider.clone()))?;
                 if session.catalog_digest != effect.capability_digest()
-                    || intent_digest != effect.capability_digest()
+                    || staged_catalog != effect.capability_digest()
                 {
                     return Err(Error::StaleCapability);
                 }
@@ -459,7 +488,13 @@ impl EffectLane {
                 }
                 session.wire.clone()
             };
-            inner.ledger.insert(key, LedgerEntry::InFlight);
+            inner.ledger.insert(
+                key,
+                LedgerRow {
+                    identity: who,
+                    entry: LedgerEntry::InFlight,
+                },
+            );
             wire
         };
 
@@ -477,13 +512,23 @@ impl EffectLane {
                     capability_digest: effect.capability_digest(),
                     output,
                 };
-                inner
-                    .ledger
-                    .insert(key, LedgerEntry::Completed(receipt.clone()));
+                inner.ledger.insert(
+                    key,
+                    LedgerRow {
+                        identity: who,
+                        entry: LedgerEntry::Completed(receipt.clone()),
+                    },
+                );
                 Ok(receipt)
             }
             Ok(CallOutcome::Uncertain) | Err(_) => {
-                inner.ledger.insert(key, LedgerEntry::Uncertain);
+                inner.ledger.insert(
+                    key,
+                    LedgerRow {
+                        identity: who,
+                        entry: LedgerEntry::Uncertain,
+                    },
+                );
                 Err(Error::ReconciliationRequired)
             }
             Ok(CallOutcome::Rejected(reason)) => {
@@ -494,6 +539,14 @@ impl EffectLane {
     }
 }
 
+fn identity(intent: &EffectIntent, world_id: WorldId, winning_jnode: JNodeId) -> EffectIdentity {
+    EffectIdentity {
+        intent: intent_digest(intent),
+        world_id,
+        winning_jnode,
+    }
+}
+
 fn find_tool<'a>(session: &'a McpSession, name: &str) -> Option<&'a ToolDescriptor> {
     session.tools.iter().find(|tool| tool.name() == name)
 }
diff --git a/crates/aien-mcp/src/error.rs b/crates/aien-mcp/src/error.rs
index c9a08e9b..8d7ee694 100644
--- a/crates/aien-mcp/src/error.rs
+++ b/crates/aien-mcp/src/error.rs
@@ -19,6 +19,8 @@ pub enum Error {
     ReconciliationRequired,
     #[error("effect is already in flight")]
     EffectInFlight,
+    #[error("idempotency key already belongs to a different effect")]
+    IdempotencyConflict,
     #[error("tool call rejected: {0}")]
     Rejected(String),
     #[error("tool `{0}` has no enrolled effect class")]
diff --git a/crates/aien-mcp/tests/binding.rs b/crates/aien-mcp/tests/binding.rs
new file mode 100644
index 00000000..0acc330f
--- /dev/null
+++ b/crates/aien-mcp/tests/binding.rs
@@ -0,0 +1,454 @@
+//! L3-AUTH negative controls: what an approval binds, what the ledger binds, and what a faulty
+//! provider can and cannot cause. Public API only. Every assertion that matters counts provider
+//! executions (`calls`), not return values.
+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, AuthorityOutcome, CallOutcome, EffectClassAuthority, EffectIntent,
+    EffectLane, EffectScope, Error, McpBroker, McpWire, SpeculativeLane,
+};
+use serde_json::{json, Value};
+
+fn scope(label: &str) -> EffectScope {
+    EffectScope {
+        world_id: WorldId(1),
+        winning_jnode: JNodeId(1),
+        idempotency_key: EffectId::from_label(label),
+    }
+}
+
+struct H {
+    broker: McpBroker,
+    lane: EffectLane,
+    desk: ApprovalDesk,
+    calls: Arc<AtomicUsize>,
+    provider: ProviderId,
+    digest: Digest32,
+}
+
+impl H {
+    fn intent(&self, tool: &str, arguments: Value) -> EffectIntent {
+        EffectIntent {
+            provider: self.provider.clone(),
+            tool_name: tool.into(),
+            arguments,
+            capability_digest: self.digest,
+        }
+    }
+}
+
+/// Provider with a write-class tool `w`, a second write-class tool `x`, and a local-ephemeral
+/// tool `e` (which `EffectClassAuthority` allows without approval). `wire` decides every call.
+async fn harness_with(wire: Arc<dyn McpWire>, calls: Arc<AtomicUsize>) -> H {
+    let broker = McpBroker::new();
+    let provider = ProviderId::new("p");
+    broker.admit(provider.clone(), wire).await.unwrap();
+    let digest = SpeculativeLane::new(broker.clone())
+        .discovery_snapshot(&provider)
+        .await
+        .unwrap()
+        .catalog_digest;
+    H {
+        lane: EffectLane::new(broker.clone()),
+        desk: ApprovalDesk::new(broker.clone()),
+        broker,
+        calls,
+        provider,
+        digest,
+    }
+}
+
+fn tools() -> Vec<ToolDescriptor> {
+    vec![
+        ToolDescriptor::new("w", ToolEffects::WORLD_MUTATION, Digest32::of(b"w")),
+        ToolDescriptor::new("x", ToolEffects::WORLD_MUTATION, Digest32::of(b"x")),
+        ToolDescriptor::new("e", ToolEffects::LOCAL_EPHEMERAL, Digest32::of(b"e")),
+    ]
+}
+
+async fn harness(outcome: CallOutcome) -> H {
+    let calls = Arc::new(AtomicUsize::new(0));
+    let c = calls.clone();
+    let wire = MemoryWire::new(tools(), move |_, _| {
+        c.fetch_add(1, Ordering::SeqCst);
+        outcome.clone()
+    });
+    harness_with(Arc::new(wire), calls).await
+}
+
+fn approval(e: AuthorityOutcome) -> ApprovalError {
+    match e {
+        AuthorityOutcome::Approval(a) => a,
+        other => panic!("expected Approval, got {other:?}"),
+    }
+}
+
+// ---- what a grant binds ----
+
+#[tokio::test]
+async fn grant_is_bound_to_the_winning_jnode() {
+    let h = harness(CallOutcome::Finished(json!({"ok": true}))).await;
+    let intent = h.intent("w", json!({"a": 1}));
+    let g = h.desk.issue(&intent, scope("j"), 100);
+    let mut other = scope("j");
+    other.winning_jnode = JNodeId(2);
+    let e = h
+        .lane
+        .authorize_approved(intent.clone(), other, &EffectClassAuthority, &g, 1)
+        .unwrap_err();
+    assert_eq!(approval(e), ApprovalError::Mismatch);
+    assert_eq!(h.calls.load(Ordering::SeqCst), 0);
+    // Not burned: the named effect still runs, once.
+    let r = h
+        .lane
+        .authorize_and_execute_approved(intent, scope("j"), &EffectClassAuthority, &g, 1)
+        .await;
+    assert!(r.is_ok());
+    assert_eq!(h.calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn grant_is_bound_to_the_tool() {
+    let h = harness(CallOutcome::Finished(json!({"ok": true}))).await;
+    let g = h
+        .desk
+        .issue(&h.intent("w", json!({"a": 1})), scope("t"), 100);
+    // Same arguments, same key, same catalog, other tool of the same effect class.
+    let e = h
+        .lane
+        .authorize_and_execute_approved(
+            h.intent("x", json!({"a": 1})),
+            scope("t"),
+            &EffectClassAuthority,
+            &g,
+            1,
+        )
+        .await
+        .unwrap_err();
+    assert_eq!(approval(e), ApprovalError::Mismatch);
+    assert_eq!(h.calls.load(Ordering::SeqCst), 0);
+}
+
+// ---- single use under concurrency ----
+
+#[tokio::test]
+async fn one_grant_spent_from_many_threads_mints_exactly_once() {
+    let h = harness(CallOutcome::Finished(json!({"ok": true}))).await;
+    let intent = h.intent("w", json!({"a": 1}));
+    let g = h.desk.issue(&intent, scope("race"), 100);
+    let minted = AtomicUsize::new(0);
+    let refused = AtomicUsize::new(0);
+    std::thread::scope(|s| {
+        for _ in 0..16 {
+            s.spawn(|| {
+                match h.lane.authorize_approved(
+                    intent.clone(),
+                    scope("race"),
+                    &EffectClassAuthority,
+                    &g,
+                    1,
+                ) {
+                    Ok(_) => minted.fetch_add(1, Ordering::SeqCst),
+                    Err(AuthorityOutcome::Approval(ApprovalError::Consumed)) => {
+                        refused.fetch_add(1, Ordering::SeqCst)
+                    }
+                    Err(other) => panic!("unexpected {other:?}"),
+                };
+            });
+        }
+    });
+    assert_eq!(minted.load(Ordering::SeqCst), 1);
+    assert_eq!(refused.load(Ordering::SeqCst), 15);
+}
+
+#[test]
+fn one_grant_executed_from_many_threads_reaches_the_provider_once() {
+    let rt = tokio::runtime::Builder::new_current_thread()
+        .build()
+        .unwrap();
+    let h = rt.block_on(harness(CallOutcome::Finished(json!({"ok": true}))));
+    let intent = h.intent("w", json!({"a": 1}));
+    let g = h.desk.issue(&intent, scope("race2"), 100);
+    let receipts = std::sync::Mutex::new(Vec::new());
+    std::thread::scope(|s| {
+        for _ in 0..16 {
+            s.spawn(|| {
+                let rt = tokio::runtime::Builder::new_current_thread()
+                    .build()
+                    .unwrap();
+                let r = rt.block_on(h.lane.authorize_and_execute_approved(
+                    intent.clone(),
+                    scope("race2"),
+                    &EffectClassAuthority,
+                    &g,
+                    1,
+                ));
+                if let Ok(rc) = r {
+                    receipts.lock().unwrap().push(rc);
+                }
+            });
+        }
+    });
+    assert_eq!(h.calls.load(Ordering::SeqCst), 1, "provider reached once");
+    // Every success is the one effect's receipt.
+    let receipts = receipts.into_inner().unwrap();
+    assert!(!receipts.is_empty());
+    assert!(receipts.windows(2).all(|w| w[0] == w[1]));
+}
+
+// ---- provider faults are never success ----
+
+struct Faulty {
+    calls: Arc<AtomicUsize>,
+}
+
+#[async_trait::async_trait]
+impl McpWire for Faulty {
+    async fn list_tools(&self) -> Result<Vec<ToolDescriptor>, Error> {
+        Ok(tools())
+    }
+    async fn call_tool(&self, _: &str, _: &Value) -> Result<CallOutcome, Error> {
+        self.calls.fetch_add(1, Ordering::SeqCst);
+        Err(Error::Transport("connection reset".into()))
+    }
+}
+
+#[tokio::test]
+async fn transport_error_is_uncertain_never_success_and_never_retried() {
+    let calls = Arc::new(AtomicUsize::new(0));
+    let h = harness_with(
+        Arc::new(Faulty {
+            calls: calls.clone(),
+        }),
+        calls.clone(),
+    )
+    .await;
+    let intent = h.intent("w", json!({"a": 1}));
+    let g = h.desk.issue(&intent, scope("f"), 100);
+    let first = h
+        .lane
+        .authorize_and_execute_approved(intent.clone(), scope("f"), &EffectClassAuthority, &g, 1)
+        .await
+        .unwrap_err();
+    assert_eq!(
+        first,
+        AuthorityOutcome::Execution(Error::ReconciliationRequired)
+    );
+    // The same effect again (same grant: replay path) and a fresh grant (same key): both are told
+    // to reconcile, and the provider is not touched a second time.
+    let again = h
+        .lane
+        .authorize_and_execute_approved(intent.clone(), scope("f"), &EffectClassAuthority, &g, 1)
+        .await
+        .unwrap_err();
+    assert_eq!(
+        again,
+        AuthorityOutcome::Execution(Error::ReconciliationRequired)
+    );
+    let g2 = h.desk.issue(&intent, scope("f"), 100);
+    let fresh = h
+        .lane
+        .authorize_and_execute_approved(intent, scope("f"), &EffectClassAuthority, &g2, 1)
+        .await
+        .unwrap_err();
+    assert_eq!(
+        fresh,
+        AuthorityOutcome::Execution(Error::ReconciliationRequired)
+    );
+    assert_eq!(calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn provider_rejection_is_an_error_and_the_spent_grant_stays_spent() {
+    let h = harness(CallOutcome::Rejected("no such directory".into())).await;
+    let intent = h.intent("w", json!({"a": 1}));
+    let g = h.desk.issue(&intent, scope("rj"), 100);
+    let e = h
+        .lane
+        .authorize_and_execute_approved(intent.clone(), scope("rj"), &EffectClassAuthority, &g, 1)
+        .await
+        .unwrap_err();
+    assert_eq!(
+        e,
+        AuthorityOutcome::Execution(Error::Rejected("no such directory".into()))
+    );
+    // One approval bought one attempt. The same grant cannot buy a second.
+    let e = h
+        .lane
+        .authorize_and_execute_approved(intent, scope("rj"), &EffectClassAuthority, &g, 1)
+        .await
+        .unwrap_err();
+    assert_eq!(approval(e), ApprovalError::Consumed);
+    assert_eq!(h.calls.load(Ordering::SeqCst), 1);
+}
+
+// ---- the ledger binds the effect, not just the key ----
+
+#[tokio::test]
+async fn a_reused_idempotency_key_never_reports_success_for_a_different_effect() {
+    let h = harness(CallOutcome::Finished(json!({"done": true}))).await;
+    let a = EffectClassAuthority;
+    // `e` is allowed without approval, so this is the plain `authorize_and_execute` path.
+    let first = h
+        .lane
+        .authorize_and_execute(h.intent("e", json!({"n": 1})), scope("k"), &a)
+        .await
+        .unwrap();
+    assert_eq!(first.tool_name, "e");
+    assert_eq!(h.calls.load(Ordering::SeqCst), 1);
+    // A different request under the same key did not run, so it must not come back as a receipt.
+    let other = h
+        .lane
+        .authorize_and_execute(h.intent("e", json!({"n": 2})), scope("k"), &a)
+        .await;
+    assert!(
+        matches!(
+            other,
+            Err(AuthorityOutcome::Execution(Error::IdempotencyConflict))
+        ),
+        "{other:?}"
+    );
+    assert_eq!(h.calls.load(Ordering::SeqCst), 1, "second effect never ran");
+    // The identical request is still an ordinary replay.
+    let same = h
+        .lane
+        .authorize_and_execute(h.intent("e", json!({"n": 1})), scope("k"), &a)
+        .await
+        .unwrap();
+    assert_eq!(same, first);
+    assert_eq!(h.calls.load(Ordering::SeqCst), 1);
+    let _ = &h.broker;
+}
+
+#[tokio::test]
+async fn a_key_names_one_effect_in_one_world() {
+    let h = harness(CallOutcome::Finished(json!({"done": true}))).await;
+    let a = EffectClassAuthority;
+    let intent = h.intent("e", json!({"n": 1}));
+    h.lane
+        .authorize_and_execute(intent.clone(), scope("w1"), &a)
+        .await
+        .unwrap();
+    // Same effect and key, other world: not a replay, and no receipt that names world 1.
+    let mut other = scope("w1");
+    other.world_id = WorldId(2);
+    let r = h.lane.authorize_and_execute(intent, other, &a).await;
+    assert!(
+        matches!(
+            r,
+            Err(AuthorityOutcome::Execution(Error::IdempotencyConflict))
+        ),
+        "{r:?}"
+    );
+    assert_eq!(h.calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn an_approved_effect_cannot_borrow_the_receipt_of_an_earlier_effect_on_its_key() {
+    let h = harness(CallOutcome::Finished(json!({"done": true}))).await;
+    let a = EffectClassAuthority;
+    // Key `shared` is first used by an allowed effect.
+    h.lane
+        .authorize_and_execute(h.intent("e", json!({"n": 1})), scope("shared"), &a)
+        .await
+        .unwrap();
+    // A different, approval-class effect is then approved under the same key.
+    let write = h.intent("w", json!({"path": "x"}));
+    let g = h.desk.issue(&write, scope("shared"), 100);
+    let r = h
+        .lane
+        .authorize_and_execute_approved(write.clone(), scope("shared"), &a, &g, 1)
+        .await;
+    assert!(
+        matches!(
+            r,
+            Err(AuthorityOutcome::Execution(Error::IdempotencyConflict))
+        ),
+        "{r:?}"
+    );
+    assert_eq!(h.calls.load(Ordering::SeqCst), 1, "the write never ran");
+    // The grant was spent at mint and the conflict does not hand out a receipt on replay either.
+    let again = h
+        .lane
+        .authorize_and_execute_approved(write, scope("shared"), &a, &g, 1)
+        .await;
+    assert!(
+        matches!(
+            again,
+            Err(AuthorityOutcome::Execution(Error::IdempotencyConflict))
+        ),
+        "{again:?}"
+    );
+    assert_eq!(h.calls.load(Ordering::SeqCst), 1);
+}
+
+// ---- cancellation: a withdrawn grant is dead ----
+
+#[tokio::test]
+async fn a_revoked_grant_cannot_be_spent_and_runs_nothing() {
+    let h = harness(CallOutcome::Finished(json!({"ok": true}))).await;
+    let intent = h.intent("w", json!({"a": 1}));
+    let g = h.desk.issue(&intent, scope("rv"), 100);
+    assert!(h.desk.revoke(&g));
+    assert!(h.desk.revoke(&g), "revoking twice is still revoked");
+    let e = h
+        .lane
+        .authorize_approved(intent.clone(), scope("rv"), &EffectClassAuthority, &g, 1)
+        .unwrap_err();
+    assert_eq!(approval(e), ApprovalError::Revoked);
+    let e = h
+        .lane
+        .authorize_and_execute_approved(intent, scope("rv"), &EffectClassAuthority, &g, 1)
+        .await
+        .unwrap_err();
+    assert_eq!(approval(e), ApprovalError::Revoked);
+    assert_eq!(h.calls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn a_spent_or_foreign_grant_cannot_be_revoked() {
+    let h = harness(CallOutcome::Finished(json!({"ok": true}))).await;
+    let intent = h.intent("w", json!({"a": 1}));
+    let g = h.desk.issue(&intent, scope("sp"), 100);
+    let r = h
+        .lane
+        .authorize_and_execute_approved(intent.clone(), scope("sp"), &EffectClassAuthority, &g, 1)
+        .await
+        .unwrap();
+    // Too late: the effect ran. Revoke says so and the replay still returns the one receipt.
+    assert!(!h.desk.revoke(&g));
+    let again = h
+        .lane
+        .authorize_and_execute_approved(intent, scope("sp"), &EffectClassAuthority, &g, 1)
+        .await
+        .unwrap();
+    assert_eq!(r, again);
+    assert_eq!(h.calls.load(Ordering::SeqCst), 1);
+    // A grant from another desk is not this desk's to revoke.
+    let other = harness(CallOutcome::Finished(json!({}))).await;
+    let foreign = other
+        .desk
+        .issue(&other.intent("w", json!({})), scope("f"), 100);
+    assert!(!h.desk.revoke(&foreign));
+    assert!(other.desk.revoke(&foreign));
+}
+
+#[tokio::test]
+async fn revoking_one_grant_leaves_another_for_the_same_effect_usable() {
+    let h = harness(CallOutcome::Finished(json!({"ok": true}))).await;
+    let intent = h.intent("w", json!({"a": 1}));
+    let dead = h.desk.issue(&intent, scope("two"), 100);
+    let live = h.desk.issue(&intent, scope("two"), 100);
+    assert!(h.desk.revoke(&dead));
+    let r = h
+        .lane
+        .authorize_and_execute_approved(intent, scope("two"), &EffectClassAuthority, &live, 1)
+        .await;
+    assert!(r.is_ok());
+    assert_eq!(h.calls.load(Ordering::SeqCst), 1);
+}