tvc 0.13.1

CLI for Turnkey Verifiable Cloud
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
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
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
//! Approve deploy command - cryptographically approve a QOS manifest.

use crate::{
    client::build_client,
    config::turnkey::Config,
    errors::MissingResource,
    local_operator_key::LocalOperatorSeedSource,
    operator::{OperatorCtx, ResolvedOperator, resolve_operator},
    outcome::Outcome,
    output::StdCtx,
    pair::HexSeed,
    prompts::{self, bail_required_in_non_interactive, stdin_can_prompt},
    shell_print, shell_println,
    util::{read_file_to_string, write_file},
};
use anyhow::{Context, anyhow, bail};
use clap::{ArgGroup, Args as ClapArgs};
use qos_core::protocol::services::boot::{
    Approval, ManifestSet, Namespace, NitroConfig, QuorumMember, ShareSet, VersionedManifest,
};
use serde::{Serialize, Serializer};
use std::collections::HashSet;
use std::fmt::{self, Display, Formatter, Write};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use tracing::debug;
use turnkey_client::generated::external::data::v1::TvcDeployment;
use turnkey_client::generated::{
    CreateTvcManifestApprovalsIntent, GetTvcDeploymentRequest, TvcManifestApproval,
};
use uuid::Uuid;

const QUORUM_REACHED_MESSAGE: &str =
    "Manifest approval quorum reached. Your deployment will be available soon.";

/// Cryptographically approve a QOS manifest for a deployment with your operator's manifest set key.
#[derive(Debug, ClapArgs)]
#[command(about, long_about = None)]
#[command(group(ArgGroup::new("manifest-source").args(["manifest", "deploy_id"])))]
pub struct Args {
    /// Path to QOS manifest file.
    #[arg(
        short,
        long,
        value_name = "PATH",
        env = "TVC_MANIFEST",
        help_heading = "Manifest source (pick one)"
    )]
    pub manifest: Option<PathBuf>,

    /// ID of the deployment the manifest belongs to.
    #[arg(
        short,
        long,
        env = "TVC_DEPLOY_ID",
        help_heading = "Manifest source (pick one)"
    )]
    pub deploy_id: Option<Uuid>,

    /// Turnkey manifest ID (UUID) for the manifest being approved.
    /// Required when posting approval to the API.
    #[arg(long, env = "TVC_MANIFEST_ID")]
    pub manifest_id: Option<String>,

    /// Turnkey operator UUID for the approving operator. When posting without
    /// this flag, TVC selects from the last manifest's saved operator IDs. A
    /// configured hosted operator is selected by its UUID.
    #[arg(long, env = "TVC_OPERATOR_ID")]
    pub operator_id: Option<Uuid>,

    /// Hex-encoded 32-byte master seed for the operator key.
    /// If no seed flag is provided, uses the operator key from the logged-in org config.
    #[arg(
        long,
        value_name = "HEX_SEED",
        env = "TVC_OPERATOR_SEED",
        help_heading = "Operator seed (pick one)"
    )]
    pub operator_seed: Option<HexSeed>,

    /// Path to a file containing the hex-encoded master seed for the operator key.
    #[arg(
        long,
        value_name = "PATH",
        env = "TVC_OPERATOR_SEED_PATH",
        help_heading = "Operator seed (pick one)"
    )]
    pub operator_seed_path: Option<PathBuf>,

    /// Walk through manifest approval prompts but do not generate an approval.
    #[arg(long, env = "TVC_DRY_RUN")]
    pub dry_run: bool,

    /// DANGEROUS: skip interactive prompts for approving each aspect of manifest.
    #[arg(long, env = "TVC_DANGEROUS_SKIP_INTERACTIVE")]
    pub dangerous_skip_interactive: bool,

    /// Write approval to file instead of stdout.
    #[arg(short = 'o', long, value_name = "PATH", env = "TVC_APPROVAL_OUT")]
    pub approval_out: Option<PathBuf>,

    /// Generate a local-operator approval without posting it to the API. This
    /// supports offline signing and cannot be used with a hosted operator.
    #[arg(long, env = "TVC_SKIP_POST")]
    pub skip_post: bool,
}

struct PostApprovalPlan<'a> {
    manifest_id: &'a str,
    operator_id: &'a Uuid,
    deploy_id: Option<&'a str>,
}

/// What `post_approval_to_api` learned from the API: the created approval IDs
/// and whether the manifest approval quorum is now reached (`None` when the
/// post-check deployment fetch failed or was not attempted).
struct PostedApproval {
    approval_ids: Vec<String>,
    quorum_reached: Option<bool>,
}

/// Terminal shapes for `deploy approve` (reasons share the `manifest_approval_*` prefix).
pub enum ApproveOutcome {
    /// Approval generated and posted to the API.
    Posted(ApprovalPosted),
    /// Approval generated but not posted (`--skip-post`).
    NotPosted(ApprovalGenerated),
    /// `--dry-run`: manifest review completed, no approval generated.
    DryRun(ApprovalDryRun),
}

impl Serialize for ApproveOutcome {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            ApproveOutcome::Posted(msg) => msg.serialize(serializer),
            ApproveOutcome::NotPosted(msg) => msg.serialize(serializer),
            ApproveOutcome::DryRun(msg) => msg.serialize(serializer),
        }
    }
}

impl Display for ApproveOutcome {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ApproveOutcome::Posted(msg) => msg.fmt(f),
            ApproveOutcome::NotPosted(msg) => msg.fmt(f),
            ApproveOutcome::DryRun(msg) => msg.fmt(f),
        }
    }
}

/// Render the approval payload part of a human message: the pretty-printed
/// approval JSON, or the path it was written to (`--approval-out`).
fn approval_payload_human_message(
    approval: &Option<Approval>,
    written_to: &Option<String>,
) -> String {
    match (approval, written_to) {
        (Some(approval), _) => serde_json::to_string_pretty(approval)
            .expect("serializing manifest approval should not fail"),
        (None, Some(path)) => format!("Approval written to: {path}"),
        (None, None) => String::new(),
    }
}

#[derive(Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovalPosted {
    /// Present when the approval was printed inline (no `--approval-out`).
    #[serde(skip_serializing_if = "Option::is_none")]
    approval: Option<Approval>,
    /// Present when the approval was written to a file via `--approval-out`.
    #[serde(skip_serializing_if = "Option::is_none")]
    written_to: Option<String>,
    manifest_id: String,
    operator_id: String,
    approval_ids: Vec<String>,
    /// `None` when the post-check deployment fetch failed or was not
    /// attempted (no `--deploy-id`), so quorum state is unknown.
    quorum_reached: Option<bool>,
}

impl Display for ApprovalPosted {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(&approval_payload_human_message(
            &self.approval,
            &self.written_to,
        ))?;
        write!(
            f,
            r#"
Approval posted successfully!

Approval IDs: {:?}
Manifest ID: {}
Operator ID: {}"#,
            self.approval_ids, self.manifest_id, self.operator_id
        )?;

        if let Some(reached) = self.quorum_reached {
            let quorum_line = if reached {
                QUORUM_REACHED_MESSAGE
            } else {
                "Your approval has been posted. Deployment requires additional manifest approvals before it can be deployed on TVC."
            };
            write!(f, "\n\n{quorum_line}")?;
        }

        Ok(())
    }
}

#[derive(Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovalGenerated {
    /// Present when the approval was printed inline (no `--approval-out`).
    #[serde(skip_serializing_if = "Option::is_none")]
    approval: Option<Approval>,
    /// Present when the approval was written to a file via `--approval-out`.
    #[serde(skip_serializing_if = "Option::is_none")]
    written_to: Option<String>,
}

impl Display for ApprovalGenerated {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(&approval_payload_human_message(
            &self.approval,
            &self.written_to,
        ))
    }
}

#[derive(Default, Serialize)]
pub struct ApprovalDryRun {}

impl Display for ApprovalDryRun {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str("Dry run complete. No approval generated.")
    }
}

struct PostTarget {
    manifest_id: String,
    deploy_id: Option<String>,
}

struct ResolvedApproveInputs {
    manifest: VersionedManifest,
    operator_seed_source: Option<LocalOperatorSeedSource>,
    operator_id: Option<Uuid>,
    approval_out: Option<PathBuf>,
    dry_run: bool,
    skip_post: bool,
    post_target: Option<PostTarget>,
}

pub async fn run(ctx: &mut StdCtx, mut args: Args) -> anyhow::Result<Outcome> {
    let operator_seed_source = LocalOperatorSeedSource::from_args(
        args.operator_seed.take(),
        args.operator_seed_path.take(),
    )?;

    let inputs = if ctx.is_non_interactive() {
        build_inputs_non_interactive(ctx, args, operator_seed_source).await?
    } else {
        build_inputs_interactive(ctx, args, operator_seed_source).await?
    };

    let outcome = run_with_resolved_inputs(ctx, inputs).await?;
    Ok(Outcome::DeployApprove(outcome))
}

async fn build_inputs_interactive(
    ctx: &mut StdCtx,
    args: Args,
    operator_seed_source: Option<LocalOperatorSeedSource>,
) -> anyhow::Result<ResolvedApproveInputs> {
    let do_prompt_user = !args.dangerous_skip_interactive;

    // Guard: bail fast before fetching the manifest if review prompts are
    // required but the caller has no TTY to answer them.
    if do_prompt_user && !stdin_can_prompt() {
        bail_required_in_non_interactive("--dangerous-skip-interactive")?;
    }

    let (manifest, fetched_manifest_id) = load_manifest(ctx, &args).await?;

    if do_prompt_user {
        interactive_approve(ctx, &manifest)?;
    }

    let mut operator_id = args.operator_id;
    let post_target = if !args.dry_run && !args.skip_post {
        let manifest_id = resolve_manifest_id(&args, fetched_manifest_id.as_deref())?;
        if operator_id.is_none() {
            operator_id = Some({
                let saved_ids = load_saved_operator_ids().await?;
                match &*saved_ids {
                    [] => bail!(
                        "--operator-id is required to post approval to API. \
                         No saved operator IDs found. \
                         Use --skip-post to only generate the approval locally."
                    ),
                    [id] => *id,
                    _ if stdin_can_prompt() => {
                        prompts::select("Select approving operator", saved_ids)?
                    }
                    _ => bail!(
                        "--operator-id is required to post approval to API when multiple saved operator IDs are available"
                    ),
                }
            });
        }
        Some(PostTarget {
            manifest_id,
            deploy_id: args.deploy_id.map(|id| id.to_string()),
        })
    } else {
        None
    };

    Ok(ResolvedApproveInputs {
        manifest,
        operator_seed_source,
        operator_id,
        approval_out: args.approval_out,
        dry_run: args.dry_run,
        skip_post: args.skip_post,
        post_target,
    })
}

async fn build_inputs_non_interactive(
    ctx: &mut StdCtx,
    args: Args,
    operator_seed_source: Option<LocalOperatorSeedSource>,
) -> anyhow::Result<ResolvedApproveInputs> {
    if !args.dangerous_skip_interactive {
        bail_required_in_non_interactive("--dangerous-skip-interactive")?;
    }

    let (manifest, fetched_manifest_id) = load_manifest(ctx, &args).await?;

    let mut operator_id = args.operator_id;
    let post_target = if !args.dry_run && !args.skip_post {
        let manifest_id = resolve_manifest_id(&args, fetched_manifest_id.as_deref())?;
        if operator_id.is_none() {
            operator_id = Some({
                let saved_ids = load_saved_operator_ids().await?;
                match &*saved_ids {
                    [] => bail!(
                        "--operator-id is required to post approval to API. \
                         No saved operator IDs found. \
                         Use --skip-post to only generate the approval locally."
                    ),
                    [id] => *id,
                    _ => bail!(
                        "--operator-id is required to post approval to API when multiple saved operator IDs are available"
                    ),
                }
            });
        }
        Some(PostTarget {
            manifest_id,
            deploy_id: args.deploy_id.map(|id| id.to_string()),
        })
    } else {
        None
    };

    Ok(ResolvedApproveInputs {
        manifest,
        operator_seed_source,
        operator_id,
        approval_out: args.approval_out,
        dry_run: args.dry_run,
        skip_post: args.skip_post,
        post_target,
    })
}

async fn run_with_resolved_inputs(
    ctx: &mut StdCtx,
    inputs: ResolvedApproveInputs,
) -> anyhow::Result<ApproveOutcome> {
    if inputs.dry_run {
        return Ok(ApproveOutcome::DryRun(ApprovalDryRun {}));
    }

    let operator = resolve_operator(inputs.operator_seed_source, inputs.operator_id).await?;
    if inputs.skip_post && operator.is_hosted() {
        bail!("--skip-post is only supported for local operators");
    }
    let auth = if operator.is_hosted() {
        Some(build_client().await?)
    } else {
        None
    };
    let approval = sign_and_write_approval(
        &operator,
        &OperatorCtx {
            auth: auth.as_ref(),
        },
        inputs.approval_out.as_deref(),
        &inputs.manifest,
    )
    .await?;

    let written_to = inputs
        .approval_out
        .as_ref()
        .map(|path| path.display().to_string());
    // The approval payload rides in the outcome only when it was not written
    // to a file; otherwise the outcome carries the file path.
    let inline_approval = if written_to.is_none() {
        Some(approval.clone())
    } else {
        None
    };

    match inputs.post_target {
        Some(target) => {
            let operator_id = operator
                .id()
                .context("resolved operator ID required to post approval")?;
            let plan = PostApprovalPlan {
                manifest_id: target.manifest_id.as_str(),
                operator_id: &operator_id,
                deploy_id: target.deploy_id.as_deref(),
            };
            let posted = post_approval_to_api(ctx, plan, &approval).await?;

            Ok(ApproveOutcome::Posted(ApprovalPosted {
                approval: inline_approval,
                written_to,
                manifest_id: target.manifest_id,
                operator_id: operator_id.to_string(),
                approval_ids: posted.approval_ids,
                quorum_reached: posted.quorum_reached,
            }))
        }
        None => Ok(ApproveOutcome::NotPosted(ApprovalGenerated {
            approval: inline_approval,
            written_to,
        })),
    }
}

async fn load_manifest(
    ctx: &mut StdCtx,
    args: &Args,
) -> anyhow::Result<(VersionedManifest, Option<String>)> {
    match (&args.manifest, &args.deploy_id) {
        (Some(path), _) => Ok((read_manifest_from_path(path).await?, None)),
        (_, Some(deploy_id)) => {
            let (manifest, manifest_id) =
                fetch_manifest_from_deploy(ctx, &deploy_id.to_string()).await?;
            Ok((manifest, Some(manifest_id)))
        }
        (None, None) => bail!("a manifest source is required"),
    }
}

/// Sign the manifest and, when `--approval-out` is set, write the approval to
/// that file. Reporting the approval (inline payload or file path) is the
/// terminal outcome's job.
async fn sign_and_write_approval(
    operator: &ResolvedOperator,
    operator_ctx: &OperatorCtx<'_>,
    approval_out: Option<&Path>,
    manifest: &VersionedManifest,
) -> anyhow::Result<Approval> {
    let approval = operator.approve_manifest(operator_ctx, manifest).await?;

    if let Some(path) = approval_out {
        let json = serde_json::to_string_pretty(&approval)?;
        write_file(path, &json).await?;
    }

    Ok(approval)
}

fn resolve_manifest_id(args: &Args, fetched_manifest_id: Option<&str>) -> anyhow::Result<String> {
    fetched_manifest_id
        .map(|s| s.to_string())
        .or_else(|| args.manifest_id.clone())
        .ok_or_else(|| {
            anyhow!(
                "--manifest-id is required to post approval to API (or use --deploy-id). \
                 Use --skip-post to only generate the approval locally."
            )
        })
}

async fn load_saved_operator_ids() -> anyhow::Result<Vec<Uuid>> {
    let config = Config::load().await?;
    config
        .get_last_operator_ids()
        .unwrap_or_default()
        .into_iter()
        .map(|id| {
            Uuid::parse_str(&id).with_context(|| format!("saved operator ID '{id}' is not a UUID"))
        })
        .collect()
}

async fn post_approval_to_api(
    ctx: &mut StdCtx,
    plan: PostApprovalPlan<'_>,
    approval: &Approval,
) -> anyhow::Result<PostedApproval> {
    shell_println!(ctx)?;
    shell_println!(ctx, "Posting approval to Turnkey...")?;

    let auth = crate::client::build_client().await?;

    let tvc_approval = TvcManifestApproval {
        operator_id: plan.operator_id.to_string(),
        signature: hex::encode(&approval.signature),
    };

    let intent = CreateTvcManifestApprovalsIntent {
        manifest_id: plan.manifest_id.into(),
        approvals: vec![tvc_approval],
    };

    let timestamp_ms = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .context("system time before unix epoch")?
        .as_millis();

    let result = auth
        .client
        .create_tvc_manifest_approvals(auth.org_id.clone(), timestamp_ms, intent)
        .await
        .context("failed to post manifest approval")?;

    let quorum_reached = match plan.deploy_id {
        Some(deploy_id) => {
            let request = GetTvcDeploymentRequest {
                organization_id: auth.org_id.clone(),
                deployment_id: deploy_id.to_string(),
            };

            match auth.client.get_tvc_deployment(request).await {
                Ok(response) => Some(
                    response
                        .tvc_deployment
                        .as_ref()
                        .is_some_and(manifest_approval_quorum_reached),
                ),
                Err(error) => {
                    debug!(
                        deploy_id,
                        %error,
                        "failed to fetch deployment after posting manifest approval"
                    );
                    None
                }
            }
        }
        None => None,
    };

    Ok(PostedApproval {
        approval_ids: result.result.approval_ids,
        quorum_reached,
    })
}

fn manifest_approval_quorum_reached(deployment: &TvcDeployment) -> bool {
    let Some(manifest_set) = &deployment.manifest_set else {
        return false;
    };

    if manifest_set.threshold == 0 {
        return false;
    }

    let mut operator_ids = HashSet::new();
    for approval in &deployment.manifest_approvals {
        let Some(operator) = &approval.operator else {
            return false;
        };

        if operator.id.is_empty() {
            return false;
        }

        operator_ids.insert(operator.id.as_str());
    }

    operator_ids.len() >= manifest_set.threshold as usize
}

/// Walk the user through each section of the manifest for approval.
fn interactive_approve(ctx: &mut StdCtx, manifest: &VersionedManifest) -> anyhow::Result<()> {
    shell_println!(ctx, "\n========================================")?;
    shell_println!(ctx, "         MANIFEST APPROVAL")?;
    shell_println!(ctx, "========================================\n")?;

    review_namespace(ctx, manifest.namespace())?;
    review_enclave(ctx, manifest.enclave())?;
    review_pivot(ctx, manifest)?;
    review_manifest_set(ctx, manifest.manifest_set())?;
    review_share_set(ctx, manifest.share_set())?;

    shell_println!(ctx, "\n========================================")?;
    shell_println!(ctx, "    ALL SECTIONS APPROVED")?;
    shell_println!(ctx, "========================================\n")?;

    Ok(())
}

fn render_namespace(namespace: &Namespace) -> String {
    let mut s = String::new();
    let _ = writeln!(s, "NAMESPACE");
    let _ = writeln!(s, "─────────────────────────────────────");
    let _ = writeln!(s, "  Name:       {}", namespace.name);
    let _ = writeln!(s, "  Nonce:      {}", namespace.nonce);
    let _ = writeln!(s, "  Quorum Key: {}", hex::encode(&namespace.quorum_key));
    let _ = writeln!(s);
    s
}

fn review_namespace(ctx: &mut StdCtx, namespace: &Namespace) -> anyhow::Result<()> {
    shell_print!(ctx, "{}", render_namespace(namespace))?;
    prompts::confirm_or_bail("Approve namespace?", "approval")
}

fn render_enclave(enclave: &NitroConfig) -> String {
    let mut s = String::new();
    let _ = writeln!(s, "ENCLAVE (AWS Nitro)");
    let _ = writeln!(s, "─────────────────────────────────────");
    let _ = writeln!(s, "  PCR0 (image):     {}", hex::encode(&enclave.pcr0));
    let _ = writeln!(s, "  PCR1 (kernel):    {}", hex::encode(&enclave.pcr1));
    let _ = writeln!(s, "  PCR2 (app):       {}", hex::encode(&enclave.pcr2));
    let _ = writeln!(s, "  PCR3 (IAM role):  {}", hex::encode(&enclave.pcr3));
    // Skip the QOS commit since it's not cryptographically linked
    let _ = writeln!(s);
    s
}

fn review_enclave(ctx: &mut StdCtx, enclave: &NitroConfig) -> anyhow::Result<()> {
    shell_print!(ctx, "{}", render_enclave(enclave))?;
    prompts::confirm_or_bail("Approve enclave configuration?", "approval")
}

fn render_pivot(manifest: &VersionedManifest) -> String {
    let mut s = String::new();
    let _ = writeln!(s, "PIVOT BINARY");
    let _ = writeln!(s, "─────────────────────────────────────");
    let _ = writeln!(
        s,
        "  Pivot Binary Hash: {}",
        hex::encode(manifest.pivot_hash())
    );
    if manifest.args().is_empty() {
        let _ = writeln!(s, "  CLI Args: (none)");
    } else {
        let _ = writeln!(s, "  CLI Args:\n   {}", manifest.args().join("\n   "));
    }
    let _ = writeln!(s);
    s
}

fn review_pivot(ctx: &mut StdCtx, manifest: &VersionedManifest) -> anyhow::Result<()> {
    shell_print!(ctx, "{}", render_pivot(manifest))?;
    prompts::confirm_or_bail("Approve pivot binary?", "approval")
}

fn render_quorum_members(members: &[QuorumMember]) -> String {
    let mut s = String::new();
    for member in members.iter() {
        let _ = writeln!(s, "    {} ({})", member.alias, hex::encode(&member.pub_key));
    }
    s
}

fn render_manifest_set(set: &ManifestSet) -> String {
    let mut s = String::new();
    let _ = writeln!(s, "MANIFEST SET");
    let _ = writeln!(s, "─────────────────────────────────────");
    let _ = writeln!(s, "  Threshold: {} of {}", set.threshold, set.members.len());
    let _ = writeln!(s, "  Members:");
    s.push_str(&render_quorum_members(&set.members));
    let _ = writeln!(s);
    s
}

fn review_manifest_set(ctx: &mut StdCtx, set: &ManifestSet) -> anyhow::Result<()> {
    shell_print!(ctx, "{}", render_manifest_set(set))?;
    prompts::confirm_or_bail("Approve manifest set?", "approval")
}

fn render_share_set(set: &ShareSet) -> String {
    let mut s = String::new();
    let _ = writeln!(s, "SHARE SET");
    let _ = writeln!(s, "─────────────────────────────────────");
    let _ = writeln!(s, "  Threshold: {} of {}", set.threshold, set.members.len());
    let _ = writeln!(s, "  Members:");
    s.push_str(&render_quorum_members(&set.members));
    let _ = writeln!(s);
    s
}

fn review_share_set(ctx: &mut StdCtx, set: &ShareSet) -> anyhow::Result<()> {
    shell_print!(ctx, "{}", render_share_set(set))?;
    prompts::confirm_or_bail("Approve share set?", "approval")
}

async fn read_manifest_from_path(path: &Path) -> anyhow::Result<VersionedManifest> {
    let content = read_file_to_string(path).await?;
    let manifest = VersionedManifest::try_from_slice_compat(content.as_bytes())
        .with_context(|| format!("failed to parse manifest JSON from: {}", path.display()))?;
    Ok(manifest)
}

/// Fetch manifest from Turnkey using GetTvcDeployment API.
/// Returns the manifest and its Turnkey manifest_id.
async fn fetch_manifest_from_deploy(
    ctx: &mut StdCtx,
    deploy_id: &str,
) -> anyhow::Result<(VersionedManifest, String)> {
    shell_println!(ctx, "Fetching deployment {deploy_id}...")?;

    let auth = build_client().await?;

    let request = GetTvcDeploymentRequest {
        organization_id: auth.org_id.clone(),
        deployment_id: deploy_id.to_string(),
    };

    let response = auth
        .client
        .get_tvc_deployment(request)
        .await
        .with_context(|| format!("failed to fetch deployment {deploy_id}"))?;

    let deployment = response
        .tvc_deployment
        .ok_or_else(|| MissingResource::new("deployment", deploy_id.to_string()))?;

    let tvc_manifest = deployment
        .manifest
        .ok_or_else(|| MissingResource::new("manifest", format!("deployment {deploy_id}")))?;

    let manifest = VersionedManifest::try_from_slice_compat(&tvc_manifest.manifest)
        .context("failed to parse manifest from deployment")?;

    shell_println!(ctx, "✓ Manifest loaded (manifest_id: {})", tvc_manifest.id)?;

    Ok((manifest, tvc_manifest.id))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::output::Message;
    use turnkey_client::generated::external::data::v1::{
        TvcOperator, TvcOperatorApproval, TvcOperatorSet,
    };

    fn fixture_manifest() -> VersionedManifest {
        VersionedManifest::try_from_slice_compat(include_bytes!("../../../fixtures/manifest.json"))
            .expect("fixture manifest should parse")
    }

    fn test_operator(id: &str) -> TvcOperator {
        TvcOperator {
            id: id.to_string(),
            name: format!("operator-{id}"),
            public_key: format!("public-key-{id}"),
            created_at: None,
            updated_at: None,
        }
    }

    fn test_approval(index: usize, operator_id: Option<&str>) -> TvcOperatorApproval {
        TvcOperatorApproval {
            id: format!("approval-{index}"),
            manifest_id: "manifest-123".to_string(),
            operator: operator_id.map(test_operator),
            approval: vec![],
            created_at: None,
            updated_at: None,
        }
    }

    fn test_deployment(
        manifest_threshold: Option<u32>,
        approval_operator_ids: &[Option<&str>],
    ) -> TvcDeployment {
        let operators = approval_operator_ids
            .iter()
            .filter_map(|operator_id| operator_id.map(test_operator))
            .collect();

        TvcDeployment {
            id: "deployment-123".to_string(),
            organization_id: "org-123".to_string(),
            app_id: "app-123".to_string(),
            manifest_set: manifest_threshold.map(|threshold| TvcOperatorSet {
                id: "manifest-set-123".to_string(),
                name: "manifest-set".to_string(),
                organization_id: "org-123".to_string(),
                operators,
                threshold,
                created_at: None,
                updated_at: None,
            }),
            share_set: None,
            manifest: None,
            manifest_approvals: approval_operator_ids
                .iter()
                .enumerate()
                .map(|(index, operator_id)| test_approval(index, *operator_id))
                .collect(),
            qos_version: "qos-v1".to_string(),
            pivot_container: None,
            debug_mode: false,
            created_at: None,
            updated_at: None,
            delete: false,
        }
    }

    #[test]
    fn render_namespace_includes_name_nonce_and_quorum_key() {
        let manifest = fixture_manifest();
        let rendered = render_namespace(manifest.namespace());
        assert!(rendered.contains("NAMESPACE"));
        assert!(rendered.contains("turnkey-prod"));
        assert!(rendered.contains("Nonce:"));
        assert!(rendered.contains("Quorum Key:"));
    }

    #[test]
    fn render_enclave_includes_all_four_pcrs() {
        let manifest = fixture_manifest();
        let rendered = render_enclave(manifest.enclave());
        assert!(rendered.contains("ENCLAVE (AWS Nitro)"));
        assert!(rendered.contains("PCR0"));
        assert!(rendered.contains("PCR1"));
        assert!(rendered.contains("PCR2"));
        assert!(rendered.contains("PCR3"));
    }

    #[test]
    fn render_pivot_includes_header_and_args() {
        let manifest = fixture_manifest();
        let rendered = render_pivot(&manifest);
        assert!(rendered.contains("PIVOT BINARY"));
        assert!(rendered.contains("Pivot Binary Hash:"));
        assert!(rendered.contains("--flag"));
        assert!(rendered.contains("positional"));
    }

    #[test]
    fn render_manifest_set_includes_threshold_and_each_member() {
        let manifest = fixture_manifest();
        let rendered = render_manifest_set(manifest.manifest_set());
        assert!(rendered.contains("MANIFEST SET"));
        assert!(rendered.contains("Threshold: 2 of 3"));
        assert!(rendered.contains("operator-alice"));
        assert!(rendered.contains("operator-bob"));
        assert!(rendered.contains("operator-charlie"));
    }

    #[test]
    fn manifest_approval_quorum_reached_is_false_below_threshold() {
        let deployment = test_deployment(Some(2), &[Some("operator-1")]);

        assert!(!manifest_approval_quorum_reached(&deployment));
    }

    #[test]
    fn manifest_approval_quorum_reached_is_true_at_threshold() {
        let deployment = test_deployment(Some(2), &[Some("operator-1"), Some("operator-2")]);

        assert!(manifest_approval_quorum_reached(&deployment));
    }

    #[test]
    fn manifest_approval_quorum_counts_distinct_operators() {
        let deployment = test_deployment(Some(2), &[Some("operator-1"), Some("operator-1")]);

        assert!(!manifest_approval_quorum_reached(&deployment));
    }

    #[test]
    fn manifest_approval_quorum_is_false_without_manifest_set() {
        let deployment = test_deployment(None, &[Some("operator-1"), Some("operator-2")]);

        assert!(!manifest_approval_quorum_reached(&deployment));
    }

    #[test]
    fn manifest_approval_quorum_is_false_with_zero_threshold() {
        let deployment = test_deployment(Some(0), &[Some("operator-1")]);

        assert!(!manifest_approval_quorum_reached(&deployment));
    }

    #[test]
    fn manifest_approval_quorum_is_false_when_approval_lacks_operator() {
        let deployment = test_deployment(Some(2), &[Some("operator-1"), None]);

        assert!(!manifest_approval_quorum_reached(&deployment));
    }

    #[test]
    fn manifest_approval_quorum_is_false_when_operator_id_is_empty() {
        let deployment = test_deployment(Some(1), &[Some("")]);

        assert!(!manifest_approval_quorum_reached(&deployment));
    }

    fn posted_to_file() -> ApprovalPosted {
        ApprovalPosted {
            approval: None,
            written_to: Some("approval.json".to_string()),
            manifest_id: "manifest-123".to_string(),
            operator_id: "operator-456".to_string(),
            approval_ids: vec!["approval-1".to_string()],
            quorum_reached: Some(true),
        }
    }

    #[test]
    fn approval_posted_serializes_expected_json() {
        let value: serde_json::Value = serde_json::from_str(
            &Outcome::DeployApprove(ApproveOutcome::Posted(posted_to_file())).to_json_string(),
        )
        .unwrap();

        assert_eq!(
            value,
            serde_json::json!({
                "reason": "manifest_approval_posted",
                "writtenTo": "approval.json",
                "manifestId": "manifest-123",
                "operatorId": "operator-456",
                "approvalIds": ["approval-1"],
                "quorumReached": true,
            })
        );
    }

    #[test]
    fn approval_generated_serializes_expected_json() {
        let generated = ApprovalGenerated {
            approval: Some(Approval {
                signature: vec![0xde, 0xad],
                member: QuorumMember {
                    alias: "operator-alice".to_string(),
                    pub_key: vec![0xaa],
                },
            }),
            written_to: None,
        };

        let value: serde_json::Value = serde_json::from_str(
            &Outcome::DeployApprove(ApproveOutcome::NotPosted(generated)).to_json_string(),
        )
        .unwrap();

        assert_eq!(
            value,
            serde_json::json!({
                "reason": "manifest_approval_generated",
                "approval": {
                    "signature": "dead",
                    "member": {
                        "alias": "operator-alice",
                        "pubKey": "aa",
                    },
                },
            })
        );
    }

    #[test]
    fn approval_dry_run_serializes_reason_only() {
        let value: serde_json::Value = serde_json::from_str(
            &Outcome::DeployApprove(ApproveOutcome::DryRun(ApprovalDryRun {})).to_json_string(),
        )
        .unwrap();

        assert_eq!(
            value,
            serde_json::json!({ "reason": "manifest_approval_dry_run" })
        );
    }

    /// The quorum line is branch-dependent: present with the reached/pending
    /// sentence when the post-check fetch succeeded, absent when quorum state
    /// is unknown (matching the pre-outcome behavior of a silent failed
    /// fetch).
    #[test]
    fn approval_posted_human_message_includes_quorum_line_only_when_known() {
        let mut posted = posted_to_file();

        posted.quorum_reached = Some(true);
        assert!(
            posted
                .to_string()
                .contains("Manifest approval quorum reached.")
        );

        posted.quorum_reached = Some(false);
        assert!(
            posted
                .to_string()
                .contains("requires additional manifest approvals")
        );

        posted.quorum_reached = None;
        let human = posted.to_string();
        assert!(!human.contains("quorum"));
        assert!(human.ends_with("Operator ID: operator-456"));
    }
}