agentmesh 3.4.0

Public Preview — Rust SDK for the Agent Governance Toolkit (policy, trust, audit, identity)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! # Agent Governance Rust SDK
//!
//! Rust SDK for the [Agent Governance Toolkit](https://github.com/microsoft/agent-governance-toolkit)
//! — policy evaluation, trust scoring, hash-chain audit logging, and Ed25519 agent identity.
//!
//! ## Quick Start
//!
//! ```rust
//! use agentmesh::AgentMeshClient;
//!
//! let client = AgentMeshClient::new("my-agent")
//!     .expect("failed to create client");
//!
//! let result = client.execute_with_governance("data.read", None);
//! assert!(result.allowed);
//! ```

pub mod audit;
pub mod control_support;
#[allow(dead_code)]
pub mod governance_support;
pub mod identity;
pub mod identity_support;
pub mod integration_support;
pub mod lifecycle;
pub mod mcp;
pub mod policy;
pub mod reward_support;
pub mod rings;
pub mod sandbox;
pub mod trust;
pub mod trust_support;
pub mod types;

pub use audit::AuditLogger;
pub use control_support::{
    CircuitBreaker, CircuitState, ErrorBudget, HealthStatus, IncidentRecord, KillSwitch,
    KillSwitchDecision, KillSwitchEvent, KillSwitchReason, KillSwitchRegistry, KillSwitchScope,
    ObjectiveEvaluation, ServiceHealthReport, ServiceLevelObjective, SloEngine,
};
pub use governance_support::{
    annex_iv_to_json, annex_iv_to_markdown, load_cedar_into_engine, load_rego_into_engine,
    ActionRequest, AgentRiskProfile, AnnexIVDocument, AnnexIVSection, AuditChain, AuditSink,
    AuthorityDecision, AuthorityRequest, CedarDecision, CedarEvaluation, CedarEvaluator,
    ClassificationResult, ComplianceEngine, ComplianceFramework, ComplianceReport,
    ComplianceViolation, ConditionOperator, DataClassification, DefaultAuthorityResolver,
    DelegationInfo, EUAIActRiskClassifier, FederationDecision, FederationEngine, FederationStore,
    FileAuditSink, FileFederationStore, HashChainVerifier, InMemoryFederationStore, OPADecision,
    OPAEvaluation, OPAEvaluator, OrgPolicy, OrgPolicyDecision, OrgPolicyRule, OrgTrustAgreement,
    PolicyBackendDiagnostic, PolicyBackendTrace, PolicyCategory, PolicyDelegation,
    PolicyDiagnosticSeverity, PolicyEvaluator, PolicyRuleTrace, RiskLevel as GovernanceRiskLevel,
    ShadowMode, ShadowResult, SignedAuditEntry, TechnicalDocumentationExporter, TrustCondition,
    TrustDefaults, TrustInfo, TrustPolicy, TrustPolicyDecision, TrustRule,
};
pub use identity::{AgentIdentity, PublicIdentity};
pub use identity_support::{
    from_jwk, from_jwks, to_jwk, to_jwks, AgentDID, AgentNamespace, Credential, CredentialManager,
    CredentialStatus, DelegationLink, HumanSponsor, KeyRotationManager, KeyStore, MTLSConfig,
    MTLSIdentityVerifier, NamespaceManager, NamespaceRule, PKCS11KeyStore, RevocationEntry,
    RevocationList, RiskLevel, RiskScore as IdentityRiskScore, RiskScorer, RiskSeverity,
    RiskSignal, SPIFFEIdentity, SPIFFERegistry, ScopeChain, SoftwareKeyStore, SvidType,
    UserContext, SVID,
};
pub use integration_support::{
    DetectionBasis, DiscoveredAgent, DiscoveryEvidence, DiscoveryInventory,
    DiscoveryInventorySummary, DiscoveryReconciler, DiscoveryRecord, DiscoveryRiskAssessment,
    DiscoveryRiskLevel, DiscoveryRiskScorer, DiscoveryScanResult, DiscoveryScanner,
    DiscoveryStatus, DriftResult, ExecutionRequest, ExecutionResponse, FrameworkAdapter,
    FrameworkExecutionResult, FrameworkGovernanceAdapter, FrameworkKind, FrameworkResponse,
    GovernanceEvent, GovernanceEventType, GovernanceHook, GovernanceMiddleware, GovernancePattern,
    GovernancePolicy, PatternType, ProcessSnapshot, PromptDefenseEvaluator, PromptDefenseFinding,
    PromptDefenseReport, PromptRiskLevel, RegisteredAgent, ResponseGovernanceAssessment,
    ShadowAgent,
};
pub use lifecycle::{LifecycleEvent, LifecycleManager, LifecycleState};
pub use mcp::*;
pub use policy::{PolicyEngine, PolicyError};
pub use reward_support::{
    AgentRewardState, ContributionWeightedStrategy, DimensionType, DistributionResult,
    EqualSplitStrategy, HierarchicalStrategy, InteractionEdge, NetworkTrustEngine, ParticipantInfo,
    RewardAllocation, RewardConfig, RewardDimension, RewardDistributor, RewardEngine, RewardPool,
    RewardSignal, RewardStrategy, RewardTrustScore, TrustEvent, TrustWeightedStrategy,
};
pub use rings::{Ring, RingEnforcer};
pub use trust::{TrustConfig, TrustManager};
pub use trust_support::{
    CapabilityGrant, CapabilityRegistry, CapabilityScope, CardRegistry, HandshakeChallenge,
    HandshakeResponse, HandshakeResult, HandshakeTrustLevel, PeerInfo, ProtocolBridge, TrustBridge,
    TrustHandshake, TrustedAgentCard,
};
pub use types::{
    AuditEntry, AuditFilter, CandidateDecision, ConflictResolutionStrategy, GovernanceResult,
    PolicyDecision, PolicyScope, ResolutionResult, TrustScore, TrustTier,
};

use std::collections::HashMap;

/// Unified governance client combining identity, policy, trust, and audit.
///
/// This is the primary entry point for most users.
pub struct AgentMeshClient {
    pub identity: AgentIdentity,
    pub trust: TrustManager,
    pub policy: PolicyEngine,
    pub audit: AuditLogger,
}

/// Builder options for [`AgentMeshClient`].
#[derive(Default)]
pub struct ClientOptions {
    pub capabilities: Vec<String>,
    pub trust_config: Option<TrustConfig>,
    pub policy_yaml: Option<String>,
}

impl AgentMeshClient {
    /// Create a new client with default configuration.
    pub fn new(agent_id: &str) -> Result<Self, ClientError> {
        Self::with_options(agent_id, ClientOptions::default())
    }

    /// Create a new client with custom options.
    pub fn with_options(agent_id: &str, opts: ClientOptions) -> Result<Self, ClientError> {
        let identity =
            AgentIdentity::generate(agent_id, opts.capabilities).map_err(ClientError::Identity)?;

        let trust_config = opts.trust_config.unwrap_or_default();
        let trust = TrustManager::new(trust_config);

        let policy = PolicyEngine::new();
        if let Some(yaml) = &opts.policy_yaml {
            policy.load_from_yaml(yaml).map_err(ClientError::Policy)?;
        }

        Ok(Self {
            identity,
            trust,
            policy,
            audit: AuditLogger::new(),
        })
    }

    /// Run an action through the full governance pipeline:
    /// policy → audit → trust update.
    pub fn execute_with_governance(
        &self,
        action: &str,
        context: Option<&HashMap<String, serde_yaml::Value>>,
    ) -> GovernanceResult {
        let decision = self.policy.evaluate(action, context);
        let audit_entry = self.audit.log(&self.identity.did, action, decision.label());
        let trust_score = self.trust.get_trust_score(&self.identity.did);

        match &decision {
            PolicyDecision::Allow => self.trust.record_success(&self.identity.did),
            PolicyDecision::Deny(_) => self.trust.record_failure(&self.identity.did),
            _ => {}
        }

        GovernanceResult {
            allowed: decision.is_allowed(),
            decision,
            trust_score,
            audit_entry,
        }
    }
}

/// Errors returned by [`AgentMeshClient`] construction.
#[derive(Debug, thiserror::Error)]
pub enum ClientError {
    #[error("identity error: {0}")]
    Identity(identity::IdentityError),
    #[error("policy error: {0}")]
    Policy(policy::PolicyError),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_client_default_allows_everything() {
        let client = AgentMeshClient::new("test-agent").unwrap();
        let result = client.execute_with_governance("anything", None);
        assert!(result.allowed);
        assert_eq!(result.decision, PolicyDecision::Allow);
    }

    #[test]
    fn test_client_with_policy() {
        let yaml = r#"
version: "1.0"
agent: test
policies:
  - name: gate
    type: capability
    allowed_actions:
      - "data.read"
    denied_actions:
      - "shell:*"
"#;
        let opts = ClientOptions {
            policy_yaml: Some(yaml.to_string()),
            ..Default::default()
        };
        let client = AgentMeshClient::with_options("test", opts).unwrap();

        let r1 = client.execute_with_governance("data.read", None);
        assert!(r1.allowed);

        let r2 = client.execute_with_governance("shell:rm", None);
        assert!(!r2.allowed);
        assert!(matches!(r2.decision, PolicyDecision::Deny(_)));
    }

    #[test]
    fn test_governance_updates_trust() {
        let client = AgentMeshClient::new("trust-test").unwrap();
        let did = client.identity.did.clone();

        client.execute_with_governance("action1", None); // allow → +trust
        client.execute_with_governance("action2", None); // allow → +trust
        let score = client.trust.get_trust_score(&did);
        assert!(score.score > 500);
    }

    #[test]
    fn test_governance_creates_audit_chain() {
        let client = AgentMeshClient::new("audit-test").unwrap();
        client.execute_with_governance("a", None);
        client.execute_with_governance("b", None);
        client.execute_with_governance("c", None);
        assert!(client.audit.verify());
        assert_eq!(client.audit.entries().len(), 3);
    }

    #[test]
    fn test_client_with_custom_trust_config() {
        let opts = ClientOptions {
            trust_config: Some(TrustConfig {
                initial_score: 800,
                threshold: 700,
                reward: 20,
                penalty: 100,
                persist_path: None,
                decay_rate: 0.95,
            }),
            ..Default::default()
        };
        let client = AgentMeshClient::with_options("custom-trust", opts).unwrap();
        let score = client.trust.get_trust_score(&client.identity.did);
        assert_eq!(score.score, 800);
        assert_eq!(score.tier, TrustTier::Trusted);
    }

    #[test]
    fn test_client_with_capabilities() {
        let opts = ClientOptions {
            capabilities: vec!["data.read".to_string(), "data.write".to_string()],
            ..Default::default()
        };
        let client = AgentMeshClient::with_options("cap-agent", opts).unwrap();
        assert_eq!(
            client.identity.capabilities,
            vec!["data.read", "data.write"]
        );
    }

    #[test]
    fn test_client_with_invalid_yaml_returns_error() {
        let opts = ClientOptions {
            policy_yaml: Some("not: valid: yaml: {{{{".to_string()),
            ..Default::default()
        };
        let result = AgentMeshClient::with_options("bad-yaml", opts);
        assert!(result.is_err());
        match result {
            Err(ClientError::Policy(_)) => {}
            other => panic!("expected ClientError::Policy, got {:?}", other.err()),
        }
    }

    #[test]
    fn test_multiple_governance_executions_build_audit_chain() {
        let client = AgentMeshClient::new("chain-agent").unwrap();
        for i in 0..5 {
            client.execute_with_governance(&format!("action.{}", i), None);
        }
        let entries = client.audit.entries();
        assert_eq!(entries.len(), 5);
        for i in 0..5 {
            assert_eq!(entries[i].seq, i as u64);
        }
        // Each entry's prev_hash links to the previous entry's hash
        for i in 1..5 {
            assert_eq!(entries[i].previous_hash, entries[i - 1].hash);
        }
        assert!(client.audit.verify());
    }

    #[test]
    fn test_governance_with_denied_action_decreases_trust() {
        let yaml = r#"
version: "1.0"
agent: test
policies:
  - name: gate
    type: capability
    denied_actions:
      - "dangerous.*"
"#;
        let opts = ClientOptions {
            policy_yaml: Some(yaml.to_string()),
            ..Default::default()
        };
        let client = AgentMeshClient::with_options("deny-trust", opts).unwrap();
        let did = client.identity.did.clone();
        let initial = client.trust.get_trust_score(&did).score;
        client.execute_with_governance("dangerous.action", None);
        let after = client.trust.get_trust_score(&did).score;
        assert!(after < initial);
    }

    #[test]
    fn test_governance_with_approval_required_action() {
        let yaml = r#"
version: "1.0"
agent: test
policies:
  - name: deploy-gate
    type: approval
    actions:
      - "deploy.*"
    min_approvals: 3
"#;
        let opts = ClientOptions {
            policy_yaml: Some(yaml.to_string()),
            ..Default::default()
        };
        let client = AgentMeshClient::with_options("approval-test", opts).unwrap();
        let result = client.execute_with_governance("deploy.prod", None);
        assert!(!result.allowed);
        assert!(matches!(
            result.decision,
            PolicyDecision::RequiresApproval(_)
        ));
    }

    #[test]
    fn test_approval_required_action_preserves_trust_and_audits_label() {
        let yaml = r#"
version: "1.0"
agent: test
policies:
  - name: deploy-gate
    type: approval
    actions:
      - "deploy.*"
    min_approvals: 2
"#;
        let opts = ClientOptions {
            policy_yaml: Some(yaml.to_string()),
            ..Default::default()
        };
        let client = AgentMeshClient::with_options("approval-audit", opts).unwrap();
        let did = client.identity.did.clone();
        let before = client.trust.get_trust_score(&did).score;

        let result = client.execute_with_governance("deploy.production", None);
        let after = client.trust.get_trust_score(&did).score;

        assert!(!result.allowed);
        assert!(matches!(
            result.decision,
            PolicyDecision::RequiresApproval(_)
        ));
        assert_eq!(result.audit_entry.decision, "requires_approval");
        assert_eq!(after, before);
    }

    #[test]
    fn test_governance_with_rate_limited_action() {
        let yaml = r#"
version: "1.0"
agent: test
policies:
  - name: rate-gate
    type: rate_limit
    actions:
      - "api.*"
    max_calls: 2
    window: "60s"
"#;
        let opts = ClientOptions {
            policy_yaml: Some(yaml.to_string()),
            ..Default::default()
        };
        let client = AgentMeshClient::with_options("rate-test", opts).unwrap();
        let r1 = client.execute_with_governance("api.call", None);
        assert!(r1.allowed);
        let r2 = client.execute_with_governance("api.call", None);
        assert!(r2.allowed);
        let r3 = client.execute_with_governance("api.call", None);
        assert!(!r3.allowed);
        assert!(matches!(r3.decision, PolicyDecision::RateLimited { .. }));
    }

    #[test]
    fn test_client_identity_did_is_correct() {
        let client = AgentMeshClient::new("my-agent-42").unwrap();
        assert_eq!(client.identity.did, "did:agentmesh:my-agent-42");
    }

    #[test]
    fn test_audit_chain_integrity_after_mixed_allow_deny() {
        let yaml = r#"
version: "1.0"
agent: test
policies:
  - name: gate
    type: capability
    allowed_actions:
      - "safe.*"
    denied_actions:
      - "bad.*"
"#;
        let opts = ClientOptions {
            policy_yaml: Some(yaml.to_string()),
            ..Default::default()
        };
        let client = AgentMeshClient::with_options("mixed-test", opts).unwrap();
        let r1 = client.execute_with_governance("safe.read", None);
        assert!(r1.allowed);
        let r2 = client.execute_with_governance("bad.delete", None);
        assert!(!r2.allowed);
        let r3 = client.execute_with_governance("safe.write", None);
        assert!(r3.allowed);

        assert!(client.audit.verify());
        assert_eq!(client.audit.entries().len(), 3);

        let entries = client.audit.entries();
        assert_eq!(entries[0].decision, "allow");
        assert_eq!(entries[1].decision, "deny");
        assert_eq!(entries[2].decision, "allow");
    }
}