crtx 0.1.1

CLI for the Cortex supervisory memory substrate.
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! ADR 0026 policy composition for the `cortex restore` surfaces.
//!
//! Doctrine: `docs/design/ADR_0026_consumer_punch_list.md` entries
//! #23-#27. The restore commands historically returned a bespoke
//! `RestoreDecision` enum that mapped directly to [`crate::exit::Exit`];
//! this module composes the same shape through the ADR 0026 outcome
//! lattice so the CLI emits the policy decision alongside the exit code.
//!
//! ## Stable rule ids
//!
//! Per ADR 0026 §5 every consumer must register stable rule ids at the
//! named call site. The constants below name the registered rules for the
//! restore surfaces. The exact strings are part of the JSON report
//! contract — operators search the audit pipeline for these ids.
//!
//! ### Semantic diff (#23)
//! - [`SEMANTIC_DIFF_RECOVERY_DRIFT_RULE_ID`]
//! - [`SEMANTIC_DIFF_SALIENCE_DRIFT_RULE_ID`]
//! - [`SEMANTIC_DIFF_CONTRADICTION_DRIFT_RULE_ID`]
//!
//! ### Preflight (#24)
//! - [`PREFLIGHT_MANIFEST_DIGEST_RULE_ID`]
//! - [`PREFLIGHT_SEMANTIC_DIFF_RULE_ID`]
//! - [`PREFLIGHT_PRODUCTION_ACTIVE_STORE_PLAN_RULE_ID`]
//!
//! ### Stage (#25)
//! - [`STAGE_DESTRUCTIVE_INTENT_RULE_ID`]
//! - [`STAGE_MANIFEST_DIGEST_RULE_ID`]
//! - [`STAGE_SEMANTIC_DIFF_RULE_ID`]
//!
//! ### Apply / apply-stage (#26)
//! - [`APPLY_STAGE_POST_RESTORE_ANCHOR_RULE_ID`]
//! - [`APPLY_STAGE_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID`]
//!
//! ### Recover-apply (#27)
//! - [`RECOVER_APPLY_RECOVERY_MANIFEST_DIGEST_RULE_ID`]
//! - [`RECOVER_APPLY_CURRENT_BACKUP_DIGEST_RULE_ID`]
//! - [`RECOVER_APPLY_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID`]

use cortex_core::{
    compose_policy_outcomes, BreakGlassAuthorization, BreakGlassReasonCode, BreakGlassScope,
    PolicyContribution, PolicyDecision, PolicyOutcome,
};
use cortex_store::semantic_diff::{
    RestoreDecision, SemanticChangeKind, SemanticDiff, SemanticSeverity,
};
use serde_json::json;

// --- semantic-diff (#23) ----------------------------------------------------

/// Recovery-drift contributor for `cortex restore semantic-diff` (ADR 0026 #23).
pub const SEMANTIC_DIFF_RECOVERY_DRIFT_RULE_ID: &str = "restore.semantic_diff.recovery_drift";
/// Salience-drift contributor for `cortex restore semantic-diff` (ADR 0026 #23).
pub const SEMANTIC_DIFF_SALIENCE_DRIFT_RULE_ID: &str = "restore.semantic_diff.salience_drift";
/// Contradiction-drift contributor for `cortex restore semantic-diff` (ADR 0026 #23).
pub const SEMANTIC_DIFF_CONTRADICTION_DRIFT_RULE_ID: &str =
    "restore.semantic_diff.contradiction_drift";

// --- preflight (#24) --------------------------------------------------------

/// Manifest-digest contributor for `cortex restore preflight` (ADR 0026 #24).
pub const PREFLIGHT_MANIFEST_DIGEST_RULE_ID: &str = "restore.preflight.manifest_digest";
/// Semantic-diff contributor for `cortex restore preflight` (ADR 0026 #24).
pub const PREFLIGHT_SEMANTIC_DIFF_RULE_ID: &str = "restore.preflight.semantic_diff";
/// Production-active-store-plan contributor for `cortex restore preflight`
/// (ADR 0026 #24). Always emits `Reject` until production gates land.
pub const PREFLIGHT_PRODUCTION_ACTIVE_STORE_PLAN_RULE_ID: &str =
    "restore.preflight.production_active_store_plan";

// --- stage (#25) ------------------------------------------------------------

/// Destructive-intent contributor for `cortex restore stage` (ADR 0026 #25).
pub const STAGE_DESTRUCTIVE_INTENT_RULE_ID: &str = "restore.stage.destructive_intent";
/// Manifest-digest contributor for `cortex restore stage` (ADR 0026 #25).
pub const STAGE_MANIFEST_DIGEST_RULE_ID: &str = "restore.stage.manifest_digest";
/// Semantic-diff contributor for `cortex restore stage` (ADR 0026 #25).
pub const STAGE_SEMANTIC_DIFF_RULE_ID: &str = "restore.stage.semantic_diff";

// --- apply-stage / apply --production (#26) ---------------------------------

/// Post-restore anchor contributor for the apply surface (ADR 0026 #26).
pub const APPLY_STAGE_POST_RESTORE_ANCHOR_RULE_ID: &str = "restore.apply_stage.post_restore_anchor";
/// Operator temporal-authority contributor for the apply surface (ADR 0026 #26).
pub const APPLY_STAGE_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID: &str =
    "restore.apply_stage.operator_temporal_authority";

// --- recover-apply (#27) ----------------------------------------------------

/// Recovery-manifest-digest contributor (ADR 0026 #27).
pub const RECOVER_APPLY_RECOVERY_MANIFEST_DIGEST_RULE_ID: &str =
    "restore.recover_apply.recovery_manifest_digest";
/// Current-backup-digest contributor (ADR 0026 #27).
pub const RECOVER_APPLY_CURRENT_BACKUP_DIGEST_RULE_ID: &str =
    "restore.recover_apply.current_backup_digest";
/// Operator temporal-authority contributor for recover-apply (ADR 0026 #27).
pub const RECOVER_APPLY_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID: &str =
    "restore.recover_apply.operator_temporal_authority";

/// Outcome of composing the semantic-diff drift contributors into one
/// ADR 0026 [`PolicyDecision`].
#[derive(Debug)]
pub struct SemanticDiffPolicy {
    /// Composed decision with explainability.
    pub decision: PolicyDecision,
    /// Mirror of [`RestoreDecision`] so existing JSON shapes stay stable
    /// while callers migrate to reading `decision.final_outcome`.
    pub legacy: RestoreDecision,
}

/// Compose the three semantic-diff drift contributors and (when the
/// operator passed `--acknowledge-recovery-risk`) attach a scoped
/// [`BreakGlassAuthorization`] whose `reason_code` is
/// [`BreakGlassReasonCode::RestoreRecovery`]. The break-glass authorization
/// elevates a `Warn`/`Quarantine` composition to `BreakGlass`; it never
/// substitutes for hard `Reject` contributors.
#[must_use]
pub fn compose_semantic_diff_decision(
    diff: &SemanticDiff,
    acknowledge_recovery_risk: bool,
    operation_type: &str,
    artifact_ref: &str,
) -> SemanticDiffPolicy {
    let recovery_drift =
        contribution_for_recovery_drift(diff, SEMANTIC_DIFF_RECOVERY_DRIFT_RULE_ID);
    let salience_drift =
        contribution_for_salience_drift(diff, SEMANTIC_DIFF_SALIENCE_DRIFT_RULE_ID);
    let contradiction_drift =
        contribution_for_contradiction_drift(diff, SEMANTIC_DIFF_CONTRADICTION_DRIFT_RULE_ID);
    let break_glass = if acknowledge_recovery_risk {
        Some(restore_recovery_break_glass(operation_type, artifact_ref))
    } else {
        None
    };
    let decision = compose_policy_outcomes(
        vec![recovery_drift, salience_drift, contradiction_drift],
        break_glass,
    );

    let legacy = diff.restore_decision(acknowledge_recovery_risk);
    SemanticDiffPolicy { decision, legacy }
}

/// Compose preflight contributors (manifest digest + semantic diff) plus,
/// when `production_active_store_plan` is requested, the always-`Reject`
/// `restore.preflight.production_active_store_plan` contributor.
#[must_use]
pub fn compose_preflight_decision(
    semantic_diff_decision: Option<&PolicyDecision>,
    production_active_store_plan_requested: bool,
) -> PolicyDecision {
    let mut contributions = vec![contribution_allow(
        PREFLIGHT_MANIFEST_DIGEST_RULE_ID,
        "structural manifest digest verified",
    )];
    if let Some(semantic) = semantic_diff_decision {
        contributions.push(contribution(
            PREFLIGHT_SEMANTIC_DIFF_RULE_ID,
            semantic.final_outcome,
            semantic_diff_reason(semantic),
        ));
    } else {
        contributions.push(contribution_allow(
            PREFLIGHT_SEMANTIC_DIFF_RULE_ID,
            "semantic diff not executed (no candidate store)",
        ));
    }
    if production_active_store_plan_requested {
        contributions.push(contribution_reject(
            PREFLIGHT_PRODUCTION_ACTIVE_STORE_PLAN_RULE_ID,
            "production active-store restore plan is fail-closed until production gates land",
        ));
    }
    compose_policy_outcomes(contributions, None)
}

/// Compose stage contributors. `Destructive-intent` is the boolean ack
/// (operator names the destructive intent); `manifest_digest` and
/// `semantic_diff` are inherited.
#[must_use]
pub fn compose_stage_decision(
    acknowledge_destructive_restore: bool,
    semantic_diff_decision: Option<&PolicyDecision>,
    acknowledge_recovery_risk: bool,
    artifact_ref: &str,
) -> PolicyDecision {
    let destructive_intent = if acknowledge_destructive_restore {
        contribution_allow(
            STAGE_DESTRUCTIVE_INTENT_RULE_ID,
            "operator acknowledged destructive restore intent",
        )
    } else {
        contribution_reject(
            STAGE_DESTRUCTIVE_INTENT_RULE_ID,
            "--acknowledge-destructive-restore is required",
        )
    };
    let manifest_digest = contribution_allow(
        STAGE_MANIFEST_DIGEST_RULE_ID,
        "backup manifest digest verified",
    );
    let semantic_diff = match semantic_diff_decision {
        Some(decision) => contribution(
            STAGE_SEMANTIC_DIFF_RULE_ID,
            decision.final_outcome,
            semantic_diff_reason(decision),
        ),
        None => contribution_allow(
            STAGE_SEMANTIC_DIFF_RULE_ID,
            "semantic diff not yet executed at this stage",
        ),
    };
    let break_glass = if acknowledge_recovery_risk {
        Some(restore_recovery_break_glass("restore.stage", artifact_ref))
    } else {
        None
    };
    compose_policy_outcomes(
        vec![destructive_intent, manifest_digest, semantic_diff],
        break_glass,
    )
}

/// Compose apply / apply-stage contributors.
#[must_use]
pub fn compose_apply_decision(
    post_restore_anchor: PolicyOutcome,
    post_restore_anchor_reason: &str,
    operator_temporal_authority: PolicyOutcome,
    operator_temporal_authority_reason: &str,
    acknowledge_recovery_risk: bool,
    operation_type: &str,
    artifact_ref: &str,
) -> PolicyDecision {
    let anchor = contribution(
        APPLY_STAGE_POST_RESTORE_ANCHOR_RULE_ID,
        post_restore_anchor,
        post_restore_anchor_reason,
    );
    let authority = contribution(
        APPLY_STAGE_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID,
        operator_temporal_authority,
        operator_temporal_authority_reason,
    );
    let break_glass = if acknowledge_recovery_risk {
        Some(restore_recovery_break_glass(operation_type, artifact_ref))
    } else {
        None
    };
    compose_policy_outcomes(vec![anchor, authority], break_glass)
}

/// Compose recover-apply contributors.
#[must_use]
pub fn compose_recover_apply_decision(
    recovery_manifest_digest_ok: bool,
    current_backup_digest_ok: bool,
    operator_temporal_authority_ok: bool,
    acknowledge_recovery_risk: bool,
    artifact_ref: &str,
) -> PolicyDecision {
    let manifest_digest = if recovery_manifest_digest_ok {
        contribution_allow(
            RECOVER_APPLY_RECOVERY_MANIFEST_DIGEST_RULE_ID,
            "recovery manifest digest verified",
        )
    } else {
        contribution_reject(
            RECOVER_APPLY_RECOVERY_MANIFEST_DIGEST_RULE_ID,
            "recovery manifest digest verification failed",
        )
    };
    let backup_digest = if current_backup_digest_ok {
        contribution_allow(
            RECOVER_APPLY_CURRENT_BACKUP_DIGEST_RULE_ID,
            "current backup artifact digests verified",
        )
    } else {
        contribution_reject(
            RECOVER_APPLY_CURRENT_BACKUP_DIGEST_RULE_ID,
            "current backup artifact digest verification failed",
        )
    };
    let authority = if operator_temporal_authority_ok {
        contribution_allow(
            RECOVER_APPLY_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID,
            "operator temporal authority within validity",
        )
    } else {
        contribution_reject(
            RECOVER_APPLY_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID,
            "operator temporal authority unverified",
        )
    };
    let break_glass = if acknowledge_recovery_risk {
        Some(restore_recovery_break_glass(
            "restore.recover_apply",
            artifact_ref,
        ))
    } else {
        None
    };
    compose_policy_outcomes(vec![manifest_digest, backup_digest, authority], break_glass)
}

/// Build the standard scoped [`BreakGlassAuthorization`] for the restore
/// surfaces. ADR 0026 §4: BreakGlass never substitutes for required
/// attestation at authority roots, so this is only attached to drift /
/// warning contributors — `apply_break_glass_override` is set true on the
/// non-blocking contributors elsewhere in the composition.
#[must_use]
pub fn restore_recovery_break_glass(
    operation_type: &str,
    artifact_ref: &str,
) -> BreakGlassAuthorization {
    BreakGlassAuthorization {
        permitted: true,
        attested: true,
        scope: BreakGlassScope {
            operation_type: operation_type.to_string(),
            artifact_refs: vec![artifact_ref.to_string()],
            not_before: None,
            not_after: None,
        },
        reason_code: BreakGlassReasonCode::RestoreRecovery,
    }
}

/// Emit a JSON value for the composed decision so callers can drop it
/// directly into a report.
#[must_use]
pub fn policy_decision_report(decision: &PolicyDecision) -> serde_json::Value {
    let contributing: Vec<_> = decision
        .contributing
        .iter()
        .map(|c| {
            json!({
                "rule_id": c.rule_id.as_str(),
                "outcome": c.outcome,
                "reason": c.reason,
            })
        })
        .collect();
    let discarded: Vec<_> = decision
        .discarded
        .iter()
        .map(|c| {
            json!({
                "rule_id": c.rule_id.as_str(),
                "outcome": c.outcome,
                "reason": c.reason,
            })
        })
        .collect();
    json!({
        "final_outcome": decision.final_outcome,
        "contributing": contributing,
        "discarded": discarded,
        "break_glass": decision.break_glass.as_ref().map(|bg| json!({
            "permitted": bg.permitted,
            "attested": bg.attested,
            "reason_code": bg.reason_code,
            "operation_type": bg.scope.operation_type,
            "artifact_refs": bg.scope.artifact_refs,
            "not_before": bg.scope.not_before,
            "not_after": bg.scope.not_after,
        })),
    })
}

fn contribution(
    rule_id: &str,
    outcome: PolicyOutcome,
    reason: impl Into<String>,
) -> PolicyContribution {
    let reason = reason.into();
    // Mark drift contributors as break-glass-overridable so the operator's
    // `--acknowledge-recovery-risk` scope can elevate a warning to a
    // BreakGlass decision. Hard `Reject` rules elsewhere in the composition
    // remain non-overridable.
    let overridable = !matches!(outcome, PolicyOutcome::Allow);
    let mut c = PolicyContribution::new(rule_id, outcome, reason)
        .expect("static restore policy contribution");
    if overridable {
        c = c.allow_break_glass_override();
    }
    c
}

fn contribution_allow(rule_id: &str, reason: &str) -> PolicyContribution {
    PolicyContribution::new(rule_id, PolicyOutcome::Allow, reason)
        .expect("static restore policy contribution")
}

fn contribution_reject(rule_id: &str, reason: &str) -> PolicyContribution {
    // Hard reject contributors are NOT marked break-glass-overridable here.
    // ADR 0026 §4: BreakGlass never substitutes for required attestation /
    // schema-version / authority-root contributors. Drift contributors are
    // marked overridable in `contribution()` above.
    PolicyContribution::new(rule_id, PolicyOutcome::Reject, reason)
        .expect("static restore policy contribution")
}

fn contribution_drift_warn(rule_id: &str, reason: &str) -> PolicyContribution {
    contribution(rule_id, PolicyOutcome::Warn, reason)
}

fn contribution_for_salience_drift(diff: &SemanticDiff, rule_id: &str) -> PolicyContribution {
    let salience_changed = diff.changes.iter().any(|change| {
        matches!(
            change.kind,
            SemanticChangeKind::SalienceDistributionChanged { .. }
        )
    });
    if salience_changed {
        contribution_drift_warn(rule_id, "salience distribution drift observed")
    } else {
        contribution_allow(rule_id, "no salience distribution drift observed")
    }
}

fn contribution_for_contradiction_drift(diff: &SemanticDiff, rule_id: &str) -> PolicyContribution {
    let contradiction_changed = diff.changes.iter().any(|change| {
        matches!(
            change.kind,
            SemanticChangeKind::UnresolvedContradictionMissing { .. }
                | SemanticChangeKind::UnresolvedContradictionAdded { .. }
                | SemanticChangeKind::UnresolvedContradictionChanged { .. }
        )
    });
    if contradiction_changed {
        contribution_drift_warn(rule_id, "contradiction snapshot drift observed")
    } else {
        contribution_allow(rule_id, "no contradiction snapshot drift observed")
    }
}

fn contribution_for_recovery_drift(diff: &SemanticDiff, rule_id: &str) -> PolicyContribution {
    let severity = diff.severity();
    let (outcome, reason): (PolicyOutcome, String) = match severity {
        SemanticSeverity::Clean => (
            PolicyOutcome::Allow,
            "no recovery drift observed".to_string(),
        ),
        SemanticSeverity::Warning => (
            PolicyOutcome::Warn,
            format!(
                "recovery drift warning across {} change(s)",
                diff.changes.len()
            ),
        ),
        // ADR 0033 §5 mandates Reject for drift conditions affecting
        // correctness — `PreconditionUnmet` is the active drift class.
        SemanticSeverity::PreconditionUnmet => (
            PolicyOutcome::Reject,
            "recovery drift precondition unmet; ADR 0033 §5 mandates Reject".to_string(),
        ),
    };
    contribution(rule_id, outcome, reason)
}

fn semantic_diff_reason(decision: &PolicyDecision) -> String {
    match decision.final_outcome {
        PolicyOutcome::Allow => "semantic diff clean".to_string(),
        PolicyOutcome::Warn => "semantic diff warning (drift acknowledged)".to_string(),
        PolicyOutcome::BreakGlass => {
            "semantic diff warning elevated to BreakGlass via --acknowledge-recovery-risk"
                .to_string()
        }
        PolicyOutcome::Quarantine => "semantic diff quarantine".to_string(),
        PolicyOutcome::Reject => "semantic diff rejected drift".to_string(),
    }
}

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

    fn clean_diff() -> SemanticDiff {
        let snap = SemanticSnapshot::default();
        snap.diff_against_restore(&snap)
    }

    #[test]
    fn clean_semantic_diff_yields_allow() {
        let diff = clean_diff();
        let policy = compose_semantic_diff_decision(&diff, false, "restore.semantic_diff", "test");
        assert_eq!(policy.decision.final_outcome, PolicyOutcome::Allow);
        assert!(policy.decision.break_glass.is_none());
        assert!(matches!(policy.legacy, RestoreDecision::Clean));
    }

    #[test]
    fn preflight_with_production_plan_is_reject() {
        let semantic = compose_semantic_diff_decision(&clean_diff(), false, "x", "y").decision;
        let decision = compose_preflight_decision(Some(&semantic), true);
        assert_eq!(decision.final_outcome, PolicyOutcome::Reject);
    }

    #[test]
    fn preflight_without_production_plan_is_allow_when_clean() {
        let semantic = compose_semantic_diff_decision(&clean_diff(), false, "x", "y").decision;
        let decision = compose_preflight_decision(Some(&semantic), false);
        assert_eq!(decision.final_outcome, PolicyOutcome::Allow);
    }

    #[test]
    fn stage_without_destructive_intent_is_reject() {
        let semantic = compose_semantic_diff_decision(&clean_diff(), false, "x", "y").decision;
        let decision = compose_stage_decision(false, Some(&semantic), false, "stage_dir:test");
        assert_eq!(decision.final_outcome, PolicyOutcome::Reject);
    }

    #[test]
    fn recover_apply_break_glass_elevates_warn_only() {
        // Three Allow contributors with break-glass attached should remain Allow.
        let decision = compose_recover_apply_decision(true, true, true, true, "manifest:test");
        assert_eq!(decision.final_outcome, PolicyOutcome::Allow);
    }
}