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
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
//! `cortex restore intent build` — mint a canonical `RESTORE_INTENT` JSON
//! payload (and optionally sign it) for the production destructive
//! restore path.
//!
//! Closes one of the `docs/RUNBOOK_PRODUCTION_RESTORE_DRILL.md` §9 known
//! gaps: until this surface landed, the playbook fell back to inline
//! Python (`scripts/restore-drill-production.sh` lines ~455-640) to mint
//! the byte-for-byte canonical payload. The Rust path matches that
//! Python signer byte-for-byte: same canonical JSON encoding
//! (`serde_json` with sorted keys + no whitespace), same
//! deployment-id derivation, same operator-principal binding from the
//! Ed25519 verifying key.
//!
//! ## Contract
//!
//! - The output JSON file MUST be the byte-exact payload that the
//!   verifier hashes. Pretty-printing after writing breaks the contract;
//!   this command writes minified JSON with sorted keys and never
//!   re-serializes.
//! - With `--sign`, the same invocation derives the operator principal
//!   id from the Ed25519 verifying key bytes (Attack A closure — see
//!   `cmd::restore::intent::derive_operator_principal_id`), writes the
//!   payload, signs the on-disk bytes, and emits a sibling `.sig` file.
//! - Without `--sign`, the payload still respects the principal-binding
//!   contract: `--operator-pubkey-hex` is required so the minted
//!   `operator_principal_id` is the deterministic derivation from the
//!   bound key. Mismatch is structurally impossible.
//! - The validity window defaults to `[now - 5 min, now + 1 h]`. The
//!   playbook §3.4 ceiling is 24h; `--expires-in-hours` rejects values
//!   above 24.

use std::fs;
use std::io::{self, Read};
use std::path::{Path, PathBuf};

use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use chrono::{Duration, Utc};
use clap::Args;
use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
use serde::Serialize;
use serde_json::json;

use crate::cmd::restore::intent::{
    derive_operator_principal_id, RESTORE_INTENT_KIND, RESTORE_INTENT_SCHEMA_VERSION,
};
use crate::cmd::restore::production::deployment_id_for;
use crate::exit::Exit;
use crate::output::{self, Envelope};
use crate::paths::DataLayout;

/// Maximum operator-configurable validity window in hours. The playbook
/// §3.4 ceiling is 24h; the verifier itself does not enforce this but the
/// drill discipline does, so the minter refuses larger windows up front.
pub const MAX_VALIDITY_WINDOW_HOURS: i64 = 24;

/// Default validity window (1 hour). The playbook §3.4 norm.
pub const DEFAULT_VALIDITY_WINDOW_HOURS: i64 = 1;

/// Backwards-clock skew (5 minutes) applied to `not_before` so a payload
/// minted on a slightly-fast clock still enters its validity window on
/// the verifier host.
pub const NOT_BEFORE_SKEW_SECONDS: i64 = 5 * 60;

/// Stable invariant emitted when the operator pubkey could not be parsed
/// (wrong length, non-hex, or not a valid Ed25519 verifying key).
pub const INTENT_BUILD_PUBKEY_MALFORMED_INVARIANT: &str = "restore.intent.build.pubkey_malformed";

/// Stable invariant emitted when a staged-artifact pair has an unequal
/// number of `--staged-artifact-digest-blake3` and `--staged-artifact-path`
/// flags.
pub const INTENT_BUILD_STAGED_PAIRS_MISMATCH_INVARIANT: &str =
    "restore.intent.build.staged_pairs.mismatch";

/// Stable invariant emitted when the operator-supplied validity window is
/// outside the `[1, 24]` hour band the playbook ratifies.
pub const INTENT_BUILD_VALIDITY_WINDOW_INVALID_INVARIANT: &str =
    "restore.intent.build.validity_window.invalid";

/// Stable invariant emitted when the signing-key value cannot be parsed.
pub const INTENT_BUILD_SIGNING_KEY_MALFORMED_INVARIANT: &str =
    "restore.intent.build.signing_key.malformed";

/// Stable invariant emitted when `--sign` is supplied without
/// `--signing-key-b64` (or vice versa).
pub const INTENT_BUILD_SIGN_FLAG_INCONSISTENT_INVARIANT: &str =
    "restore.intent.build.sign_flag.inconsistent";

/// Stable invariant emitted when `--operator-pubkey-hex` and a derived
/// pubkey from `--signing-key-b64` disagree (operator passed both and they
/// do not bind to the same Ed25519 keypair).
pub const INTENT_BUILD_KEY_MATERIAL_DISAGREE_INVARIANT: &str =
    "restore.intent.build.key_material.disagree";

/// Stable invariant emitted when the output file already exists. The
/// minter refuses to clobber: a stale payload could be valid for a
/// different cutover.
pub const INTENT_BUILD_OUTPUT_ALREADY_EXISTS_INVARIANT: &str =
    "restore.intent.build.output.already_exists";

/// `cortex restore intent build` arguments.
#[derive(Debug, Args)]
pub struct BuildArgs {
    /// 64-hex-char operator Ed25519 verifying key. Optional only when
    /// `--sign` is supplied (the pubkey is then derived from the signing
    /// seed); otherwise required so the principal binding can be
    /// computed.
    #[arg(long, value_name = "HEX")]
    pub operator_pubkey_hex: Option<String>,
    /// Deployment id to bind into the payload. Defaults to the
    /// deterministic derivation from the resolved data directory (same
    /// rule `cortex doctor --print-deployment-id` emits).
    #[arg(long, value_name = "DEPLOYMENT_ID")]
    pub deployment_id: Option<String>,
    /// Backup manifest path. The minter computes BLAKE3 over the on-disk
    /// bytes and writes `blake3:<hex>` into the payload.
    #[arg(long, value_name = "PATH")]
    pub backup_manifest: PathBuf,
    /// Staged SQLite artifact path. Repeat together with
    /// `--staged-artifact-digest-blake3` to bind both the SQLite and
    /// JSONL digests. The order is positional: first pair feeds
    /// `staged_sqlite_blake3`, second pair feeds `staged_jsonl_blake3`.
    #[arg(long = "staged-artifact-path", value_name = "PATH")]
    pub staged_artifact_paths: Vec<PathBuf>,
    /// Staged artifact BLAKE3 digest (`blake3:<hex>`). Pair with
    /// `--staged-artifact-path`; the operator may supply 0 or 2 pairs.
    /// When zero, the minter computes the digests from the paired path
    /// at write time; when two, the digests in the payload are the
    /// operator-declared values verbatim.
    #[arg(long = "staged-artifact-digest-blake3", value_name = "BLAKE3_HEX")]
    pub staged_artifact_digests_blake3: Vec<String>,
    /// Validity window in hours. Default 1; max 24 (playbook §3.4).
    #[arg(long, value_name = "HOURS", default_value_t = DEFAULT_VALIDITY_WINDOW_HOURS)]
    pub expires_in_hours: i64,
    /// Sign the minted payload bytes in the same invocation. Requires
    /// `--signing-key-b64`; emits a sibling `.sig` file next to `--output`.
    #[arg(long)]
    pub sign: bool,
    /// Base64-encoded 32-byte Ed25519 signing seed. Pass `-` to read
    /// the base64 string from stdin (no trailing newline required) so
    /// the secret is never visible in `argv`.
    #[arg(long, value_name = "BASE64_OR_DASH")]
    pub signing_key_b64: Option<String>,
    /// Destination for the canonical RESTORE_INTENT JSON. Refuses if the
    /// file already exists. With `--sign`, the sibling `.sig` lands next
    /// to it (file stem `+ ".sig"`).
    #[arg(long, value_name = "PATH")]
    pub output: PathBuf,
}

/// Run `cortex restore intent build`.
pub fn run(args: BuildArgs) -> Exit {
    let json = output::json_enabled();

    if args.expires_in_hours < 1 || args.expires_in_hours > MAX_VALIDITY_WINDOW_HOURS {
        let detail = format!(
            "validity window must be in [1, {MAX_VALIDITY_WINDOW_HOURS}] hours; got {}",
            args.expires_in_hours
        );
        eprintln!(
            "cortex restore intent build: invariant={INTENT_BUILD_VALIDITY_WINDOW_INVALID_INVARIANT} {detail}"
        );
        return finish(
            Exit::Usage,
            &detail,
            Some(INTENT_BUILD_VALIDITY_WINDOW_INVALID_INVARIANT),
            &args.output,
            None,
            json,
        );
    }

    if args.staged_artifact_paths.len() != args.staged_artifact_digests_blake3.len() {
        let detail = format!(
            "--staged-artifact-path count ({}) must equal --staged-artifact-digest-blake3 count ({})",
            args.staged_artifact_paths.len(),
            args.staged_artifact_digests_blake3.len(),
        );
        eprintln!(
            "cortex restore intent build: invariant={INTENT_BUILD_STAGED_PAIRS_MISMATCH_INVARIANT} {detail}"
        );
        return finish(
            Exit::Usage,
            &detail,
            Some(INTENT_BUILD_STAGED_PAIRS_MISMATCH_INVARIANT),
            &args.output,
            None,
            json,
        );
    }
    if !args.staged_artifact_paths.is_empty() && args.staged_artifact_paths.len() != 2 {
        let detail = format!(
            "exactly 0 or 2 --staged-artifact-path/--staged-artifact-digest-blake3 pairs required (first=sqlite, second=jsonl); got {} pairs",
            args.staged_artifact_paths.len()
        );
        eprintln!(
            "cortex restore intent build: invariant={INTENT_BUILD_STAGED_PAIRS_MISMATCH_INVARIANT} {detail}"
        );
        return finish(
            Exit::Usage,
            &detail,
            Some(INTENT_BUILD_STAGED_PAIRS_MISMATCH_INVARIANT),
            &args.output,
            None,
            json,
        );
    }

    if args.sign != args.signing_key_b64.is_some() {
        let detail = "--sign and --signing-key-b64 must be supplied together".to_string();
        eprintln!(
            "cortex restore intent build: invariant={INTENT_BUILD_SIGN_FLAG_INCONSISTENT_INVARIANT} {detail}"
        );
        return finish(
            Exit::Usage,
            &detail,
            Some(INTENT_BUILD_SIGN_FLAG_INCONSISTENT_INVARIANT),
            &args.output,
            None,
            json,
        );
    }

    if args.output.exists() {
        let detail = format!(
            "refusing to overwrite existing --output `{}`",
            args.output.display()
        );
        eprintln!(
            "cortex restore intent build: invariant={INTENT_BUILD_OUTPUT_ALREADY_EXISTS_INVARIANT} {detail}"
        );
        return finish(
            Exit::PreconditionUnmet,
            &detail,
            Some(INTENT_BUILD_OUTPUT_ALREADY_EXISTS_INVARIANT),
            &args.output,
            None,
            json,
        );
    }

    // Resolve key material. Either the operator passed `--operator-pubkey-hex`,
    // or they passed `--sign --signing-key-b64 <B64>` and we derive the
    // verifying key from the seed. If both, we verify they agree.
    let signing_key = match args.signing_key_b64.as_deref() {
        Some(value) => match resolve_signing_key(value) {
            Ok(key) => Some(key),
            Err(detail) => {
                eprintln!(
                    "cortex restore intent build: invariant={INTENT_BUILD_SIGNING_KEY_MALFORMED_INVARIANT} {detail}"
                );
                return finish(
                    Exit::PreconditionUnmet,
                    &detail,
                    Some(INTENT_BUILD_SIGNING_KEY_MALFORMED_INVARIANT),
                    &args.output,
                    None,
                    json,
                );
            }
        },
        None => None,
    };

    let verifying_key = match (&args.operator_pubkey_hex, &signing_key) {
        (Some(hex), Some(sk)) => {
            let supplied = match parse_pubkey_hex(hex) {
                Ok(key) => key,
                Err(detail) => {
                    eprintln!(
                        "cortex restore intent build: invariant={INTENT_BUILD_PUBKEY_MALFORMED_INVARIANT} {detail}"
                    );
                    return finish(
                        Exit::PreconditionUnmet,
                        &detail,
                        Some(INTENT_BUILD_PUBKEY_MALFORMED_INVARIANT),
                        &args.output,
                        None,
                        json,
                    );
                }
            };
            let derived = sk.verifying_key();
            if supplied.to_bytes() != derived.to_bytes() {
                let detail = "--operator-pubkey-hex does not match the verifying key derived from --signing-key-b64".to_string();
                eprintln!(
                    "cortex restore intent build: invariant={INTENT_BUILD_KEY_MATERIAL_DISAGREE_INVARIANT} {detail}"
                );
                return finish(
                    Exit::PreconditionUnmet,
                    &detail,
                    Some(INTENT_BUILD_KEY_MATERIAL_DISAGREE_INVARIANT),
                    &args.output,
                    None,
                    json,
                );
            }
            supplied
        }
        (Some(hex), None) => match parse_pubkey_hex(hex) {
            Ok(key) => key,
            Err(detail) => {
                eprintln!(
                    "cortex restore intent build: invariant={INTENT_BUILD_PUBKEY_MALFORMED_INVARIANT} {detail}"
                );
                return finish(
                    Exit::PreconditionUnmet,
                    &detail,
                    Some(INTENT_BUILD_PUBKEY_MALFORMED_INVARIANT),
                    &args.output,
                    None,
                    json,
                );
            }
        },
        (None, Some(sk)) => sk.verifying_key(),
        (None, None) => {
            let detail =
                "either --operator-pubkey-hex or --sign --signing-key-b64 must be supplied"
                    .to_string();
            eprintln!(
                "cortex restore intent build: invariant={INTENT_BUILD_PUBKEY_MALFORMED_INVARIANT} {detail}"
            );
            return finish(
                Exit::Usage,
                &detail,
                Some(INTENT_BUILD_PUBKEY_MALFORMED_INVARIANT),
                &args.output,
                None,
                json,
            );
        }
    };

    let operator_principal_id = derive_operator_principal_id(&verifying_key.to_bytes());

    let layout = match DataLayout::resolve(None, None) {
        Ok(layout) => layout,
        Err(exit) => {
            let detail = "failed to resolve data layout".to_string();
            eprintln!("cortex restore intent build: {detail}");
            return finish(exit, &detail, None, &args.output, None, json);
        }
    };
    let deployment_id = args
        .deployment_id
        .clone()
        .unwrap_or_else(|| deployment_id_for(&layout));

    // Compute backup manifest digest from on-disk bytes.
    let manifest_bytes = match fs::read(&args.backup_manifest) {
        Ok(bytes) => bytes,
        Err(err) => {
            let detail = format!(
                "cannot read --backup-manifest `{}`: {err}",
                args.backup_manifest.display()
            );
            eprintln!("cortex restore intent build: {detail}");
            return finish(
                Exit::PreconditionUnmet,
                &detail,
                None,
                &args.output,
                None,
                json,
            );
        }
    };
    let manifest_b3 = format!("blake3:{}", blake3::hash(&manifest_bytes).to_hex());

    // Compute / accept staged digests.
    let (staged_sqlite_b3, staged_jsonl_b3) = if args.staged_artifact_paths.is_empty() {
        // Fallback: try to read the manifest as JSON and extract the
        // declared staged digests (mirroring the drill orchestrator).
        match extract_staged_digests_from_manifest(&manifest_bytes) {
            Some(pair) => pair,
            None => {
                let detail = "no --staged-artifact-path supplied and --backup-manifest does not declare sqlite_store_blake3 + jsonl_mirror_blake3".to_string();
                eprintln!("cortex restore intent build: {detail}");
                return finish(
                    Exit::PreconditionUnmet,
                    &detail,
                    None,
                    &args.output,
                    None,
                    json,
                );
            }
        }
    } else {
        (
            args.staged_artifact_digests_blake3[0].clone(),
            args.staged_artifact_digests_blake3[1].clone(),
        )
    };

    let active_db_path = canonicalize_string(&layout.db_path);
    let active_event_log_path = canonicalize_string(&layout.event_log_path);

    let now = Utc::now();
    let not_before = now - Duration::seconds(NOT_BEFORE_SKEW_SECONDS);
    let not_after = now + Duration::hours(args.expires_in_hours);

    let payload = RestoreIntentPayloadView {
        active_db_path: active_db_path.clone(),
        active_event_log_path: active_event_log_path.clone(),
        backup_manifest_blake3: manifest_b3.clone(),
        deployment_id: deployment_id.clone(),
        kind: RESTORE_INTENT_KIND.to_string(),
        not_after: not_after.to_rfc3339(),
        not_before: not_before.to_rfc3339(),
        operator_principal_id: operator_principal_id.clone(),
        p_n_schema_version: RESTORE_INTENT_SCHEMA_VERSION,
        schema_version: RESTORE_INTENT_SCHEMA_VERSION,
        staged_jsonl_blake3: staged_jsonl_b3.clone(),
        staged_sqlite_blake3: staged_sqlite_b3.clone(),
    };

    // Canonical bytes: serde_json with sorted keys (the struct fields are
    // declared in alphabetical order so the Serde output is the canonical
    // form). No pretty-printing; the verifier hashes these bytes verbatim.
    let canonical_bytes = match serde_json::to_vec(&payload) {
        Ok(bytes) => bytes,
        Err(err) => {
            eprintln!("cortex restore intent build: failed to serialize payload: {err}");
            return finish(
                Exit::Internal,
                &err.to_string(),
                None,
                &args.output,
                None,
                json,
            );
        }
    };

    if let Err(err) = fs::write(&args.output, &canonical_bytes) {
        let detail = format!("cannot write --output `{}`: {err}", args.output.display());
        eprintln!("cortex restore intent build: {detail}");
        return finish(Exit::Internal, &detail, None, &args.output, None, json);
    }

    let mut signature_path: Option<PathBuf> = None;
    if let Some(sk) = signing_key.as_ref() {
        let sig_path = sibling_sig_path(&args.output);
        if sig_path.exists() {
            let detail = format!(
                "refusing to overwrite existing signature `{}`",
                sig_path.display()
            );
            eprintln!(
                "cortex restore intent build: invariant={INTENT_BUILD_OUTPUT_ALREADY_EXISTS_INVARIANT} {detail}"
            );
            // Roll back the payload we just wrote so the caller does not see
            // a half-emitted pair.
            let _ = fs::remove_file(&args.output);
            return finish(
                Exit::PreconditionUnmet,
                &detail,
                Some(INTENT_BUILD_OUTPUT_ALREADY_EXISTS_INVARIANT),
                &args.output,
                Some(&sig_path),
                json,
            );
        }
        let signature = sk.sign(&canonical_bytes);
        if let Err(err) = fs::write(&sig_path, signature.to_bytes()) {
            let detail = format!("cannot write signature `{}`: {err}", sig_path.display());
            eprintln!("cortex restore intent build: {detail}");
            let _ = fs::remove_file(&args.output);
            return finish(Exit::Internal, &detail, None, &args.output, None, json);
        }
        signature_path = Some(sig_path);
    }

    if !json {
        println!(
            "cortex restore intent build: minted `{}` (operator_principal_id={operator_principal_id})",
            args.output.display()
        );
        if let Some(sig_path) = signature_path.as_ref() {
            println!(
                "cortex restore intent build: signed -> `{}`",
                sig_path.display()
            );
        }
    }

    finish_ok(
        &payload,
        &canonical_bytes,
        verifying_key,
        &args.output,
        signature_path.as_deref(),
        json,
    )
}

#[derive(Debug, Serialize)]
struct RestoreIntentPayloadView {
    // Field order is alphabetical so the default `serde_json` encoding is
    // byte-stable across builds and matches the Python signer in
    // `scripts/restore-drill-production.sh`, which uses `sort_keys=True`.
    active_db_path: String,
    active_event_log_path: String,
    backup_manifest_blake3: String,
    deployment_id: String,
    kind: String,
    not_after: String,
    not_before: String,
    operator_principal_id: String,
    p_n_schema_version: u16,
    schema_version: u16,
    staged_jsonl_blake3: String,
    staged_sqlite_blake3: String,
}

fn sibling_sig_path(intent_path: &Path) -> PathBuf {
    let mut path = intent_path.to_path_buf();
    let stem = path
        .file_stem()
        .map(|s| s.to_owned())
        .unwrap_or_else(|| std::ffi::OsString::from("RESTORE_INTENT"));
    let mut sig_name = stem;
    sig_name.push(".sig");
    path.set_file_name(sig_name);
    path
}

fn canonicalize_string(path: &Path) -> String {
    path.canonicalize()
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or_else(|_| path.to_string_lossy().into_owned())
}

fn resolve_signing_key(value: &str) -> Result<SigningKey, String> {
    let b64 = if value == "-" {
        let mut buf = String::new();
        io::stdin()
            .read_to_string(&mut buf)
            .map_err(|err| format!("cannot read --signing-key-b64 from stdin: {err}"))?;
        buf.trim().to_string()
    } else {
        value.trim().to_string()
    };
    let raw = STANDARD
        .decode(b64.as_bytes())
        .map_err(|err| format!("--signing-key-b64 is not valid base64: {err}"))?;
    let seed: [u8; 32] = raw.as_slice().try_into().map_err(|_| {
        format!(
            "--signing-key-b64 must decode to 32 bytes (Ed25519 seed); got {}",
            raw.len()
        )
    })?;
    Ok(SigningKey::from_bytes(&seed))
}

fn parse_pubkey_hex(hex_str: &str) -> Result<VerifyingKey, String> {
    let hex_str = hex_str.trim();
    if hex_str.len() != 64 {
        return Err(format!(
            "--operator-pubkey-hex must be exactly 64 hex chars (32 bytes); got {}",
            hex_str.len()
        ));
    }
    let mut bytes = [0u8; 32];
    for (i, byte) in bytes.iter_mut().enumerate() {
        let chunk = &hex_str[2 * i..2 * i + 2];
        *byte = u8::from_str_radix(chunk, 16)
            .map_err(|err| format!("--operator-pubkey-hex chunk `{chunk}` is not hex: {err}"))?;
    }
    VerifyingKey::from_bytes(&bytes)
        .map_err(|err| format!("--operator-pubkey-hex is not a valid Ed25519 verifying key: {err}"))
}

/// Extract the `sqlite_store_blake3` + `jsonl_mirror_blake3` fields from a
/// backup-manifest JSON document, in the manifest's wire shape. Returns
/// `None` if either field is missing or not a string.
fn extract_staged_digests_from_manifest(bytes: &[u8]) -> Option<(String, String)> {
    let value: serde_json::Value = serde_json::from_slice(bytes).ok()?;
    let sqlite = value.get("sqlite_store_blake3")?.as_str()?.to_string();
    let jsonl = value.get("jsonl_mirror_blake3")?.as_str()?.to_string();
    Some((sqlite, jsonl))
}

fn finish(
    exit: Exit,
    detail: &str,
    invariant: Option<&'static str>,
    output: &Path,
    signature: Option<&Path>,
    json: bool,
) -> Exit {
    if !json {
        return exit;
    }
    let report = json!({
        "command": "cortex.restore.intent.build",
        "detail": detail,
        "invariant": invariant,
        "output_path": output.display().to_string(),
        "signature_path": signature.map(|p| p.display().to_string()),
        "persisted": false,
    });
    let envelope = Envelope::new("cortex.restore.intent.build", exit, report);
    output::emit(&envelope, exit)
}

fn finish_ok(
    payload: &RestoreIntentPayloadView,
    canonical_bytes: &[u8],
    verifying_key: VerifyingKey,
    output: &Path,
    signature: Option<&Path>,
    json: bool,
) -> Exit {
    if !json {
        return Exit::Ok;
    }
    let pubkey_hex = lowercase_hex(verifying_key.as_bytes());
    let canonical_blake3 = format!("blake3:{}", blake3::hash(canonical_bytes).to_hex());
    let report = json!({
        "command": "cortex.restore.intent.build",
        "output_path": output.display().to_string(),
        "signature_path": signature.map(|p| p.display().to_string()),
        "canonical_bytes_len": canonical_bytes.len(),
        "canonical_blake3": canonical_blake3,
        "operator_pubkey_hex": pubkey_hex,
        "payload": payload,
        "persisted": true,
    });
    let envelope = Envelope::new("cortex.restore.intent.build", Exit::Ok, report);
    output::emit(&envelope, Exit::Ok)
}

fn lowercase_hex(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        out.push(HEX[(byte >> 4) as usize] as char);
        out.push(HEX[(byte & 0x0f) as usize] as char);
    }
    out
}

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

    fn write_minimal_manifest(dir: &Path) -> PathBuf {
        let path = dir.join("BACKUP_MANIFEST");
        let manifest = json!({
            "kind": "cortex_pre_v2_backup",
            "schema_version": 1,
            "sqlite_store": "cortex.db",
            "jsonl_mirror": "events.jsonl",
            "tool_version": "test",
            "backup_timestamp": "2026-05-12T00:00:00Z",
            "sqlite_store_size_bytes": 0,
            "sqlite_store_blake3": "blake3:aa",
            "jsonl_mirror_size_bytes": 0,
            "jsonl_mirror_blake3": "blake3:bb",
        });
        fs::write(&path, serde_json::to_vec_pretty(&manifest).unwrap()).unwrap();
        path
    }

    fn seed_to_b64(seed: [u8; 32]) -> String {
        STANDARD.encode(seed)
    }

    fn pubkey_hex_from_seed(seed: [u8; 32]) -> String {
        let sk = SigningKey::from_bytes(&seed);
        lowercase_hex(sk.verifying_key().as_bytes())
    }

    #[test]
    fn build_unsigned_minted_payload_round_trips_through_serde() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = write_minimal_manifest(dir.path());
        let output = dir.path().join("RESTORE_INTENT.json");
        let pubkey_hex = pubkey_hex_from_seed([3u8; 32]);

        let args = BuildArgs {
            operator_pubkey_hex: Some(pubkey_hex.clone()),
            deployment_id: Some("deployment:test".to_string()),
            backup_manifest: manifest,
            staged_artifact_paths: Vec::new(),
            staged_artifact_digests_blake3: Vec::new(),
            expires_in_hours: 1,
            sign: false,
            signing_key_b64: None,
            output: output.clone(),
        };

        let exit = run(args);
        assert_eq!(exit, Exit::Ok);

        let bytes = fs::read(&output).unwrap();
        let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(value["kind"], "cortex_restore_intent");
        assert_eq!(value["deployment_id"], "deployment:test");
        let principal = value["operator_principal_id"].as_str().unwrap();
        assert!(
            principal.starts_with("operator:"),
            "principal must use the operator: prefix; got {principal}"
        );
        // Round-trip: the derived principal must match what
        // `derive_operator_principal_id` would compute for the bound
        // verifying key.
        let mut pk_bytes = [0u8; 32];
        for (i, byte) in pk_bytes.iter_mut().enumerate() {
            *byte = u8::from_str_radix(&pubkey_hex[2 * i..2 * i + 2], 16).unwrap();
        }
        assert_eq!(principal, derive_operator_principal_id(&pk_bytes));
    }

    #[test]
    fn build_with_sign_produces_round_trippable_signature() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = write_minimal_manifest(dir.path());
        let output = dir.path().join("RESTORE_INTENT.json");
        let seed = [11u8; 32];

        let args = BuildArgs {
            operator_pubkey_hex: None,
            deployment_id: Some("deployment:test".to_string()),
            backup_manifest: manifest,
            staged_artifact_paths: Vec::new(),
            staged_artifact_digests_blake3: Vec::new(),
            expires_in_hours: 1,
            sign: true,
            signing_key_b64: Some(seed_to_b64(seed)),
            output: output.clone(),
        };

        let exit = run(args);
        assert_eq!(exit, Exit::Ok);

        let canonical_bytes = fs::read(&output).unwrap();
        let sig_path = sibling_sig_path(&output);
        assert!(sig_path.exists(), "expected sibling .sig at {sig_path:?}");

        let sig_bytes = fs::read(&sig_path).unwrap();
        assert_eq!(sig_bytes.len(), 64, "Ed25519 signature must be 64 bytes");

        let sk = SigningKey::from_bytes(&seed);
        let vk = sk.verifying_key();
        let sig_array: [u8; 64] = sig_bytes.as_slice().try_into().unwrap();
        let signature = ed25519_dalek::Signature::from_bytes(&sig_array);
        vk.verify(&canonical_bytes, &signature)
            .expect("signature must verify against the derived public key");

        // Principal id must derive from the same key the signer used.
        let value: serde_json::Value = serde_json::from_slice(&canonical_bytes).unwrap();
        let principal = value["operator_principal_id"].as_str().unwrap();
        assert_eq!(principal, derive_operator_principal_id(&vk.to_bytes()));
    }

    #[test]
    fn build_refuses_when_validity_window_exceeds_ceiling() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = write_minimal_manifest(dir.path());
        let output = dir.path().join("RESTORE_INTENT.json");

        let args = BuildArgs {
            operator_pubkey_hex: Some(pubkey_hex_from_seed([5u8; 32])),
            deployment_id: Some("deployment:test".to_string()),
            backup_manifest: manifest,
            staged_artifact_paths: Vec::new(),
            staged_artifact_digests_blake3: Vec::new(),
            expires_in_hours: 48,
            sign: false,
            signing_key_b64: None,
            output: output.clone(),
        };
        let exit = run(args);
        assert_eq!(exit, Exit::Usage);
        assert!(
            !output.exists(),
            "no output must be written when the validity window is refused"
        );
    }

    #[test]
    fn build_refuses_when_signing_key_and_pubkey_disagree() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = write_minimal_manifest(dir.path());
        let output = dir.path().join("RESTORE_INTENT.json");

        let args = BuildArgs {
            operator_pubkey_hex: Some(pubkey_hex_from_seed([7u8; 32])),
            deployment_id: Some("deployment:test".to_string()),
            backup_manifest: manifest,
            staged_artifact_paths: Vec::new(),
            staged_artifact_digests_blake3: Vec::new(),
            expires_in_hours: 1,
            sign: true,
            signing_key_b64: Some(seed_to_b64([8u8; 32])),
            output: output.clone(),
        };

        let exit = run(args);
        assert_eq!(exit, Exit::PreconditionUnmet);
        assert!(!output.exists(), "no output on key-material disagreement");
    }

    #[test]
    fn build_refuses_when_output_already_exists() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = write_minimal_manifest(dir.path());
        let output = dir.path().join("RESTORE_INTENT.json");
        fs::write(&output, b"pre-existing").unwrap();

        let args = BuildArgs {
            operator_pubkey_hex: Some(pubkey_hex_from_seed([2u8; 32])),
            deployment_id: Some("deployment:test".to_string()),
            backup_manifest: manifest,
            staged_artifact_paths: Vec::new(),
            staged_artifact_digests_blake3: Vec::new(),
            expires_in_hours: 1,
            sign: false,
            signing_key_b64: None,
            output: output.clone(),
        };
        let exit = run(args);
        assert_eq!(exit, Exit::PreconditionUnmet);
        let after = fs::read(&output).unwrap();
        assert_eq!(after, b"pre-existing");
    }

    #[test]
    fn build_refuses_when_staged_pairs_unbalanced() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = write_minimal_manifest(dir.path());
        let output = dir.path().join("RESTORE_INTENT.json");

        let args = BuildArgs {
            operator_pubkey_hex: Some(pubkey_hex_from_seed([1u8; 32])),
            deployment_id: Some("deployment:test".to_string()),
            backup_manifest: manifest,
            staged_artifact_paths: vec![dir.path().join("staged.db")],
            staged_artifact_digests_blake3: Vec::new(),
            expires_in_hours: 1,
            sign: false,
            signing_key_b64: None,
            output: output.clone(),
        };
        let exit = run(args);
        assert_eq!(exit, Exit::Usage);
        assert!(!output.exists(), "no output when staged pairs unbalanced");
    }

    #[test]
    fn parse_pubkey_hex_rejects_wrong_length() {
        let err = parse_pubkey_hex("aabb").unwrap_err();
        assert!(err.contains("64 hex chars"), "got: {err}");
    }
}