Skip to main content

agentic_contract/
inventions.rs

1//! The 16 Contract Inventions — advanced governance capabilities.
2//!
3//! Organized into five categories:
4//!
5//! - **Visibility** (1-5): Policy Omniscience, Risk Prophecy, Approval Telepathy,
6//!   Obligation Clairvoyance, Violation Precognition
7//! - **Generation** (6-7): Contract Crystallization, Policy DNA
8//! - **Trust** (8-9): Trust Gradients, Collective Contracts
9//! - **Temporal** (10-11): Temporal Contracts, Contract Inheritance
10//! - **Advanced** (12-16): Smart Escalation, Violation Archaeology,
11//!   Contract Simulation, Federated Governance, Self-Healing Contracts
12
13use chrono::{DateTime, Utc};
14use serde::{Deserialize, Serialize};
15
16use crate::ContractId;
17
18// ─── VISIBILITY (1-5) ───────────────────────────────────────────────────────
19
20// ─── 1. Policy Omniscience ──────────────────────────────────────────────────
21
22/// Complete visibility into all applicable policies for an action.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct PolicyOmniscience {
25    /// Unique identifier.
26    pub id: ContractId,
27    /// The agent being queried about.
28    pub agent_id: String,
29    /// The context of the query.
30    pub context: String,
31    /// Actions explicitly allowed.
32    pub allowed_actions: Vec<PermissionEntry>,
33    /// Actions explicitly denied.
34    pub denied_actions: Vec<PermissionEntry>,
35    /// Actions requiring approval.
36    pub conditional_actions: Vec<PermissionEntry>,
37    /// Overall permission count.
38    pub total_permissions: u32,
39    /// When this query was made.
40    pub queried_at: DateTime<Utc>,
41}
42
43/// A single permission entry in an omniscience result.
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct PermissionEntry {
46    /// The action pattern.
47    pub action: String,
48    /// The policy granting/denying this.
49    pub policy_id: ContractId,
50    /// Policy label.
51    pub policy_label: String,
52    /// Explanation of why.
53    pub reason: String,
54    /// Scope of the permission.
55    pub scope: String,
56}
57
58// ─── 2. Risk Prophecy ───────────────────────────────────────────────────────
59
60/// Prediction of future risk budget usage.
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct RiskProphecy {
63    /// Unique identifier.
64    pub id: ContractId,
65    /// The agent being prophesied about.
66    pub agent_id: String,
67    /// Forecast window in seconds.
68    pub forecast_window_secs: i64,
69    /// Projected budget usage by limit.
70    pub projections: Vec<RiskProjection>,
71    /// Overall risk score (0.0-1.0).
72    pub overall_risk_score: f64,
73    /// Recommended adjustments.
74    pub recommendations: Vec<String>,
75    /// When this prophecy was made.
76    pub prophesied_at: DateTime<Utc>,
77}
78
79/// A projection for a specific risk limit.
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct RiskProjection {
82    /// The risk limit being projected.
83    pub limit_id: ContractId,
84    /// Risk limit label.
85    pub limit_label: String,
86    /// Current usage (0.0-1.0 fraction of limit).
87    pub current_usage: f64,
88    /// Projected usage at end of window.
89    pub projected_usage: f64,
90    /// Probability of exceeding limit (0.0-1.0).
91    pub exceed_probability: f64,
92    /// Estimated time until limit reached (seconds), if applicable.
93    pub time_until_limit_secs: Option<i64>,
94}
95
96// ─── 3. Approval Telepathy ──────────────────────────────────────────────────
97
98/// Prediction of approval likelihood.
99#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct ApprovalTelepathy {
101    /// Unique identifier.
102    pub id: ContractId,
103    /// The action being considered.
104    pub action: String,
105    /// Probability of approval (0.0-1.0).
106    pub approval_probability: f64,
107    /// Likely approvers.
108    pub likely_approvers: Vec<String>,
109    /// Estimated response time in seconds.
110    pub estimated_response_secs: i64,
111    /// Suggested modifications to increase probability.
112    pub suggestions: Vec<ApprovalSuggestion>,
113    /// Historical data informing this prediction.
114    pub historical_approval_rate: f64,
115    /// When this prediction was made.
116    pub predicted_at: DateTime<Utc>,
117}
118
119/// A suggestion to improve approval chances.
120#[derive(Debug, Clone, Serialize, Deserialize)]
121pub struct ApprovalSuggestion {
122    /// What to change.
123    pub modification: String,
124    /// New probability after this change.
125    pub new_probability: f64,
126    /// Effort required (low/medium/high).
127    pub effort: String,
128}
129
130// ─── 4. Obligation Clairvoyance ─────────────────────────────────────────────
131
132/// Visibility into future obligations and dependencies.
133#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct ObligationClairvoyance {
135    /// Unique identifier.
136    pub id: ContractId,
137    /// The agent being analyzed.
138    pub agent_id: String,
139    /// Projection window in seconds.
140    pub window_secs: i64,
141    /// Upcoming obligations sorted by deadline.
142    pub upcoming: Vec<ObligationForecast>,
143    /// Dependency conflicts detected.
144    pub conflicts: Vec<ObligationConflict>,
145    /// Optimal fulfillment schedule.
146    pub optimal_order: Vec<ContractId>,
147    /// When this projection was made.
148    pub projected_at: DateTime<Utc>,
149}
150
151/// A forecast for a single obligation.
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct ObligationForecast {
154    /// Obligation ID.
155    pub obligation_id: ContractId,
156    /// Obligation label.
157    pub label: String,
158    /// Deadline.
159    pub deadline: Option<DateTime<Utc>>,
160    /// Time remaining in seconds.
161    pub time_remaining_secs: Option<i64>,
162    /// Estimated fulfillment effort in minutes.
163    pub estimated_effort_minutes: u32,
164    /// Dependencies on other obligations.
165    pub depends_on: Vec<ContractId>,
166    /// Risk of missing deadline (0.0-1.0).
167    pub miss_risk: f64,
168}
169
170/// A conflict between obligations.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct ObligationConflict {
173    /// First obligation.
174    pub obligation_a: ContractId,
175    /// Second obligation.
176    pub obligation_b: ContractId,
177    /// Nature of the conflict.
178    pub conflict_type: String,
179    /// Suggested resolution.
180    pub resolution: String,
181}
182
183// ─── 5. Violation Precognition ──────────────────────────────────────────────
184
185/// Detection of potential violations before they occur.
186#[derive(Debug, Clone, Serialize, Deserialize)]
187pub struct ViolationPrecognition {
188    /// Unique identifier.
189    pub id: ContractId,
190    /// The planned action being analyzed.
191    pub planned_action: String,
192    /// Policies at risk of being violated.
193    pub at_risk_policies: Vec<PolicyRisk>,
194    /// Risk limits at risk of being exceeded.
195    pub at_risk_limits: Vec<LimitRisk>,
196    /// Safe alternative actions.
197    pub safe_alternatives: Vec<String>,
198    /// Overall violation probability (0.0-1.0).
199    pub violation_probability: f64,
200    /// When this analysis was made.
201    pub analyzed_at: DateTime<Utc>,
202}
203
204/// A policy at risk of being violated.
205#[derive(Debug, Clone, Serialize, Deserialize)]
206pub struct PolicyRisk {
207    /// The policy at risk.
208    pub policy_id: ContractId,
209    /// Policy label.
210    pub policy_label: String,
211    /// Probability of violation (0.0-1.0).
212    pub probability: f64,
213    /// What would trigger the violation.
214    pub trigger: String,
215}
216
217/// A risk limit at risk of being exceeded.
218#[derive(Debug, Clone, Serialize, Deserialize)]
219pub struct LimitRisk {
220    /// The risk limit.
221    pub limit_id: ContractId,
222    /// Limit label.
223    pub limit_label: String,
224    /// Current headroom before exceeding.
225    pub headroom: f64,
226    /// Projected usage from the planned action.
227    pub projected_usage: f64,
228}
229
230// ─── GENERATION (6-7) ───────────────────────────────────────────────────────
231
232// ─── 6. Contract Crystallization ────────────────────────────────────────────
233
234/// A crystallized contract generated from high-level intent.
235#[derive(Debug, Clone, Serialize, Deserialize)]
236pub struct CrystallizedContract {
237    /// Unique identifier.
238    pub id: ContractId,
239    /// The original intent string.
240    pub intent: String,
241    /// Generated policies.
242    pub policies: Vec<CrystallizedPolicy>,
243    /// Generated risk limits.
244    pub risk_limits: Vec<CrystallizedRiskLimit>,
245    /// Generated approval workflows.
246    pub approval_workflows: Vec<String>,
247    /// Edge cases identified.
248    pub edge_cases: Vec<String>,
249    /// Confidence in the crystallization (0.0-1.0).
250    pub confidence: f64,
251    /// When crystallized.
252    pub crystallized_at: DateTime<Utc>,
253}
254
255/// A policy generated during crystallization.
256#[derive(Debug, Clone, Serialize, Deserialize)]
257pub struct CrystallizedPolicy {
258    /// Suggested label.
259    pub label: String,
260    /// Suggested scope.
261    pub scope: String,
262    /// Suggested action.
263    pub action: String,
264    /// Why this policy was generated.
265    pub rationale: String,
266}
267
268/// A risk limit generated during crystallization.
269#[derive(Debug, Clone, Serialize, Deserialize)]
270pub struct CrystallizedRiskLimit {
271    /// Suggested label.
272    pub label: String,
273    /// Suggested maximum value.
274    pub max_value: f64,
275    /// Suggested limit type.
276    pub limit_type: String,
277    /// Why this limit was generated.
278    pub rationale: String,
279}
280
281// ─── 7. Policy DNA ──────────────────────────────────────────────────────────
282
283/// Genetic representation of a policy for evolution.
284#[derive(Debug, Clone, Serialize, Deserialize)]
285pub struct PolicyDna {
286    /// Unique identifier.
287    pub id: ContractId,
288    /// Source policy.
289    pub policy_id: ContractId,
290    /// DNA sequence (encoded traits).
291    pub genes: Vec<PolicyGene>,
292    /// Fitness score based on outcomes (0.0-1.0).
293    pub fitness: f64,
294    /// Generation number.
295    pub generation: u32,
296    /// Mutation history.
297    pub mutations: Vec<PolicyMutation>,
298    /// When this DNA was extracted.
299    pub extracted_at: DateTime<Utc>,
300}
301
302/// A gene in a policy's DNA.
303#[derive(Debug, Clone, Serialize, Deserialize)]
304pub struct PolicyGene {
305    /// Gene name (e.g., "scope_breadth", "restriction_level").
306    pub name: String,
307    /// Gene value (0.0-1.0).
308    pub value: f64,
309    /// Whether this gene is dominant.
310    pub dominant: bool,
311}
312
313/// A mutation in policy evolution.
314#[derive(Debug, Clone, Serialize, Deserialize)]
315pub struct PolicyMutation {
316    /// What changed.
317    pub gene_name: String,
318    /// Previous value.
319    pub old_value: f64,
320    /// New value.
321    pub new_value: f64,
322    /// Whether this mutation improved fitness.
323    pub beneficial: bool,
324}
325
326/// Result of evolving policies.
327#[derive(Debug, Clone, Serialize, Deserialize)]
328pub struct EvolutionResult {
329    /// Number of generations simulated.
330    pub generations: u32,
331    /// Best evolved policy set.
332    pub evolved_policies: Vec<PolicyDna>,
333    /// Final fitness score.
334    pub best_fitness: f64,
335    /// Improvements made.
336    pub improvements: Vec<String>,
337}
338
339// ─── TRUST (8-9) ────────────────────────────────────────────────────────────
340
341// ─── 8. Trust Gradients ─────────────────────────────────────────────────────
342
343/// A trust-augmented policy evaluation.
344#[derive(Debug, Clone, Serialize, Deserialize)]
345pub struct TrustGradient {
346    /// Unique identifier.
347    pub id: ContractId,
348    /// The agent being evaluated.
349    pub agent_id: String,
350    /// The action being evaluated.
351    pub action: String,
352    /// Trust factor (0.0-1.0).
353    pub trust_factor: f64,
354    /// Confidence in the trust assessment (0.0-1.0).
355    pub confidence: f64,
356    /// Monitoring level applied.
357    pub monitoring_level: MonitoringLevel,
358    /// Trust score threshold for auto-revocation.
359    pub auto_revoke_threshold: f64,
360    /// Factors contributing to the trust score.
361    pub contributing_factors: Vec<TrustFactor>,
362    /// When this evaluation was made.
363    pub evaluated_at: DateTime<Utc>,
364}
365
366/// Monitoring level based on trust.
367#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
368pub enum MonitoringLevel {
369    /// Minimal monitoring.
370    Minimal,
371    /// Standard monitoring.
372    Standard,
373    /// Enhanced monitoring.
374    Enhanced,
375    /// Full audit trail.
376    FullAudit,
377}
378
379/// A factor contributing to the trust score.
380#[derive(Debug, Clone, Serialize, Deserialize)]
381pub struct TrustFactor {
382    /// Factor name.
383    pub name: String,
384    /// Weight in trust calculation (0.0-1.0).
385    pub weight: f64,
386    /// Current score for this factor (0.0-1.0).
387    pub score: f64,
388    /// Trend (positive = improving).
389    pub trend: f64,
390}
391
392// ─── 9. Collective Contracts ────────────────────────────────────────────────
393
394/// A contract spanning multiple agents or organizations.
395#[derive(Debug, Clone, Serialize, Deserialize)]
396pub struct CollectiveContract {
397    /// Unique identifier.
398    pub id: ContractId,
399    /// Parties to this contract.
400    pub parties: Vec<ContractParty>,
401    /// Shared policies.
402    pub shared_policies: Vec<ContractId>,
403    /// Arbitration rules.
404    pub arbitration: ArbitrationRules,
405    /// Current status.
406    pub status: CollectiveStatus,
407    /// Signature count.
408    pub signatures: u32,
409    /// Required signatures.
410    pub required_signatures: u32,
411    /// When created.
412    pub created_at: DateTime<Utc>,
413}
414
415/// A party to a collective contract.
416#[derive(Debug, Clone, Serialize, Deserialize)]
417pub struct ContractParty {
418    /// Party identifier.
419    pub party_id: String,
420    /// Party name.
421    pub name: String,
422    /// Role in the contract.
423    pub role: String,
424    /// Whether this party has signed.
425    pub signed: bool,
426    /// When they signed (if they have).
427    pub signed_at: Option<DateTime<Utc>>,
428}
429
430/// Rules for arbitrating disputes in collective contracts.
431#[derive(Debug, Clone, Serialize, Deserialize)]
432pub struct ArbitrationRules {
433    /// Arbitration method.
434    pub method: ArbitrationMethod,
435    /// Timeout before escalation (seconds).
436    pub timeout_secs: i64,
437    /// Who arbitrates.
438    pub arbitrator: Option<String>,
439}
440
441/// Method of arbitration.
442#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
443pub enum ArbitrationMethod {
444    /// Simple majority vote.
445    MajorityVote,
446    /// Unanimous agreement.
447    Unanimous,
448    /// Designated third-party arbitrator.
449    ThirdParty,
450    /// Automated based on rules.
451    Automated,
452}
453
454/// Status of a collective contract.
455#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
456pub enum CollectiveStatus {
457    /// Awaiting all signatures.
458    Pending,
459    /// All signed, contract is active.
460    Active,
461    /// Contract has been terminated.
462    Terminated,
463    /// In dispute.
464    Disputed,
465}
466
467// ─── TEMPORAL (10-11) ───────────────────────────────────────────────────────
468
469// ─── 10. Temporal Contracts ─────────────────────────────────────────────────
470
471/// A contract that evolves over time.
472#[derive(Debug, Clone, Serialize, Deserialize)]
473pub struct TemporalContract {
474    /// Unique identifier.
475    pub id: ContractId,
476    /// Contract label.
477    pub label: String,
478    /// Initial governance level.
479    pub initial_level: GovernanceLevel,
480    /// Current governance level.
481    pub current_level: GovernanceLevel,
482    /// Planned transitions.
483    pub transitions: Vec<GovernanceTransition>,
484    /// Conditions that must be met for transitions.
485    pub transition_conditions: Vec<String>,
486    /// Performance history (0.0-1.0 per period).
487    pub performance_history: Vec<f64>,
488    /// When created.
489    pub created_at: DateTime<Utc>,
490}
491
492/// A governance level (how strict the contract is).
493#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
494pub enum GovernanceLevel {
495    /// Very restrictive.
496    Conservative,
497    /// Moderately restrictive.
498    Moderate,
499    /// Permissive.
500    Permissive,
501    /// Agent has full autonomy.
502    Autonomous,
503}
504
505/// A planned transition between governance levels.
506#[derive(Debug, Clone, Serialize, Deserialize)]
507pub struct GovernanceTransition {
508    /// From level.
509    pub from: GovernanceLevel,
510    /// To level.
511    pub to: GovernanceLevel,
512    /// When this transition should happen.
513    pub scheduled_at: DateTime<Utc>,
514    /// Whether the transition has occurred.
515    pub completed: bool,
516    /// Whether conditions were met.
517    pub conditions_met: bool,
518}
519
520// ─── 11. Contract Inheritance ───────────────────────────────────────────────
521
522/// A hierarchical contract relationship.
523#[derive(Debug, Clone, Serialize, Deserialize)]
524pub struct ContractInheritance {
525    /// Unique identifier.
526    pub id: ContractId,
527    /// Parent contract ID.
528    pub parent_id: ContractId,
529    /// Child contract ID.
530    pub child_id: ContractId,
531    /// What the child inherits.
532    pub inherited_policies: Vec<ContractId>,
533    /// What the child overrides.
534    pub overrides: Vec<InheritanceOverride>,
535    /// Whether parent changes propagate.
536    pub propagate_changes: bool,
537    /// When this relationship was created.
538    pub created_at: DateTime<Utc>,
539}
540
541/// An override in a child contract.
542#[derive(Debug, Clone, Serialize, Deserialize)]
543pub struct InheritanceOverride {
544    /// Policy being overridden.
545    pub policy_id: ContractId,
546    /// Override type.
547    pub override_type: OverrideType,
548    /// Description of the override.
549    pub description: String,
550}
551
552/// Type of inheritance override.
553#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
554pub enum OverrideType {
555    /// Allow an additional action.
556    AllowAdditional,
557    /// Restrict further.
558    RestrictFurther,
559    /// Modify parameters.
560    ModifyParameters,
561}
562
563// ─── ADVANCED (12-16) ───────────────────────────────────────────────────────
564
565// ─── 12. Smart Escalation ───────────────────────────────────────────────────
566
567/// AI-powered escalation routing result.
568#[derive(Debug, Clone, Serialize, Deserialize)]
569pub struct SmartEscalation {
570    /// Unique identifier.
571    pub id: ContractId,
572    /// The request being escalated.
573    pub request_description: String,
574    /// Request urgency (0.0-1.0).
575    pub urgency: f64,
576    /// Recommended approver.
577    pub recommended_approver: String,
578    /// Why this approver was chosen.
579    pub routing_reason: String,
580    /// Alternative approvers in order.
581    pub fallback_chain: Vec<EscalationTarget>,
582    /// Estimated response time in seconds.
583    pub estimated_response_secs: i64,
584    /// Confidence in routing (0.0-1.0).
585    pub confidence: f64,
586    /// When routed.
587    pub routed_at: DateTime<Utc>,
588}
589
590/// A target in an escalation chain.
591#[derive(Debug, Clone, Serialize, Deserialize)]
592pub struct EscalationTarget {
593    /// Approver ID.
594    pub approver_id: String,
595    /// Approver name.
596    pub name: String,
597    /// Estimated availability (0.0-1.0).
598    pub availability: f64,
599    /// Historical response time in seconds.
600    pub avg_response_secs: i64,
601    /// Historical approval rate (0.0-1.0).
602    pub approval_rate: f64,
603}
604
605// ─── 13. Violation Archaeology ──────────────────────────────────────────────
606
607/// Deep analysis of violation patterns and root causes.
608#[derive(Debug, Clone, Serialize, Deserialize)]
609pub struct ViolationArchaeology {
610    /// Unique identifier.
611    pub id: ContractId,
612    /// Agent being analyzed.
613    pub agent_id: String,
614    /// Analysis window in seconds.
615    pub window_secs: i64,
616    /// Violation clusters found.
617    pub clusters: Vec<ViolationCluster>,
618    /// Root cause hypotheses.
619    pub root_causes: Vec<RootCause>,
620    /// Remediation recommendations.
621    pub recommendations: Vec<Remediation>,
622    /// Policy adjustment suggestions.
623    pub policy_adjustments: Vec<PolicyAdjustment>,
624    /// When analyzed.
625    pub analyzed_at: DateTime<Utc>,
626}
627
628/// A cluster of related violations.
629#[derive(Debug, Clone, Serialize, Deserialize)]
630pub struct ViolationCluster {
631    /// Cluster label.
632    pub label: String,
633    /// Violation count in this cluster.
634    pub count: u32,
635    /// Common severity.
636    pub severity: String,
637    /// Common time pattern (e.g., "weekday mornings").
638    pub time_pattern: Option<String>,
639    /// Common context.
640    pub context_pattern: Option<String>,
641}
642
643/// A root cause hypothesis.
644#[derive(Debug, Clone, Serialize, Deserialize)]
645pub struct RootCause {
646    /// Hypothesis description.
647    pub hypothesis: String,
648    /// Confidence (0.0-1.0).
649    pub confidence: f64,
650    /// Supporting evidence.
651    pub evidence: Vec<String>,
652    /// Contributing factors.
653    pub factors: Vec<String>,
654}
655
656/// A remediation recommendation.
657#[derive(Debug, Clone, Serialize, Deserialize)]
658pub struct Remediation {
659    /// Action to take.
660    pub action: String,
661    /// Expected impact.
662    pub expected_impact: String,
663    /// Effort required (low/medium/high).
664    pub effort: String,
665    /// Priority (1 = highest).
666    pub priority: u32,
667}
668
669/// A suggested policy adjustment.
670#[derive(Debug, Clone, Serialize, Deserialize)]
671pub struct PolicyAdjustment {
672    /// Policy to adjust.
673    pub policy_id: ContractId,
674    /// Suggested change.
675    pub adjustment: String,
676    /// Reason for the adjustment.
677    pub reason: String,
678}
679
680// ─── 14. Contract Simulation ────────────────────────────────────────────────
681
682/// Results of simulating contract behavior.
683#[derive(Debug, Clone, Serialize, Deserialize)]
684pub struct ContractSimulation {
685    /// Unique identifier.
686    pub id: ContractId,
687    /// Number of scenarios simulated.
688    pub scenario_count: u32,
689    /// Approval rate across simulations (0.0-1.0).
690    pub approval_rate: f64,
691    /// Denial rate (0.0-1.0).
692    pub denial_rate: f64,
693    /// Risk limit breach rate (0.0-1.0).
694    pub risk_breach_rate: f64,
695    /// Potential deadlocks discovered.
696    pub deadlocks: Vec<SimulationDeadlock>,
697    /// Edge cases discovered.
698    pub edge_cases: Vec<SimulationEdgeCase>,
699    /// Overall contract health score (0.0-1.0).
700    pub health_score: f64,
701    /// When simulated.
702    pub simulated_at: DateTime<Utc>,
703}
704
705/// A deadlock found during simulation.
706#[derive(Debug, Clone, Serialize, Deserialize)]
707pub struct SimulationDeadlock {
708    /// Description of the deadlock.
709    pub description: String,
710    /// Policies involved.
711    pub policies_involved: Vec<ContractId>,
712    /// How to resolve it.
713    pub resolution: String,
714}
715
716/// An edge case found during simulation.
717#[derive(Debug, Clone, Serialize, Deserialize)]
718pub struct SimulationEdgeCase {
719    /// Description of the edge case.
720    pub description: String,
721    /// How the contract handles it currently.
722    pub current_behavior: String,
723    /// Suggested improvement.
724    pub suggested_fix: String,
725}
726
727// ─── 15. Federated Governance ───────────────────────────────────────────────
728
729/// Governance spanning organizational boundaries.
730#[derive(Debug, Clone, Serialize, Deserialize)]
731pub struct FederatedGovernance {
732    /// Unique identifier.
733    pub id: ContractId,
734    /// Federation name.
735    pub name: String,
736    /// Member organizations.
737    pub members: Vec<FederationMember>,
738    /// Shared policy set.
739    pub shared_policies: Vec<ContractId>,
740    /// Transparency level.
741    pub transparency: TransparencyLevel,
742    /// Status.
743    pub status: FederationStatus,
744    /// When created.
745    pub created_at: DateTime<Utc>,
746}
747
748/// A member of a federation.
749#[derive(Debug, Clone, Serialize, Deserialize)]
750pub struct FederationMember {
751    /// Organization ID.
752    pub org_id: String,
753    /// Organization name.
754    pub name: String,
755    /// Policies contributed.
756    pub contributed_policies: u32,
757    /// Trust level within federation (0.0-1.0).
758    pub trust_level: f64,
759    /// Whether this member has ratified.
760    pub ratified: bool,
761}
762
763/// Transparency level of a federation.
764#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
765pub enum TransparencyLevel {
766    /// All members see everything.
767    Full,
768    /// Members see summaries only.
769    Summary,
770    /// Members see only their own actions.
771    Minimal,
772}
773
774/// Status of a federation.
775#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
776pub enum FederationStatus {
777    /// Being formed.
778    Forming,
779    /// Active and operational.
780    Active,
781    /// Suspended.
782    Suspended,
783    /// Dissolved.
784    Dissolved,
785}
786
787// ─── 16. Self-Healing Contracts ─────────────────────────────────────────────
788
789/// A contract that automatically adapts to violations.
790#[derive(Debug, Clone, Serialize, Deserialize)]
791pub struct SelfHealingContract {
792    /// Unique identifier.
793    pub id: ContractId,
794    /// Base contract ID.
795    pub base_contract_id: ContractId,
796    /// Healing rules.
797    pub healing_rules: Vec<HealingRule>,
798    /// Healing events that have occurred.
799    pub healing_history: Vec<HealingEvent>,
800    /// Current adaptation level.
801    pub adaptation_level: AdaptationLevel,
802    /// Overall contract health (0.0-1.0).
803    pub health_score: f64,
804    /// When created.
805    pub created_at: DateTime<Utc>,
806}
807
808/// A rule for self-healing behavior.
809#[derive(Debug, Clone, Serialize, Deserialize)]
810pub struct HealingRule {
811    /// Trigger condition.
812    pub trigger: HealingTrigger,
813    /// Action to take.
814    pub action: HealingAction,
815    /// Cooldown before re-triggering (seconds).
816    pub cooldown_secs: i64,
817    /// Last triggered.
818    pub last_triggered: Option<DateTime<Utc>>,
819}
820
821/// What triggers a healing action.
822#[derive(Debug, Clone, Serialize, Deserialize)]
823pub enum HealingTrigger {
824    /// Repeated violations (threshold count).
825    RepeatedViolation { count: u32 },
826    /// Perfect record for a duration (seconds).
827    PerfectRecord { duration_secs: i64 },
828    /// Risk limit approaching threshold.
829    RiskApproaching { threshold: f64 },
830    /// Context change detected.
831    ContextChange,
832}
833
834/// What action to take for healing.
835#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
836pub enum HealingAction {
837    /// Tighten policy restrictions.
838    TightenPolicy,
839    /// Relax policy restrictions.
840    RelaxPolicy,
841    /// Add monitoring.
842    AddMonitoring,
843    /// Remove monitoring.
844    RemoveMonitoring,
845    /// Require additional approval.
846    AddApproval,
847    /// Remove approval requirement.
848    RemoveApproval,
849}
850
851/// A healing event that has occurred.
852#[derive(Debug, Clone, Serialize, Deserialize)]
853pub struct HealingEvent {
854    /// What triggered the healing.
855    pub trigger: String,
856    /// What action was taken.
857    pub action: String,
858    /// Policies affected.
859    pub affected_policies: Vec<ContractId>,
860    /// When the healing occurred.
861    pub healed_at: DateTime<Utc>,
862    /// Result of the healing.
863    pub result: String,
864}
865
866/// Current adaptation level.
867#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
868pub enum AdaptationLevel {
869    /// Original contract, no adaptations.
870    Original,
871    /// Minor adaptations applied.
872    MinorAdaptation,
873    /// Significant adaptations applied.
874    MajorAdaptation,
875    /// Substantially different from original.
876    FullyAdapted,
877}
878
879#[cfg(test)]
880mod tests {
881    use super::*;
882
883    #[test]
884    fn test_monitoring_level_equality() {
885        assert_eq!(MonitoringLevel::Standard, MonitoringLevel::Standard);
886        assert_ne!(MonitoringLevel::Minimal, MonitoringLevel::FullAudit);
887    }
888
889    #[test]
890    fn test_governance_level_equality() {
891        assert_eq!(GovernanceLevel::Conservative, GovernanceLevel::Conservative);
892        assert_ne!(GovernanceLevel::Moderate, GovernanceLevel::Autonomous);
893    }
894
895    #[test]
896    fn test_collective_status_equality() {
897        assert_eq!(CollectiveStatus::Active, CollectiveStatus::Active);
898    }
899
900    #[test]
901    fn test_override_type_equality() {
902        assert_eq!(OverrideType::AllowAdditional, OverrideType::AllowAdditional);
903    }
904
905    #[test]
906    fn test_arbitration_method_equality() {
907        assert_eq!(
908            ArbitrationMethod::MajorityVote,
909            ArbitrationMethod::MajorityVote
910        );
911    }
912
913    #[test]
914    fn test_healing_action_equality() {
915        assert_eq!(HealingAction::TightenPolicy, HealingAction::TightenPolicy);
916        assert_ne!(HealingAction::TightenPolicy, HealingAction::RelaxPolicy);
917    }
918
919    #[test]
920    fn test_adaptation_level_equality() {
921        assert_eq!(AdaptationLevel::Original, AdaptationLevel::Original);
922    }
923
924    #[test]
925    fn test_federation_status_equality() {
926        assert_eq!(FederationStatus::Active, FederationStatus::Active);
927    }
928
929    #[test]
930    fn test_transparency_level_equality() {
931        assert_eq!(TransparencyLevel::Full, TransparencyLevel::Full);
932    }
933}