higher-graphen-core 0.7.1

Shared primitive types and contracts for HigherGraphen.
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
use super::common::{Description, LifecycleStatus, ObjectRef};
use super::validation::require_some;
use crate::text::{normalize_required_text, normalize_required_text_vec};
use crate::{CoreError, Id, Provenance, Result, ReviewStatus};
use serde::{Deserialize, Serialize};

/// Scenario kind.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ScenarioKind {
    /// Hypothetical world.
    Hypothetical,
    /// Reachable world.
    Reachable,
    /// Blocked world.
    Blocked,
    /// Counterfactual world.
    Counterfactual,
    /// Planned world.
    Planned,
    /// Refuted world.
    Refuted,
    /// Accepted operational plan.
    AcceptedOperationalPlan,
}

/// Structures changed by a scenario.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ScenarioChanges {
    /// Added cells.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub added: Vec<Id>,
    /// Removed cells.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub removed: Vec<Id>,
    /// Modified morphisms.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub modified: Vec<Id>,
}

/// Reachability path from a base space.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Reachability {
    /// Source space.
    #[serde(rename = "ref")]
    pub reference: Id,
    /// Morphisms used to reach the scenario.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub via_morphisms: Vec<Id>,
}

/// Reviewable hypothetical, reachable, or counterfactual world.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Scenario {
    /// Scenario identifier.
    pub id: Id,
    /// Base space.
    pub base_space: Id,
    /// Scenario kind.
    pub scenario_kind: ScenarioKind,
    /// Assumption cells.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub assumptions: Vec<Id>,
    /// Changed structures.
    pub changed_structures: ScenarioChanges,
    /// Reachability relation from another space.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reachable_from: Option<Reachability>,
    /// Affected invariants.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub affected_invariants: Vec<Id>,
    /// Expected obstructions.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub expected_obstructions: Vec<Id>,
    /// Required witnesses.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required_witnesses: Vec<Id>,
    /// Valuations attached to the scenario.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub valuations: Vec<Id>,
    /// Scenario status.
    pub status: ScenarioStatus,
    /// Scenario provenance.
    pub provenance: Provenance,
    /// Review status.
    pub review_status: LifecycleStatus,
}

/// Scenario-specific status.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ScenarioStatus {
    /// Draft scenario.
    Draft,
    /// Candidate scenario.
    Candidate,
    /// Under review.
    UnderReview,
    /// Reachable from the base.
    Reachable,
    /// Blocked by obstructions.
    Blocked,
    /// Refuted.
    Refuted,
    /// Accepted for its declared use.
    Accepted,
}

impl Scenario {
    /// Validates conditions required before treating the scenario as accepted.
    pub fn validate_acceptance(&self) -> Result<()> {
        match self.scenario_kind {
            ScenarioKind::Hypothetical if self.status == ScenarioStatus::Accepted => {
                return Err(CoreError::malformed_field(
                    "scenario_kind",
                    "hypothetical scenario cannot be treated as accepted fact",
                ));
            }
            ScenarioKind::Reachable | ScenarioKind::AcceptedOperationalPlan => {
                require_some("reachable_from", self.reachable_from.as_ref())?;
            }
            _ => {}
        }
        if self.affected_invariants.is_empty() {
            return Err(CoreError::malformed_field(
                "affected_invariants",
                "accepted scenario requires invariant checks or affected invariant records",
            ));
        }
        if self.scenario_kind == ScenarioKind::AcceptedOperationalPlan
            && self.provenance.review_status != ReviewStatus::Accepted
        {
            return Err(CoreError::malformed_field(
                "provenance.review_status",
                "accepted operational plan requires policy/capability review",
            ));
        }
        Ok(())
    }
}

/// Operation governed by a capability.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CapabilityOperation {
    /// Read a target.
    Read,
    /// Propose a target.
    Propose,
    /// Modify a target.
    Modify,
    /// Accept a target.
    Accept,
    /// Reject a target.
    Reject,
    /// Project a target.
    Project,
    /// Execute a morphism.
    ExecuteMorphism,
    /// Merge an equivalence.
    MergeEquivalence,
    /// Create a scenario.
    CreateScenario,
    /// Approve a policy exception.
    ApprovePolicyException,
}

/// Review required by a capability.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RequiredReview {
    /// Policy requiring review.
    pub policy: Id,
    /// Reviewer actor.
    pub reviewer: Id,
}

/// Validity interval for a capability.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ValidityInterval {
    /// Start timestamp.
    pub starts_at: String,
    /// End timestamp.
    pub ends_at: String,
}

impl ValidityInterval {
    /// Validates the portable timestamp payloads.
    pub fn validate(&self) -> Result<()> {
        normalize_required_text("validity_interval.starts_at", &self.starts_at)?;
        normalize_required_text("validity_interval.ends_at", &self.ends_at)?;
        Ok(())
    }
}

/// Capability status.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CapabilityStatus {
    /// Active capability.
    Active,
    /// Temporarily suspended capability.
    Suspended,
    /// Expired capability.
    Expired,
    /// Revoked capability.
    Revoked,
    /// Candidate capability.
    Candidate,
}

/// Actor-specific ability to operate on a target in a context.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Capability {
    /// Capability identifier.
    pub id: Id,
    /// Actor cell.
    pub actor: Id,
    /// Operation granted.
    pub operation: CapabilityOperation,
    /// Target type.
    pub target_type: String,
    /// Target references.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub target_refs: Vec<ObjectRef>,
    /// Valid contexts.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub contexts: Vec<Id>,
    /// Preconditions.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub preconditions: Vec<Id>,
    /// Postconditions.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub postconditions: Vec<Id>,
    /// Forbidden effects.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub forbidden_effects: Vec<Description>,
    /// Required review.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required_review: Option<RequiredReview>,
    /// Validity interval.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub validity_interval: Option<ValidityInterval>,
    /// Capability provenance.
    pub provenance: Provenance,
    /// Capability status.
    pub status: CapabilityStatus,
}

impl Capability {
    /// Validates whether this capability may be used for a mutating operation.
    pub fn validate_active_use(&self) -> Result<()> {
        if self.status != CapabilityStatus::Active {
            return Err(CoreError::malformed_field(
                "status",
                "capability must be active before use",
            ));
        }
        normalize_required_text("target_type", &self.target_type)?;
        if let Some(validity_interval) = &self.validity_interval {
            validity_interval.validate()?;
        }
        if self.operation == CapabilityOperation::Accept
            && self.required_review.is_none()
            && self.provenance.review_status != ReviewStatus::Accepted
        {
            return Err(CoreError::malformed_field(
                "required_review",
                "accept operation requires explicit policy review",
            ));
        }
        Ok(())
    }
}

/// Policy kind.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PolicyKind {
    /// Permission policy.
    Permission,
    /// Prohibition policy.
    Prohibition,
    /// Obligation policy.
    Obligation,
    /// Review requirement policy.
    ReviewRequirement,
    /// Projection safety policy.
    ProjectionSafety,
    /// Candidate acceptance policy.
    CandidateAcceptance,
    /// Data boundary policy.
    DataBoundary,
    /// Escalation policy.
    Escalation,
}

/// Targets and operations a policy applies to.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PolicyApplicability {
    /// Target type names.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub target_types: Vec<String>,
    /// Context identifiers.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub contexts: Vec<Id>,
    /// Operation names.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub operations: Vec<String>,
}

impl PolicyApplicability {
    fn validate(&self) -> Result<()> {
        normalize_required_text_vec("target_types", &self.target_types)?;
        normalize_required_text_vec("operations", &self.operations)?;
        Ok(())
    }
}

/// Policy rule payload.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PolicyRule {
    /// Rule description.
    pub description: String,
    /// Constraint identifiers.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Id>,
}

impl PolicyRule {
    /// Creates a policy rule.
    pub fn new(description: impl Into<String>) -> Result<Self> {
        Ok(Self {
            description: normalize_required_text("policy.rule.description", description)?,
            constraints: Vec::new(),
        })
    }
}

/// Policy status.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PolicyStatus {
    /// Draft policy.
    Draft,
    /// Active policy.
    Active,
    /// Deprecated policy.
    Deprecated,
    /// Revoked policy.
    Revoked,
}

/// System-wide or context-bound rule.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Policy {
    /// Policy identifier.
    pub id: Id,
    /// Policy kind.
    pub policy_kind: PolicyKind,
    /// Applicability.
    pub applies_to: PolicyApplicability,
    /// Policy rule.
    pub rule: PolicyRule,
    /// Required witnesses.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required_witnesses: Vec<Id>,
    /// Required derivations.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required_derivations: Vec<Id>,
    /// Escalation path.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub escalation_path: Vec<Id>,
    /// Violation obstruction template id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub violation_obstruction_template: Option<Id>,
    /// Policy status.
    pub status: PolicyStatus,
    /// Policy provenance.
    pub provenance: Provenance,
    /// Policy review status.
    pub review_status: ReviewStatus,
}

impl Policy {
    /// Validates conditions required for an active policy.
    pub fn validate_active(&self) -> Result<()> {
        self.applies_to.validate()?;
        normalize_required_text("policy.rule.description", &self.rule.description)?;
        if self.status == PolicyStatus::Active && self.review_status != ReviewStatus::Accepted {
            return Err(CoreError::malformed_field(
                "review_status",
                "active policy requires accepted review status",
            ));
        }
        if self.status == PolicyStatus::Active
            && self.provenance.review_status != ReviewStatus::Accepted
        {
            return Err(CoreError::malformed_field(
                "provenance.review_status",
                "active policy provenance must be accepted",
            ));
        }
        Ok(())
    }
}