diff --git a/adapters/aien/Cargo.lock b/adapters/aien/Cargo.lock index 65a1f56..555c99d 100644 --- a/adapters/aien/Cargo.lock +++ b/adapters/aien/Cargo.lock @@ -83,7 +83,7 @@ dependencies = [ [[package]] name = "aien-capability" version = "0.1.0" -source = "git+https://github.com/aien-dev/aien-sovereign-core.git?rev=2a968bfc2770c012b4d53cfb1669f97594d2ff31#2a968bfc2770c012b4d53cfb1669f97594d2ff31" +source = "git+https://github.com/aien-dev/aien-sovereign-core.git?rev=6554aac7d81b04c91202e6bb0c90d258c8a07f04#6554aac7d81b04c91202e6bb0c90d258c8a07f04" dependencies = [ "sha2 0.10.9", ] @@ -134,7 +134,7 @@ dependencies = [ [[package]] name = "aien-mcp" version = "0.1.0" -source = "git+https://github.com/aien-dev/aien-sovereign-core.git?rev=2a968bfc2770c012b4d53cfb1669f97594d2ff31#2a968bfc2770c012b4d53cfb1669f97594d2ff31" +source = "git+https://github.com/aien-dev/aien-sovereign-core.git?rev=6554aac7d81b04c91202e6bb0c90d258c8a07f04#6554aac7d81b04c91202e6bb0c90d258c8a07f04" dependencies = [ "aien-capability", "async-trait", diff --git a/adapters/aien/Cargo.toml b/adapters/aien/Cargo.toml index 98d1864..aa8441f 100644 --- a/adapters/aien/Cargo.toml +++ b/adapters/aien/Cargo.toml @@ -21,9 +21,9 @@ interplane-crossveil = { path = "../../rust/crates/interplane-crossveil" } serde_json = "1" sha2 = "0.10" tokio = { version = "1", features = ["rt"] } -# Pinned AIEN sources: aien-dev/aien-sovereign-core PR #203 branch head (TEMPORARY; re-pin to the merge commit). -aien-capability = { git = "https://github.com/aien-dev/aien-sovereign-core.git", rev = "2a968bfc2770c012b4d53cfb1669f97594d2ff31" } -aien-mcp = { git = "https://github.com/aien-dev/aien-sovereign-core.git", rev = "2a968bfc2770c012b4d53cfb1669f97594d2ff31" } +# Pinned AIEN sources: aien-dev/aien-sovereign-core main at 6554aac (PR #204, single-use approvals). +aien-capability = { git = "https://github.com/aien-dev/aien-sovereign-core.git", rev = "6554aac7d81b04c91202e6bb0c90d258c8a07f04" } +aien-mcp = { git = "https://github.com/aien-dev/aien-sovereign-core.git", rev = "6554aac7d81b04c91202e6bb0c90d258c8a07f04" } # aegis-runtime cannot be a git dependency: its own Cargo.toml reaches a sibling checkout # (`../aien-protocols/crates/*`). Layout required (see README): next to this repository, # `interplane-audit/aegis-runtime` at f4e870953a466bb1cf68f1d88285929024cf1ba9 and diff --git a/adapters/aien/README.md b/adapters/aien/README.md index 0d43d47..d6ac9ad 100644 --- a/adapters/aien/README.md +++ b/adapters/aien/README.md @@ -7,15 +7,15 @@ authority machinery. License: AGPL-3.0-or-later (see `LICENSE`). Design: `docs/a could mistake for its own decision: no `AuthorizedEffect`, no `DoctrineDecision`, no `SafetyDecision`. `authorized` appears only when AIEN's own gate returned `Ok` for a read, or when AIEN's `EffectLane::authorize` minted an `AuthorizedEffect` after AIEN's `EffectClassAuthority` said Allow. -`requires_approval` and `denied` carry AIEN's reason. No approval id is invented (AIEN has none to -hand out) and nothing is consumed. Nothing under `rust/`, `spec/`, `python/` or +`requires_approval` and `denied` carry AIEN's reason. No approval id is invented: grants come only from AIEN's `ApprovalDesk` and are +spent only by AIEN. Nothing under `rust/`, `spec/`, `python/` or `conformance/` and no AIEN repository is modified. ## Pinned AIEN sources `aien-capability` and `aien-mcp` are git dependencies pinned to -`aien-dev/aien-sovereign-core@2a968bfc2770c012b4d53cfb1669f97594d2ff31` (main after PR #203 merged, -which adds the production authority seam). `aegis` (feature `aegis-gate`, on by default) cannot be a git dependency because +`aien-dev/aien-sovereign-core@6554aac7d81b04c91202e6bb0c90d258c8a07f04` (main after PR #204 merged, +which adds single-use approvals on top of the PR #203 authority seam). `aegis` (feature `aegis-gate`, on by default) cannot be a git dependency because `aegis-runtime`'s own `Cargo.toml` reaches a sibling checkout by relative path (`../aien-protocols/crates/*`). The build therefore expects this layout next to the INTERPLANE checkout: @@ -65,9 +65,17 @@ stage intent (a speculation-safe local-ephemeral tool cannot be staged by AIEN, | Deny (EXTERNAL_IRREVERSIBLE, unknown tool or bits, stale intent) | `denied` with AIEN's reason | no | | Contain | `denied` with AIEN's reason | no | -Not implemented: approval consumption. `requires_approval` is a pending handle (the intent digest); -aien-mcp has no approval store wired, so there is no way yet to approve and then execute. The -stock `write_file` and `bash_eval` descriptors are WORLD_MUTATION, so they stay pending. +Approvals (aien-mcp single-use grants, PR #204): `requires_approval` is a pending handle (the +intent digest). The host's approver calls `AienAuthority::issue_approval(req, expires_at)`, which +issues a grant through AIEN's own `ApprovalDesk` bound to that exact effect, then +`present_approval(request_id, grant, now)`; the next `decide` spends it through +`EffectLane::authorize_approved`. Refusals (`Unknown`, `Mismatch`, `Consumed`, `Expired`) come +back as `denied` with `approval refused: `. A spent grant presented again for the same +completed request is a replay: AIEN's ledger returns the existing receipt (via +`authorize_and_execute_approved`) and nothing re-executes. Limit: the interplane `Pipeline` has no +field that carries a grant, so grants are presented on the adapter, not on the wire, and the tests +drive `decide`/`execute` directly. The stock `write_file` and `bash_eval` descriptors are +WORLD_MUTATION, so they stay pending until a grant is presented. `with_effects(name, bits)` re-declares a stock capability's `ToolEffects` (used by tests with a LOCAL_EPHEMERAL temp-dir write and an EXTERNAL_IRREVERSIBLE deny); AIEN's authority decides from the new bits. diff --git a/adapters/aien/src/lib.rs b/adapters/aien/src/lib.rs index febbaec..992203f 100644 --- a/adapters/aien/src/lib.rs +++ b/adapters/aien/src/lib.rs @@ -17,9 +17,9 @@ use aien_capability::{ }; use aien_mcp::memory::MemoryWire; use aien_mcp::{ - AuthorityOutcome, AuthorizedEffect, CallOutcome, EffectClassAuthority, EffectIntent, - EffectLane, EffectScope, Error as McpError, SessionManager, SpeculativeLane, - SpeculativeToolCall, + ApprovalDesk, ApprovalError, ApprovalGrant, AuthorityOutcome, AuthorizedEffect, CallOutcome, + EffectClassAuthority, EffectIntent, EffectLane, EffectReceipt, EffectScope, Error as McpError, + SessionManager, SpeculativeLane, SpeculativeToolCall, }; use interplane_core::*; use interplane_crossaxis::MappingTable; @@ -118,6 +118,12 @@ pub struct AienAuthority { effect_lane: EffectLane, /// Effects AIEN minted in `decide`, waiting for `execute`. The adapter only holds them. authorized: HashMap>, + /// AIEN's approver handle for the enrolled broker. + desk: Option, + /// Grants presented per request id (with the host-supplied `now`), spent by `decide`. + grants: HashMap, + /// Receipts AIEN's ledger returned for a replayed request, handed back by `execute`. + replayed: HashMap, provider: ProviderId, runtime: tokio::runtime::Runtime, wire_calls: Arc, @@ -164,6 +170,9 @@ impl AienAuthority { lane: SpeculativeLane::new(aien_mcp::McpBroker::new()), effect_lane: EffectLane::new(aien_mcp::McpBroker::new()), authorized: HashMap::new(), + desk: None, + grants: HashMap::new(), + replayed: HashMap::new(), provider: ProviderId::new("interplane-reference"), runtime, wire_calls: Arc::new(AtomicUsize::new(0)), @@ -184,6 +193,7 @@ impl AienAuthority { .map_err(|e| e.to_string())?; self.lane = mgr.speculative_lane(); self.effect_lane = mgr.effect_lane(); + self.desk = Some(mgr.approval_desk()); Ok(()) } @@ -249,19 +259,12 @@ impl AienAuthority { } } - /// Effect path: stage, then ask AIEN (`EffectLane::authorize` with `EffectClassAuthority`). - /// The adapter translates the answer and never builds the authorized value itself. - fn decide_effect(&mut self, req: &CapabilityRequest, effects: ToolEffects) -> Decision { - if let Some(path) = req.arguments.get("path").and_then(Value::as_str) { - if let Err(why) = self.confine(path) { - return self.decision( - req, - DecisionKind::Denied, - Some(&why), - "adapter.workspace_confinement", - ); - } - } + /// Stage the intent for an effect request and build its scope. The idempotency key is the + /// request id, so one logical request is one effect identity (and one ledger entry). + fn stage( + &mut self, + req: &CapabilityRequest, + ) -> Result<(EffectIntent, EffectScope), Box> { let args = Value::Object(req.arguments.clone()); let staged = self.runtime.block_on(self.lane.stage_effect_intent( &self.provider, @@ -280,7 +283,12 @@ impl AienAuthority { }, Err(e) => { let r = e.to_string(); - return self.decision(req, DecisionKind::Denied, Some(&r), ENGINE_EFFECT); + return Err(Box::new(self.decision( + req, + DecisionKind::Denied, + Some(&r), + ENGINE_EFFECT, + ))); } }; let scope = EffectScope { @@ -288,11 +296,99 @@ impl AienAuthority { winning_jnode: JNodeId(1), idempotency_key: EffectId::from_label(req.request_id.as_str()), }; + Ok((intent, scope)) + } + + /// The approver's handle (AIEN's `ApprovalDesk`), once a workspace is enrolled. Hand it only + /// to the host's approval service; the adapter itself never issues a grant on its own. + pub fn approval_desk(&self) -> Option<&ApprovalDesk> { + self.desk.as_ref() + } + + /// Issue one single-use grant, through AIEN's desk, for exactly the effect `req` names + /// (intent, idempotency key, world, J-node). Valid while `now < expires_at`. + pub fn issue_approval( + &mut self, + req: &CapabilityRequest, + expires_at: u64, + ) -> Result { + let (intent, scope) = self + .stage(req) + .map_err(|d| d.reason.clone().unwrap_or_default())?; + let desk = self.desk.as_ref().ok_or(UNAVAILABLE)?; + Ok(desk.issue(&intent, scope, expires_at)) + } + + /// Present a grant for `request_id`; the next `decide` for that request spends it through + /// `EffectLane::authorize_approved`. `now` is host-supplied (aien-mcp reads no clock). + pub fn present_approval(&mut self, request_id: &str, grant: ApprovalGrant, now: u64) { + self.grants.insert(request_id.to_string(), (grant, now)); + } + + /// Effect path: stage, then ask AIEN (`EffectLane::authorize` with `EffectClassAuthority`, + /// or `authorize_approved` when a grant was presented for this request). + /// The adapter translates the answer and never builds the authorized value itself. + fn decide_effect(&mut self, req: &CapabilityRequest, effects: ToolEffects) -> Decision { + if let Some(path) = req.arguments.get("path").and_then(Value::as_str) { + if let Err(why) = self.confine(path) { + return self.decision( + req, + DecisionKind::Denied, + Some(&why), + "adapter.workspace_confinement", + ); + } + } + let (intent, scope) = match self.stage(req) { + Ok(x) => x, + Err(d) => return *d, + }; let mut values = vec![format!("effect_class={:?}", routing_class(effects))]; - match self - .effect_lane - .authorize(intent, scope, &EffectClassAuthority) - { + let grant = self.grants.get(req.request_id.as_str()).cloned(); + let outcome = match &grant { + Some((g, now)) => self.effect_lane.authorize_approved( + intent.clone(), + scope, + &EffectClassAuthority, + g, + *now, + ), + None => self + .effect_lane + .authorize(intent.clone(), scope, &EffectClassAuthority), + }; + // A spent grant presented again for the effect it was spent on is a replay of a finished + // request: AIEN's ledger returns the existing receipt and nothing is minted or run. + let outcome = match (outcome, &grant) { + (Err(AuthorityOutcome::Approval(ApprovalError::Consumed)), Some((g, now))) => { + match self + .runtime + .block_on(self.effect_lane.authorize_and_execute_approved( + intent, + scope, + &EffectClassAuthority, + g, + *now, + )) { + Ok(receipt) => { + self.replayed + .insert(req.request_id.as_str().to_string(), receipt); + values.push("replay=true".into()); + let mut d = + self.decision(req, DecisionKind::Authorized, None, ENGINE_EFFECT); + d.runtime_state = Some(RuntimeExtension { + vocabulary: "aien.effects".into(), + values, + extensions: Map::new(), + }); + return d; + } + Err(other) => Err(other), + } + } + (o, _) => o, + }; + match outcome { Ok(effect) => { self.authorized .insert(req.request_id.as_str().to_string(), effect); @@ -310,7 +406,7 @@ impl AienAuthority { }) => { values.push("staged=true".into()); values.push(format!("intent_digest={}", hex(&intent_digest))); - // AIEN has no approval record for this; none is invented or consumed here. + // No grant presented: none is invented or consumed here. let mut d = self.decision( req, DecisionKind::RequiresApproval, @@ -324,6 +420,10 @@ impl AienAuthority { }); d } + Err(AuthorityOutcome::Approval(e)) => { + let r = format!("approval refused: {e:?}"); + self.decision(req, DecisionKind::Denied, Some(&r), ENGINE_EFFECT) + } Err(AuthorityOutcome::Denied(r)) | Err(AuthorityOutcome::Contained(r)) => { self.decision(req, DecisionKind::Denied, Some(&r), ENGINE_EFFECT) } @@ -553,11 +653,21 @@ impl RuntimeAuthority for AienAuthority { } else { None }; - let mut r = if let Some(effect) = effect { - match self - .runtime - .block_on(self.effect_lane.execute_effect(effect)) - { + let replay = if decision.is_authorized() { + self.replayed.remove(rid) + } else { + None + }; + let receipt = match (effect, replay) { + (Some(effect), _) => Some( + self.runtime + .block_on(self.effect_lane.execute_effect(effect)), + ), + (None, Some(rc)) => Some(Ok(rc)), + (None, None) => None, + }; + let mut r = if let Some(receipt) = receipt { + match receipt { Ok(rc) => ToolResult::ok( rid, json!({"output": rc.output, "receipt": { diff --git a/adapters/aien/tests/approval.rs b/adapters/aien/tests/approval.rs new file mode 100644 index 0000000..b7fdc1c --- /dev/null +++ b/adapters/aien/tests/approval.rs @@ -0,0 +1,166 @@ +//! Single-use approvals (aien-mcp at 6554aac) through the adapter. The `Pipeline` has no way to +//! carry a grant, so these drive `AienAuthority` through the `RuntimeAuthority` trait directly, +//! the same two calls the pipeline makes (`decide`, then `execute`). +use interplane_adapter_aien::*; +use interplane_core::*; +use interplane_crossveil::{CallContext, RuntimeAuthority}; +use serde_json::json; + +fn req(id: &str, path: &str, content: &str) -> CapabilityRequest { + serde_json::from_value(json!({ + "kind": "capability_request", "request_id": id, "runtime": RUNTIME_ID, + "capability": "write_file", + "arguments": {"path": path, "content": content}, + "tool": {"namespace": null, "name": "write_file"}, + "mapping": {"table_version": "1", "rule_id": "passthrough:write_file", "passthrough": true} + })) + .unwrap() +} + +fn ctx() -> CallContext { + CallContext { + trace_id: "t".into(), + message_id: "m".into(), + parent_id: None, + model: Party::new("model", "m"), + session: None, + } +} + +/// decide + execute, as the pipeline does (execute only after an authorized decision). +fn run(rt: &mut AienAuthority, r: &CapabilityRequest) -> (Decision, Option) { + let d = rt.decide(r, &ctx()); + let res = d.is_authorized().then(|| rt.execute(r, &d, &ctx())); + (d, res) +} + +fn ws() -> tempfile::TempDir { + tempfile::tempdir().unwrap() +} + +#[test] +fn without_a_grant_it_stays_pending() { + let d = ws(); + let mut rt = AienAuthority::new(d.path()).unwrap(); + let (dec, res) = run(&mut rt, &req("r1", "a.txt", "x")); + assert_eq!(dec.decision, DecisionKind::RequiresApproval); + assert!(res.is_none()); + assert_eq!(rt.wire_calls(), 0); +} + +#[test] +fn approved_effect_executes_once() { + let d = ws(); + let mut rt = AienAuthority::new(d.path()).unwrap(); + let r = req("r1", "a.txt", "hello"); + let grant = rt.issue_approval(&r, 100).unwrap(); + rt.present_approval("r1", grant, 10); + let (dec, res) = run(&mut rt, &r); + assert!(dec.is_authorized(), "{dec:?}"); + let res = res.unwrap(); + assert_eq!(res.status, ResultStatus::Ok, "{res:?}"); + assert_eq!(res.data["receipt"]["tool_name"], "write_file"); + assert_eq!( + std::fs::read_to_string(d.path().join("a.txt")).unwrap(), + "hello" + ); + assert_eq!(rt.wire_calls(), 1); +} + +#[test] +fn spent_grant_used_again_is_consumed_and_runs_nothing() { + let d = ws(); + let mut rt = AienAuthority::new(d.path()).unwrap(); + let r = req("r1", "a.txt", "hello"); + let grant = rt.issue_approval(&r, 100).unwrap(); + rt.present_approval("r1", grant.clone(), 10); + // First decide spends the grant (AIEN mints the effect) but execute is never called, so the + // ledger has no receipt and a second decide is not a replay. + assert!(rt.decide(&r, &ctx()).is_authorized()); + let (dec, res) = run(&mut rt, &r); + assert_eq!(dec.decision, DecisionKind::Denied); + assert!( + dec.reason.as_deref().unwrap().contains("Consumed"), + "{dec:?}" + ); + assert!(res.is_none()); + // The same grant on another request id is a different effect: refused, nothing runs. + let other = req("r2", "a.txt", "hello"); + let (dec, _) = run_with(&mut rt, &other, grant); + assert_eq!(dec.decision, DecisionKind::Denied); + assert_eq!(rt.wire_calls(), 0, "no effect executed"); +} + +#[test] +fn replay_of_the_same_request_returns_the_existing_receipt() { + let d = ws(); + let mut rt = AienAuthority::new(d.path()).unwrap(); + let r = req("r1", "a.txt", "hello"); + let grant = rt.issue_approval(&r, 100).unwrap(); + rt.present_approval("r1", grant, 10); + let first = run(&mut rt, &r).1.unwrap(); + assert_eq!(first.status, ResultStatus::Ok); + // The file is removed so a second real write would be visible. + std::fs::remove_file(d.path().join("a.txt")).unwrap(); + let (dec, second) = run(&mut rt, &r); + assert!(dec.is_authorized(), "{dec:?}"); + let second = second.unwrap(); + assert_eq!(second.status, ResultStatus::Ok, "{second:?}"); + assert_eq!(second.data["receipt"], first.data["receipt"]); + assert_eq!(second.data["output"], first.data["output"]); + assert_eq!(rt.wire_calls(), 1, "replay did not touch the provider"); + assert!(!d.path().join("a.txt").exists()); +} + +#[test] +fn grant_for_a_different_effect_is_a_mismatch() { + let d = ws(); + let mut rt = AienAuthority::new(d.path()).unwrap(); + let approved = req("r1", "a.txt", "approved content"); + let grant = rt.issue_approval(&approved, 100).unwrap(); + // Same request id, different arguments: a different intent digest. + let other = req("r1", "a.txt", "something else"); + rt.present_approval("r1", grant.clone(), 10); + let (dec, res) = run(&mut rt, &other); + assert_eq!(dec.decision, DecisionKind::Denied); + assert!( + dec.reason.as_deref().unwrap().contains("Mismatch"), + "{dec:?}" + ); + assert!(res.is_none()); + assert_eq!(rt.wire_calls(), 0); + // Nothing was spent: the grant still works for the effect it names. + let (dec, res) = run_with(&mut rt, &approved, grant); + assert!(dec.is_authorized(), "{dec:?}"); + assert_eq!(res.unwrap().status, ResultStatus::Ok); + assert_eq!(rt.wire_calls(), 1); +} + +fn run_with( + rt: &mut AienAuthority, + r: &CapabilityRequest, + g: aien_mcp::ApprovalGrant, +) -> (Decision, Option) { + rt.present_approval(r.request_id.as_str(), g, 10); + run(rt, r) +} + +#[test] +fn expired_grant_is_refused() { + let d = ws(); + let mut rt = AienAuthority::new(d.path()).unwrap(); + let r = req("r1", "a.txt", "x"); + let grant = rt.issue_approval(&r, 50).unwrap(); + rt.present_approval("r1", grant.clone(), 50); // now >= expires_at + let (dec, res) = run(&mut rt, &r); + assert_eq!(dec.decision, DecisionKind::Denied); + assert!( + dec.reason.as_deref().unwrap().contains("Expired"), + "{dec:?}" + ); + assert!(res.is_none()); + assert_eq!(rt.wire_calls(), 0); + // Expiry does not spend the grant: presented in time, it works. + let (dec, _) = run_with(&mut rt, &r, grant); + assert!(dec.is_authorized(), "{dec:?}"); +}