crtx 0.1.0

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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
//! `RESTORE_INTENT` payload + verification (Ed25519, ADR 0010).
//!
//! Doctrine: `DESIGN_production_active_store_restore.md` §"RESTORE_INTENT
//! payload". The payload is a JSON document; the signature is detached
//! (sibling `.sig` file containing raw 64-byte Ed25519 signature) so it can
//! be reproduced from canonical bytes without re-serializing.
//!
//! Canonical bytes: the on-disk payload bytes as read. To make this stable
//! the operator MUST write the payload exactly once and not pretty-print
//! after signing — exactly the contract `audit anchor` already enforces for
//! anchor payloads (`crates/cortex-cli/src/cmd/audit.rs` §"verification-key").
//!
//! ## Lock takeover sub-payload
//!
//! Stale-lock takeover uses a smaller `RESTORE_TAKEOVER_ATTESTATION` payload
//! (same crypto, different `kind`). The takeover payload binds the stale
//! `pid` and `acquired_at` from the on-disk marker so a generic operator
//! signature cannot be redirected to a different stranded process.

use std::fs;
use std::path::{Path, PathBuf};

use chrono::{DateTime, Utc};
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use serde::Deserialize;

/// Wire kind for production destructive restore intent.
pub const RESTORE_INTENT_KIND: &str = "cortex_restore_intent";
/// Wire kind for stale-lock takeover attestation.
pub const RESTORE_TAKEOVER_KIND: &str = "cortex_restore_lock_takeover";
/// Schema version for both payload kinds in this build.
pub const RESTORE_INTENT_SCHEMA_VERSION: u16 = 1;

/// Stable invariant emitted to stderr when the payload
/// `operator_principal_id` is not structurally bound to the supplied
/// Ed25519 verifying key. See [`derive_operator_principal_id`] for the
/// binding rule. Closes Attack A in
/// `docs/reviews/RED_TEAM_2026-05-12_post_8f43450.md`.
pub const RESTORE_INTENT_PRINCIPAL_NOT_BOUND_INVARIANT: &str =
    "restore.intent.operator_principal_id.not_bound_to_verifying_key";

/// Prefix for deterministically derived operator principal ids.
///
/// The principal id is bound to the verifying key by construction:
/// `operator:` + the full 64 lowercase hex chars (32 bytes) of
/// BLAKE3(key_bytes). The verifier rejects any payload whose
/// `operator_principal_id` is not the derived string for the supplied 32-byte
/// Ed25519 public key. This makes principal forgery structurally impossible:
/// minting a fresh keypair and naming yourself any other operator label
/// fails closed (Attack A, `docs/reviews/RED_TEAM_2026-05-12_post_8f43450.md`).
pub const OPERATOR_PRINCIPAL_PREFIX: &str = "operator:";

/// Length (hex chars) of the BLAKE3-key-fingerprint portion of a derived
/// principal id. Equal to the full 32-byte BLAKE3 output rendered as
/// lowercase hex (64 chars). The earlier truncation to 16 hex chars (64
/// bits) was flagged by Red Team v2 (INFO) and Code Review v2 (MEDIUM):
/// a preimage attack against a specific target principal id is ~$200-500k
/// cloud and becomes attackable when a roster-backed gate lands (ADR 0033
/// §4a forward path). The full digest collapses preimage cost to BLAKE3's
/// 256-bit security target.
pub const OPERATOR_PRINCIPAL_FINGERPRINT_HEX_LEN: usize = 64;

/// Derive the operator principal id deterministically from the Ed25519
/// verifying key bytes. Pattern: `operator:` + `hex(blake3(key_bytes))`
/// (the full 64-char lowercase hex digest).
///
/// This is the only legal value for `operator_principal_id` in a verified
/// `RESTORE_INTENT` or `RESTORE_TAKEOVER_ATTESTATION` payload. The verifier
/// asserts `payload.operator_principal_id == derive_operator_principal_id(key_bytes)`
/// before running the Ed25519 verify, so an attacker who mints a fresh
/// keypair cannot claim a different principal id.
#[must_use]
pub fn derive_operator_principal_id(key_bytes: &[u8; 32]) -> String {
    let digest = blake3::hash(key_bytes);
    let hex = digest.to_hex().to_string();
    debug_assert_eq!(hex.len(), OPERATOR_PRINCIPAL_FINGERPRINT_HEX_LEN);
    format!("{OPERATOR_PRINCIPAL_PREFIX}{hex}")
}

/// Errors raised while verifying a `RESTORE_INTENT` (or takeover) payload.
#[derive(Debug)]
pub enum IntentError {
    /// Payload file is missing or unreadable.
    Io {
        /// Field name the caller passed (for the operator message).
        field: &'static str,
        /// Path that failed.
        path: PathBuf,
        /// Underlying error string.
        message: String,
    },
    /// Payload JSON did not parse.
    Malformed {
        /// Path that did not parse.
        path: PathBuf,
        /// Parse error.
        message: String,
    },
    /// Payload `kind` did not match the expected wire string.
    KindMismatch {
        /// Expected wire kind.
        expected: &'static str,
        /// Observed wire kind.
        found: String,
    },
    /// Payload `schema_version` did not match this build.
    SchemaMismatch {
        /// Expected schema version.
        expected: u16,
        /// Observed schema version.
        found: u16,
    },
    /// Payload `not_before` / `not_after` window does not include `now`.
    OutsideValidity {
        /// `now()` at verification time.
        now: DateTime<Utc>,
        /// Lower bound on validity (from payload).
        not_before: DateTime<Utc>,
        /// Upper bound on validity (from payload).
        not_after: DateTime<Utc>,
    },
    /// Payload `deployment_id` did not match the runtime deployment.
    DeploymentMismatch {
        /// Deployment in payload.
        payload: String,
        /// Deployment expected by the runtime.
        expected: String,
    },
    /// Payload `active_db_path` did not match the runtime layout path.
    ActivePathMismatch {
        /// Wire field name for diagnostics.
        field: &'static str,
        /// Path in payload.
        payload: PathBuf,
        /// Path expected by the runtime layout.
        expected: PathBuf,
    },
    /// Backup-manifest BLAKE3 digest in payload disagrees with the
    /// caller-computed digest.
    ManifestDigestMismatch {
        /// Digest declared in payload.
        payload: String,
        /// Digest the caller computed over the manifest bytes.
        computed: String,
    },
    /// Staged-artifact BLAKE3 digest in payload disagrees with the
    /// caller-computed digest.
    StagedDigestMismatch {
        /// Wire field name for diagnostics.
        field: &'static str,
        /// Digest declared in payload.
        payload: String,
        /// Digest the caller computed over the staged artifact bytes.
        computed: String,
    },
    /// Signature file is missing or invalid.
    Signature {
        /// What failed (e.g. "missing signature file").
        reason: String,
        /// Path involved.
        path: PathBuf,
    },
    /// Cryptographic verification failed.
    BadSignature,
    /// Payload `operator_principal_id` is not structurally bound to the
    /// supplied verifying key. The principal must equal the deterministic
    /// derivation from the 32-byte Ed25519 public key
    /// ([`derive_operator_principal_id`]). Closes Attack A from the
    /// 2026-05-12 red-team review.
    KeyMismatch {
        /// `operator_principal_id` observed in the payload.
        payload_principal: String,
        /// Principal id deterministically derived from the supplied key.
        derived_principal: String,
    },
}

impl std::fmt::Display for IntentError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io {
                field,
                path,
                message,
            } => write!(
                f,
                "restore intent: cannot read `{field}` at `{}`: {message}",
                path.display()
            ),
            Self::Malformed { path, message } => write!(
                f,
                "restore intent: payload `{}` is malformed JSON: {message}",
                path.display()
            ),
            Self::KindMismatch { expected, found } => write!(
                f,
                "restore intent: payload kind `{found}` does not match expected `{expected}`",
            ),
            Self::SchemaMismatch { expected, found } => write!(
                f,
                "restore intent: payload schema_version {found} does not match expected {expected}",
            ),
            Self::OutsideValidity {
                now,
                not_before,
                not_after,
            } => write!(
                f,
                "restore intent: now={now} is outside validity window [{not_before}, {not_after}]",
            ),
            Self::DeploymentMismatch { payload, expected } => write!(
                f,
                "restore intent: payload deployment_id `{payload}` does not match runtime `{expected}`",
            ),
            Self::ActivePathMismatch {
                field,
                payload,
                expected,
            } => write!(
                f,
                "restore intent: payload `{field}` `{}` does not match runtime path `{}`",
                payload.display(),
                expected.display(),
            ),
            Self::ManifestDigestMismatch { payload, computed } => write!(
                f,
                "restore intent: backup_manifest_blake3 mismatch: payload={payload}, computed={computed}",
            ),
            Self::StagedDigestMismatch {
                field,
                payload,
                computed,
            } => write!(
                f,
                "restore intent: staged `{field}` digest mismatch: payload={payload}, computed={computed}",
            ),
            Self::Signature { reason, path } => write!(
                f,
                "restore intent: signature failure: {reason} (path `{}`)",
                path.display()
            ),
            Self::BadSignature => write!(f, "restore intent: Ed25519 signature verification failed"),
            Self::KeyMismatch {
                payload_principal,
                derived_principal,
            } => write!(
                f,
                "restore intent: payload operator_principal_id `{payload_principal}` is not bound to the supplied verifying key (expected deterministic derivation `{derived_principal}`; invariant={RESTORE_INTENT_PRINCIPAL_NOT_BOUND_INVARIANT})",
            ),
        }
    }
}

impl std::error::Error for IntentError {}

/// Wire payload deserialized verbatim from disk.
///
/// This mirrors `DESIGN_production_active_store_restore.md` §"RESTORE_INTENT
/// payload". Extra fields are ignored so future minor revs of the payload
/// (still `schema_version = 1`) round-trip.
#[derive(Debug, Deserialize)]
pub struct RestoreIntentPayload {
    /// Wire kind: must equal [`RESTORE_INTENT_KIND`].
    pub kind: String,
    /// Schema version: must equal [`RESTORE_INTENT_SCHEMA_VERSION`].
    pub schema_version: u16,
    /// Deployment binding.
    pub deployment_id: String,
    /// Absolute path to the active SQLite store this intent authorizes
    /// replacing.
    pub active_db_path: PathBuf,
    /// Absolute path to the active JSONL mirror this intent authorizes
    /// replacing.
    pub active_event_log_path: PathBuf,
    /// Caller-side digest of the backup manifest bytes.
    pub backup_manifest_blake3: String,
    /// Caller-side digest of the staged SQLite bytes.
    pub staged_sqlite_blake3: String,
    /// Caller-side digest of the staged JSONL bytes.
    pub staged_jsonl_blake3: String,
    /// Operator principal this intent binds to (ADR 0019).
    pub operator_principal_id: String,
    /// Validity window lower bound.
    pub not_before: DateTime<Utc>,
    /// Validity window upper bound.
    pub not_after: DateTime<Utc>,
    /// Domain-version of the payload contract.
    pub p_n_schema_version: u16,
}

/// Sub-payload for stale-lock takeover attestation. Binds the stale process
/// pid + acquired_at so a generic operator signature cannot be redirected to
/// take over a different stranded process.
#[derive(Debug, Deserialize)]
pub struct RestoreLockTakeoverPayload {
    /// Wire kind: must equal [`RESTORE_TAKEOVER_KIND`].
    pub kind: String,
    /// Schema version: must equal [`RESTORE_INTENT_SCHEMA_VERSION`].
    pub schema_version: u16,
    /// Deployment binding (mirrors RESTORE_INTENT).
    pub deployment_id: String,
    /// Operator principal bound to the takeover (ADR 0019).
    pub operator_principal_id: String,
    /// Stale process pid as observed in the marker. Caller MUST verify this
    /// matches the on-disk marker before invoking takeover.
    pub stale_pid: u32,
    /// Stale `acquired_at` as observed in the marker.
    pub stale_acquired_at: DateTime<Utc>,
    /// Operator-provided justification (ADR 0026 §4 BreakGlass scope).
    pub justification: String,
    /// Validity window lower bound.
    pub not_before: DateTime<Utc>,
    /// Validity window upper bound.
    pub not_after: DateTime<Utc>,
}

/// Verified `RESTORE_INTENT` plus the canonical payload bytes that were
/// signed. The bytes are returned so the caller can hash them and bind the
/// hash into the lock marker.
#[derive(Debug)]
pub struct VerifiedRestoreIntent {
    /// Parsed payload.
    pub payload: RestoreIntentPayload,
    /// Raw on-disk bytes (the signature is over these bytes byte-for-byte).
    /// Retained for downstream replay verification; not all callers need
    /// it today (lock marker binds the digest instead) so the field is
    /// annotated `#[allow(dead_code)]` until a re-verifier consumer lands.
    #[allow(dead_code)]
    pub canonical_bytes: Vec<u8>,
    /// BLAKE3 digest of `canonical_bytes` (with `blake3:` prefix).
    pub canonical_blake3: String,
}

/// Verified takeover attestation plus the canonical bytes that were signed.
#[derive(Debug)]
pub struct VerifiedTakeoverAttestation {
    /// Parsed payload.
    pub payload: RestoreLockTakeoverPayload,
    /// Raw on-disk bytes. Retained for downstream replay verification.
    #[allow(dead_code)]
    pub canonical_bytes: Vec<u8>,
    /// BLAKE3 digest of `canonical_bytes`.
    pub canonical_blake3: String,
}

/// Runtime-side expectations the caller passes in so the intent payload can
/// be bound to actual restore inputs. Mismatch on any field is a hard
/// failure (`Reject`).
#[derive(Debug)]
pub struct ExpectedIntent<'a> {
    /// Deployment identifier the runtime resolved from `cortex-core`.
    pub deployment_id: &'a str,
    /// Active SQLite path the runtime resolved from [`crate::paths::DataLayout`].
    pub active_db_path: &'a Path,
    /// Active JSONL path the runtime resolved.
    pub active_event_log_path: &'a Path,
    /// Caller-computed digest of the backup manifest bytes.
    pub backup_manifest_blake3: &'a str,
    /// Caller-computed digest of the staged SQLite bytes.
    pub staged_sqlite_blake3: &'a str,
    /// Caller-computed digest of the staged JSONL bytes.
    pub staged_jsonl_blake3: &'a str,
    /// Current wall-clock time for validity window enforcement.
    pub now: DateTime<Utc>,
    /// Ed25519 verifying key bound to the operator principal. The
    /// payload `operator_principal_id` MUST equal the deterministic
    /// derivation from these key bytes (see
    /// [`derive_operator_principal_id`]). Operator-visible
    /// diagnostics use [`Self::verifying_key_fingerprint`].
    pub verifying_key: VerifyingKey,
    /// Operator-visible fingerprint of the verifying key. Used by the
    /// lock-marker and audit-row diagnostics surfaced by
    /// `cortex restore apply --production`; not consulted by the
    /// principal-binding check (which derives the expected principal id
    /// from `verifying_key` bytes structurally), so this field is
    /// retained for caller-side documentation only.
    #[allow(dead_code)]
    pub verifying_key_fingerprint: &'a str,
}

/// Verify a `RESTORE_INTENT` payload + detached signature file.
///
/// `signature_path` is the sibling `<intent>.sig` file (raw 64 bytes of
/// Ed25519 signature; no envelope). The signature is over
/// `canonical_bytes` (the on-disk payload bytes byte-for-byte).
pub fn verify_restore_intent(
    intent_path: &Path,
    signature_path: &Path,
    expected: &ExpectedIntent<'_>,
) -> Result<VerifiedRestoreIntent, IntentError> {
    let canonical_bytes = read_canonical_bytes(intent_path, "restore_intent")?;
    let payload: RestoreIntentPayload =
        serde_json::from_slice(&canonical_bytes).map_err(|err| IntentError::Malformed {
            path: intent_path.to_path_buf(),
            message: err.to_string(),
        })?;

    if payload.kind != RESTORE_INTENT_KIND {
        return Err(IntentError::KindMismatch {
            expected: RESTORE_INTENT_KIND,
            found: payload.kind,
        });
    }
    if payload.schema_version != RESTORE_INTENT_SCHEMA_VERSION
        || payload.p_n_schema_version != RESTORE_INTENT_SCHEMA_VERSION
    {
        return Err(IntentError::SchemaMismatch {
            expected: RESTORE_INTENT_SCHEMA_VERSION,
            found: payload.schema_version,
        });
    }

    enforce_validity_window(expected.now, payload.not_before, payload.not_after)?;
    enforce_deployment(&payload.deployment_id, expected.deployment_id)?;
    enforce_active_path(
        "active_db_path",
        &payload.active_db_path,
        expected.active_db_path,
    )?;
    enforce_active_path(
        "active_event_log_path",
        &payload.active_event_log_path,
        expected.active_event_log_path,
    )?;
    enforce_digest(
        "backup_manifest_blake3",
        &payload.backup_manifest_blake3,
        expected.backup_manifest_blake3,
        |payload, computed| IntentError::ManifestDigestMismatch {
            payload: payload.to_string(),
            computed: computed.to_string(),
        },
    )?;
    enforce_digest(
        "staged_sqlite_blake3",
        &payload.staged_sqlite_blake3,
        expected.staged_sqlite_blake3,
        |payload, computed| IntentError::StagedDigestMismatch {
            field: "staged_sqlite_blake3",
            payload: payload.to_string(),
            computed: computed.to_string(),
        },
    )?;
    enforce_digest(
        "staged_jsonl_blake3",
        &payload.staged_jsonl_blake3,
        expected.staged_jsonl_blake3,
        |payload, computed| IntentError::StagedDigestMismatch {
            field: "staged_jsonl_blake3",
            payload: payload.to_string(),
            computed: computed.to_string(),
        },
    )?;

    verify_detached_signature(
        signature_path,
        &canonical_bytes,
        &expected.verifying_key,
        &payload.operator_principal_id,
    )?;

    let canonical_blake3 = blake3_hex(&canonical_bytes);
    Ok(VerifiedRestoreIntent {
        payload,
        canonical_bytes,
        canonical_blake3,
    })
}

/// Runtime-side expectations the caller passes in for stale-lock takeover
/// verification. Mirrors [`ExpectedIntent`] but for the takeover sub-payload.
#[derive(Debug)]
pub struct ExpectedTakeover<'a> {
    /// Deployment identifier the runtime resolved.
    pub deployment_id: &'a str,
    /// Stale pid observed in the on-disk marker.
    pub stale_pid: u32,
    /// Stale `acquired_at` observed in the on-disk marker.
    pub stale_acquired_at: DateTime<Utc>,
    /// Current wall-clock time for validity window enforcement.
    pub now: DateTime<Utc>,
    /// Operator verifying key. The payload `operator_principal_id`
    /// MUST equal the deterministic derivation from these key bytes
    /// (see [`derive_operator_principal_id`]).
    pub verifying_key: VerifyingKey,
    /// Operator-visible fingerprint of the verifying key. Retained for
    /// caller-side audit/diagnostic surfacing only; not consulted by
    /// the principal-binding check.
    #[allow(dead_code)]
    pub verifying_key_fingerprint: &'a str,
}

/// Verify a stale-lock takeover attestation. The caller MUST pass the
/// observed stale `pid` and `acquired_at` extracted from the on-disk marker
/// so the signed payload must name them explicitly.
pub fn verify_takeover_attestation(
    attestation_path: &Path,
    signature_path: &Path,
    expected: &ExpectedTakeover<'_>,
) -> Result<VerifiedTakeoverAttestation, IntentError> {
    let canonical_bytes = read_canonical_bytes(attestation_path, "takeover_attestation")?;
    let payload: RestoreLockTakeoverPayload =
        serde_json::from_slice(&canonical_bytes).map_err(|err| IntentError::Malformed {
            path: attestation_path.to_path_buf(),
            message: err.to_string(),
        })?;

    if payload.kind != RESTORE_TAKEOVER_KIND {
        return Err(IntentError::KindMismatch {
            expected: RESTORE_TAKEOVER_KIND,
            found: payload.kind,
        });
    }
    if payload.schema_version != RESTORE_INTENT_SCHEMA_VERSION {
        return Err(IntentError::SchemaMismatch {
            expected: RESTORE_INTENT_SCHEMA_VERSION,
            found: payload.schema_version,
        });
    }

    enforce_validity_window(expected.now, payload.not_before, payload.not_after)?;
    enforce_deployment(&payload.deployment_id, expected.deployment_id)?;

    if payload.stale_pid != expected.stale_pid {
        return Err(IntentError::Malformed {
            path: attestation_path.to_path_buf(),
            message: format!(
                "takeover attestation stale_pid={} does not match observed marker pid={}",
                payload.stale_pid, expected.stale_pid,
            ),
        });
    }
    if payload.stale_acquired_at != expected.stale_acquired_at {
        return Err(IntentError::Malformed {
            path: attestation_path.to_path_buf(),
            message: format!(
                "takeover attestation stale_acquired_at={} does not match observed marker acquired_at={}",
                payload.stale_acquired_at, expected.stale_acquired_at,
            ),
        });
    }
    if payload.justification.trim().is_empty() {
        return Err(IntentError::Malformed {
            path: attestation_path.to_path_buf(),
            message: "takeover attestation justification is empty".to_string(),
        });
    }

    verify_detached_signature(
        signature_path,
        &canonical_bytes,
        &expected.verifying_key,
        &payload.operator_principal_id,
    )?;

    let canonical_blake3 = blake3_hex(&canonical_bytes);
    Ok(VerifiedTakeoverAttestation {
        payload,
        canonical_bytes,
        canonical_blake3,
    })
}

fn read_canonical_bytes(path: &Path, field: &'static str) -> Result<Vec<u8>, IntentError> {
    fs::read(path).map_err(|err| IntentError::Io {
        field,
        path: path.to_path_buf(),
        message: err.to_string(),
    })
}

fn enforce_validity_window(
    now: DateTime<Utc>,
    not_before: DateTime<Utc>,
    not_after: DateTime<Utc>,
) -> Result<(), IntentError> {
    if not_after < not_before {
        return Err(IntentError::OutsideValidity {
            now,
            not_before,
            not_after,
        });
    }
    if now < not_before || now > not_after {
        return Err(IntentError::OutsideValidity {
            now,
            not_before,
            not_after,
        });
    }
    Ok(())
}

fn enforce_deployment(payload_id: &str, expected_id: &str) -> Result<(), IntentError> {
    if payload_id == expected_id {
        Ok(())
    } else {
        Err(IntentError::DeploymentMismatch {
            payload: payload_id.to_string(),
            expected: expected_id.to_string(),
        })
    }
}

fn enforce_active_path(
    field: &'static str,
    payload_path: &Path,
    expected_path: &Path,
) -> Result<(), IntentError> {
    let payload_canon = payload_path
        .canonicalize()
        .unwrap_or_else(|_| payload_path.to_path_buf());
    let expected_canon = expected_path
        .canonicalize()
        .unwrap_or_else(|_| expected_path.to_path_buf());
    if payload_canon == expected_canon {
        Ok(())
    } else {
        Err(IntentError::ActivePathMismatch {
            field,
            payload: payload_canon,
            expected: expected_canon,
        })
    }
}

fn enforce_digest(
    _field: &'static str,
    payload_digest: &str,
    computed_digest: &str,
    err: impl FnOnce(&str, &str) -> IntentError,
) -> Result<(), IntentError> {
    if payload_digest == computed_digest {
        Ok(())
    } else {
        Err(err(payload_digest, computed_digest))
    }
}

fn verify_detached_signature(
    signature_path: &Path,
    canonical_bytes: &[u8],
    verifying_key: &VerifyingKey,
    payload_principal: &str,
) -> Result<(), IntentError> {
    // Structural binding: the payload `operator_principal_id` MUST equal
    // the deterministic derivation from the supplied 32-byte verifying
    // key. Closes Attack A from the 2026-05-12 red-team review: minting
    // a fresh keypair and naming any other operator label now fails
    // closed before the Ed25519 verify runs. The verify itself is still
    // load-bearing — it proves the holder of the matching private key
    // signed the canonical bytes — but the principal claim is no longer
    // operator-supplied; it is derived from the key bytes.
    let key_bytes = verifying_key.to_bytes();
    let derived_principal = derive_operator_principal_id(&key_bytes);
    if payload_principal != derived_principal {
        return Err(IntentError::KeyMismatch {
            payload_principal: payload_principal.to_string(),
            derived_principal,
        });
    }
    let sig_bytes = fs::read(signature_path).map_err(|err| IntentError::Signature {
        reason: format!("cannot read detached signature: {err}"),
        path: signature_path.to_path_buf(),
    })?;
    let sig_array: [u8; 64] =
        sig_bytes
            .as_slice()
            .try_into()
            .map_err(|_| IntentError::Signature {
                reason: format!(
                    "detached signature must be exactly 64 bytes (Ed25519), got {}",
                    sig_bytes.len()
                ),
                path: signature_path.to_path_buf(),
            })?;
    let signature = Signature::from_bytes(&sig_array);
    verifying_key
        .verify(canonical_bytes, &signature)
        .map_err(|_| IntentError::BadSignature)?;
    Ok(())
}

fn blake3_hex(bytes: &[u8]) -> String {
    format!("blake3:{}", blake3::hash(bytes).to_hex())
}

#[cfg(test)]
mod tests {
    use super::*;
    use ed25519_dalek::{Signer, SigningKey};

    fn now() -> DateTime<Utc> {
        Utc::now()
    }

    fn fixture_signing_key() -> SigningKey {
        SigningKey::from_bytes(&[7u8; 32])
    }

    /// Principal id deterministically derived from [`fixture_signing_key`].
    /// Tests that exercise the happy path or the post-binding signature
    /// gate MUST use this value in the payload `operator_principal_id`
    /// field; otherwise the new structural binding check (Attack A
    /// closure) fail-closes before the signature verify.
    fn fixture_principal_id() -> String {
        let vk = fixture_signing_key().verifying_key();
        derive_operator_principal_id(&vk.to_bytes())
    }

    fn sign_into(dir: &Path, payload_json: &serde_json::Value) -> (PathBuf, PathBuf, VerifyingKey) {
        let intent_path = dir.join("RESTORE_INTENT.json");
        let sig_path = dir.join("RESTORE_INTENT.sig");
        let bytes = serde_json::to_vec_pretty(payload_json).unwrap();
        fs::write(&intent_path, &bytes).unwrap();
        let signing_key = fixture_signing_key();
        let signature = signing_key.sign(&bytes);
        fs::write(&sig_path, signature.to_bytes()).unwrap();
        (intent_path, sig_path, signing_key.verifying_key())
    }

    #[test]
    fn verify_restore_intent_happy_path() {
        let dir = tempfile::tempdir().unwrap();
        let active_db = dir.path().join("cortex.db");
        let active_jsonl = dir.path().join("events.jsonl");
        fs::write(&active_db, b"db").unwrap();
        fs::write(&active_jsonl, b"jsonl").unwrap();

        let principal_id = fixture_principal_id();
        let not_before = now() - chrono::Duration::seconds(60);
        let not_after = now() + chrono::Duration::seconds(60);
        let payload = serde_json::json!({
            "kind": RESTORE_INTENT_KIND,
            "schema_version": RESTORE_INTENT_SCHEMA_VERSION,
            "deployment_id": "dep-1",
            "active_db_path": active_db,
            "active_event_log_path": active_jsonl,
            "backup_manifest_blake3": "blake3:aa",
            "staged_sqlite_blake3": "blake3:bb",
            "staged_jsonl_blake3": "blake3:cc",
            "operator_principal_id": principal_id,
            "not_before": not_before.to_rfc3339(),
            "not_after": not_after.to_rfc3339(),
            "p_n_schema_version": RESTORE_INTENT_SCHEMA_VERSION,
        });
        let (intent_path, sig_path, verifying_key) = sign_into(dir.path(), &payload);

        let expected = ExpectedIntent {
            deployment_id: "dep-1",
            active_db_path: &active_db,
            active_event_log_path: &active_jsonl,
            backup_manifest_blake3: "blake3:aa",
            staged_sqlite_blake3: "blake3:bb",
            staged_jsonl_blake3: "blake3:cc",
            now: now(),
            verifying_key,
            verifying_key_fingerprint: "fp",
        };
        let verified = verify_restore_intent(&intent_path, &sig_path, &expected).unwrap();
        assert_eq!(
            verified.payload.operator_principal_id,
            fixture_principal_id()
        );
        assert!(verified.canonical_blake3.starts_with("blake3:"));
    }

    #[test]
    fn verify_restore_intent_rejects_wrong_deployment() {
        let dir = tempfile::tempdir().unwrap();
        let active_db = dir.path().join("cortex.db");
        let active_jsonl = dir.path().join("events.jsonl");
        fs::write(&active_db, b"db").unwrap();
        fs::write(&active_jsonl, b"jsonl").unwrap();

        let not_before = now() - chrono::Duration::seconds(60);
        let not_after = now() + chrono::Duration::seconds(60);
        let payload = serde_json::json!({
            "kind": RESTORE_INTENT_KIND,
            "schema_version": RESTORE_INTENT_SCHEMA_VERSION,
            "deployment_id": "dep-other",
            "active_db_path": active_db,
            "active_event_log_path": active_jsonl,
            "backup_manifest_blake3": "blake3:aa",
            "staged_sqlite_blake3": "blake3:bb",
            "staged_jsonl_blake3": "blake3:cc",
            "operator_principal_id": fixture_principal_id(),
            "not_before": not_before.to_rfc3339(),
            "not_after": not_after.to_rfc3339(),
            "p_n_schema_version": RESTORE_INTENT_SCHEMA_VERSION,
        });
        let (intent_path, sig_path, verifying_key) = sign_into(dir.path(), &payload);
        let expected = ExpectedIntent {
            deployment_id: "dep-1",
            active_db_path: &active_db,
            active_event_log_path: &active_jsonl,
            backup_manifest_blake3: "blake3:aa",
            staged_sqlite_blake3: "blake3:bb",
            staged_jsonl_blake3: "blake3:cc",
            now: now(),
            verifying_key,
            verifying_key_fingerprint: "fp",
        };
        match verify_restore_intent(&intent_path, &sig_path, &expected) {
            Err(IntentError::DeploymentMismatch { payload, expected }) => {
                assert_eq!(payload, "dep-other");
                assert_eq!(expected, "dep-1");
            }
            other => panic!("expected DeploymentMismatch, got {other:?}"),
        }
    }

    #[test]
    fn verify_restore_intent_rejects_expired() {
        let dir = tempfile::tempdir().unwrap();
        let active_db = dir.path().join("cortex.db");
        let active_jsonl = dir.path().join("events.jsonl");
        fs::write(&active_db, b"db").unwrap();
        fs::write(&active_jsonl, b"jsonl").unwrap();

        let not_before = now() - chrono::Duration::seconds(120);
        let not_after = now() - chrono::Duration::seconds(60);
        let payload = serde_json::json!({
            "kind": RESTORE_INTENT_KIND,
            "schema_version": RESTORE_INTENT_SCHEMA_VERSION,
            "deployment_id": "dep-1",
            "active_db_path": active_db,
            "active_event_log_path": active_jsonl,
            "backup_manifest_blake3": "blake3:aa",
            "staged_sqlite_blake3": "blake3:bb",
            "staged_jsonl_blake3": "blake3:cc",
            "operator_principal_id": fixture_principal_id(),
            "not_before": not_before.to_rfc3339(),
            "not_after": not_after.to_rfc3339(),
            "p_n_schema_version": RESTORE_INTENT_SCHEMA_VERSION,
        });
        let (intent_path, sig_path, verifying_key) = sign_into(dir.path(), &payload);
        let expected = ExpectedIntent {
            deployment_id: "dep-1",
            active_db_path: &active_db,
            active_event_log_path: &active_jsonl,
            backup_manifest_blake3: "blake3:aa",
            staged_sqlite_blake3: "blake3:bb",
            staged_jsonl_blake3: "blake3:cc",
            now: now(),
            verifying_key,
            verifying_key_fingerprint: "fp",
        };
        match verify_restore_intent(&intent_path, &sig_path, &expected) {
            Err(IntentError::OutsideValidity { .. }) => {}
            other => panic!("expected OutsideValidity, got {other:?}"),
        }
    }

    #[test]
    fn verify_restore_intent_rejects_tampered_payload() {
        let dir = tempfile::tempdir().unwrap();
        let active_db = dir.path().join("cortex.db");
        let active_jsonl = dir.path().join("events.jsonl");
        fs::write(&active_db, b"db").unwrap();
        fs::write(&active_jsonl, b"jsonl").unwrap();

        let not_before = now() - chrono::Duration::seconds(60);
        let not_after = now() + chrono::Duration::seconds(60);
        let payload = serde_json::json!({
            "kind": RESTORE_INTENT_KIND,
            "schema_version": RESTORE_INTENT_SCHEMA_VERSION,
            "deployment_id": "dep-1",
            "active_db_path": active_db,
            "active_event_log_path": active_jsonl,
            "backup_manifest_blake3": "blake3:aa",
            "staged_sqlite_blake3": "blake3:bb",
            "staged_jsonl_blake3": "blake3:cc",
            "operator_principal_id": fixture_principal_id(),
            "not_before": not_before.to_rfc3339(),
            "not_after": not_after.to_rfc3339(),
            "p_n_schema_version": RESTORE_INTENT_SCHEMA_VERSION,
        });
        let (intent_path, sig_path, verifying_key) = sign_into(dir.path(), &payload);
        // Tamper with the payload AFTER signing.
        let mut bytes = fs::read(&intent_path).unwrap();
        bytes[0] = bytes[0].wrapping_add(1);
        fs::write(&intent_path, &bytes).unwrap();

        let expected = ExpectedIntent {
            deployment_id: "dep-1",
            active_db_path: &active_db,
            active_event_log_path: &active_jsonl,
            backup_manifest_blake3: "blake3:aa",
            staged_sqlite_blake3: "blake3:bb",
            staged_jsonl_blake3: "blake3:cc",
            now: now(),
            verifying_key,
            verifying_key_fingerprint: "fp",
        };
        // Tampering can either invalidate JSON or the signature; both are
        // verifier-rejection paths and that is the contract under test.
        match verify_restore_intent(&intent_path, &sig_path, &expected) {
            Err(IntentError::BadSignature) | Err(IntentError::Malformed { .. }) => {}
            other => panic!("expected BadSignature or Malformed, got {other:?}"),
        }
    }

    /// Closes Attack A (`docs/reviews/RED_TEAM_2026-05-12_post_8f43450.md`).
    /// An attacker who mints a fresh keypair and hand-picks an
    /// `operator_principal_id` distinct from the deterministic
    /// derivation MUST be refused by the verifier, even with a valid
    /// Ed25519 signature over the canonical bytes.
    #[test]
    fn verify_restore_intent_refuses_principal_not_bound_to_key() {
        let dir = tempfile::tempdir().unwrap();
        let active_db = dir.path().join("cortex.db");
        let active_jsonl = dir.path().join("events.jsonl");
        fs::write(&active_db, b"db").unwrap();
        fs::write(&active_jsonl, b"jsonl").unwrap();

        // The attacker mints a fresh keypair (the fixture key here) and
        // claims a principal id distinct from the structural derivation.
        // The signature itself is valid: the attacker controls the
        // private half. The new binding check must still refuse.
        let not_before = now() - chrono::Duration::seconds(60);
        let not_after = now() + chrono::Duration::seconds(60);
        let forged_principal = "operator:trusted-incident-responder";
        let derived_principal = fixture_principal_id();
        assert_ne!(
            forged_principal, derived_principal,
            "test premise: forged principal must differ from the derived one",
        );
        let payload = serde_json::json!({
            "kind": RESTORE_INTENT_KIND,
            "schema_version": RESTORE_INTENT_SCHEMA_VERSION,
            "deployment_id": "dep-1",
            "active_db_path": active_db,
            "active_event_log_path": active_jsonl,
            "backup_manifest_blake3": "blake3:aa",
            "staged_sqlite_blake3": "blake3:bb",
            "staged_jsonl_blake3": "blake3:cc",
            "operator_principal_id": forged_principal,
            "not_before": not_before.to_rfc3339(),
            "not_after": not_after.to_rfc3339(),
            "p_n_schema_version": RESTORE_INTENT_SCHEMA_VERSION,
        });
        let (intent_path, sig_path, verifying_key) = sign_into(dir.path(), &payload);

        let expected = ExpectedIntent {
            deployment_id: "dep-1",
            active_db_path: &active_db,
            active_event_log_path: &active_jsonl,
            backup_manifest_blake3: "blake3:aa",
            staged_sqlite_blake3: "blake3:bb",
            staged_jsonl_blake3: "blake3:cc",
            now: now(),
            verifying_key,
            verifying_key_fingerprint: "fp",
        };
        match verify_restore_intent(&intent_path, &sig_path, &expected) {
            Err(IntentError::KeyMismatch {
                payload_principal,
                derived_principal: observed_derived,
            }) => {
                assert_eq!(payload_principal, forged_principal);
                assert_eq!(observed_derived, derived_principal);
                let rendered = IntentError::KeyMismatch {
                    payload_principal,
                    derived_principal: observed_derived,
                }
                .to_string();
                assert!(
                    rendered.contains(RESTORE_INTENT_PRINCIPAL_NOT_BOUND_INVARIANT),
                    "Display impl must surface the stable invariant; got: {rendered}",
                );
            }
            other => {
                panic!("expected KeyMismatch (structural binding fail-closed); got {other:?}",)
            }
        }
    }

    #[test]
    fn derive_operator_principal_id_is_deterministic_and_prefixed() {
        let vk = fixture_signing_key().verifying_key();
        let principal = derive_operator_principal_id(&vk.to_bytes());
        assert!(principal.starts_with(OPERATOR_PRINCIPAL_PREFIX));
        // Re-derivation is byte-stable across calls.
        assert_eq!(principal, derive_operator_principal_id(&vk.to_bytes()));
        // Hex portion is exactly OPERATOR_PRINCIPAL_FINGERPRINT_HEX_LEN
        // (64) chars — the full BLAKE3 digest, no truncation.
        let hex_part = principal.strip_prefix(OPERATOR_PRINCIPAL_PREFIX).unwrap();
        assert_eq!(hex_part.len(), OPERATOR_PRINCIPAL_FINGERPRINT_HEX_LEN);
        assert!(hex_part.chars().all(|c| c.is_ascii_hexdigit()));
    }

    /// Format-length pin: this constant is referenced by external
    /// signers (the production restore drill script and any caller that
    /// reproduces the derivation outside this crate). Changing it is a
    /// wire-format change and must be co-ordinated; this test fails
    /// loudly if the constant drifts unexpectedly.
    #[test]
    fn operator_principal_fingerprint_hex_len_is_full_blake3_digest() {
        // 32-byte BLAKE3 output rendered as lowercase hex = 64 chars.
        assert_eq!(OPERATOR_PRINCIPAL_FINGERPRINT_HEX_LEN, 64);
        let vk = fixture_signing_key().verifying_key();
        let principal = derive_operator_principal_id(&vk.to_bytes());
        let hex_part = principal.strip_prefix(OPERATOR_PRINCIPAL_PREFIX).unwrap();
        // Sanity: full digest matches blake3 of the key bytes directly.
        let expected_hex = blake3::hash(&vk.to_bytes()).to_hex().to_string();
        assert_eq!(hex_part, expected_hex.as_str());
        assert_eq!(hex_part.len(), 64);
    }
}