Skip to main content

hyprstream_core/cli/
wizard_handlers.rs

1//! Interactive setup wizard for bootstrapping hyprstream
2//!
3//! Guides new users through environment setup, policy configuration,
4//! user/role creation, API token generation, and optional service startup.
5//!
6//! Both CLI (inquire-based text prompts) and TUI (ratatui) wizards share
7//! the same `WizardBackend` trait for business logic, avoiding duplication.
8// CLI handlers intentionally print to stdout/stderr for user interaction
9#![allow(clippy::print_stdout, clippy::print_stderr)]
10
11use std::path::{Path, PathBuf};
12
13use anyhow::Result;
14use inquire::{Confirm, Select, Text};
15
16use hyprstream_tui::wizard::backend::*;
17
18use crate::cli::service_handlers::{
19    build_version, format_size, handle_service_install, is_binary_installed, print_check,
20    CheckStatus, InstallPlan,
21};
22
23// ─────────────────────────────────────────────────────────────────────────────
24// Predefined roles (display labels for inquire prompts)
25// ─────────────────────────────────────────────────────────────────────────────
26
27struct RoleDef {
28    name: &'static str,
29    description: &'static str,
30}
31
32const PREDEFINED_ROLES: &[RoleDef] = &[
33    RoleDef {
34        name: "admin",
35        description: "Full access to everything",
36    },
37    RoleDef {
38        name: "operator",
39        description: "Infer + query + load/unload models",
40    },
41    RoleDef {
42        name: "viewer",
43        description: "Read-only queries",
44    },
45    RoleDef {
46        name: "trainer",
47        description: "Inference + training",
48    },
49];
50
51// ─────────────────────────────────────────────────────────────────────────────
52// Display tracking (for end-of-wizard summary)
53// ─────────────────────────────────────────────────────────────────────────────
54
55struct TextWizardSummary {
56    templates_applied: Vec<String>,
57    users_created: Vec<(String, String)>,
58    tokens_generated: Vec<(String, String, String)>,
59    /// Grade line for the deployment root, when a ceremony ran.
60    deployment_trust: Option<String>,
61}
62
63impl TextWizardSummary {
64    fn new() -> Self {
65        Self {
66            templates_applied: Vec::new(),
67            users_created: Vec::new(),
68            tokens_generated: Vec::new(),
69            deployment_trust: None,
70        }
71    }
72}
73
74// ─────────────────────────────────────────────────────────────────────────────
75// Entry points
76// ─────────────────────────────────────────────────────────────────────────────
77
78/// Handle `hyprstream wizard --tui` — TUI setup wizard with bootstrap manager.
79pub async fn handle_wizard_tui(models_dir: &Path, config_services: &[String]) -> Result<()> {
80    let rt = tokio::runtime::Handle::current();
81    let models_dir = models_dir.to_path_buf();
82    let config_services = config_services.to_vec();
83    tokio::task::spawn_blocking(move || {
84        let backend =
85            crate::cli::bootstrap_manager::BootstrapManager::new(rt, models_dir, config_services);
86        let app = hyprstream_tui::wizard::WizardApp::new(backend);
87        waxterm::run_sync(app, waxterm::TerminalConfig::new())
88    })
89    .await??;
90    Ok(())
91}
92
93/// Opt-in deployment-trust ceremony settings.
94///
95/// Deployment trust is a separate layer from node bootstrap: none of this runs
96/// unless `enabled` is set, and the wizard's node-local behaviour is unchanged
97/// when it is not.
98#[derive(Clone, Debug, Default)]
99pub struct DeploymentTrustOptions {
100    /// Run the ceremony after node bootstrap.
101    pub enabled: bool,
102    /// Absolute ceremony working directory. Defaults under the models dir.
103    pub dir: Option<std::path::PathBuf>,
104    /// Mint a software root even if a token is attached.
105    pub force_software: bool,
106    /// Token serial to use when several are attached.
107    pub serial: Option<String>,
108    /// PIV slot for the Ed25519 leg on firmware that supports it.
109    pub piv_slot: Option<String>,
110    /// Accept an unencrypted break-glass identity. Throwaway roots only.
111    pub allow_plaintext_break_glass: bool,
112}
113
114/// Everything `hyprstream wizard` was invoked with.
115#[derive(Clone, Debug, Default)]
116pub struct WizardOptions {
117    /// Accept defaults without prompting.
118    pub non_interactive: bool,
119    /// Start services once setup finishes.
120    pub start_services: bool,
121    /// Run only phase 1 (node bootstrap).
122    pub bootstrap_only: bool,
123    /// Apply the federation-open policy template.
124    pub enable_federation: bool,
125    /// Role assigned to the local user under `--non-interactive`.
126    pub initial_user_role: String,
127    /// Deployment-trust ceremony settings.
128    pub deployment_trust: DeploymentTrustOptions,
129}
130
131impl WizardOptions {
132    /// Defaults for the first-run path: interactive, no federation, admin user.
133    #[must_use]
134    pub fn first_run() -> Self {
135        Self {
136            initial_user_role: "admin".to_owned(),
137            ..Self::default()
138        }
139    }
140}
141
142/// Handle `hyprstream wizard` — interactive setup wizard.
143///
144/// When `bootstrap_only` is true, only phase 1 (trust-root setup) runs.
145/// `initial_user_role` overrides the default "admin" role assigned to the
146/// local user under `--non-interactive`; use "operator" or "viewer" for
147/// least-privilege test setups (#184).
148pub async fn handle_wizard(
149    models_dir: &Path,
150    config_services: &[String],
151    options: WizardOptions,
152) -> Result<()> {
153    // Install systemd units before entering spawn_blocking (async operation).
154    if !options.bootstrap_only && hyprstream_rpc::has_systemd() {
155        wizard_pre_install_step(|iroh_required| {
156            handle_service_install(
157                models_dir,
158                config_services,
159                None,
160                false,
161                false,
162                hyprstream_service::ServiceTarget::User,
163                false,
164                crate::config::explicit_config_path().map(PathBuf::as_path),
165                iroh_required,
166            )
167        })
168        .await?;
169    }
170
171    let rt = tokio::runtime::Handle::current();
172    let models_dir = models_dir.to_path_buf();
173    let config_services = config_services.to_vec();
174
175    tokio::task::spawn_blocking(move || {
176        let mut backend = crate::cli::bootstrap_manager::BootstrapManager::new(
177            rt,
178            models_dir.clone(),
179            config_services.clone(),
180        );
181        run_text_wizard(&mut backend, &options, &models_dir, &config_services)
182    })
183    .await??;
184
185    Ok(())
186}
187
188/// Wizard pre-install step: load the process configuration and decide whether
189/// fixed-unit installation may run before the wizard phases proceed.
190///
191/// An unloadable configuration fails closed here — it is never silently
192/// treated as the default profile (#1585). Installed systemd units run their
193/// own stored configuration and can carry neither this process's explicit
194/// `--config` provenance nor the required-native profile, so for those
195/// profiles unit installation is skipped and setup continues; a later start
196/// routes through the supported direct launch path instead.
197///
198/// The `install` closure is the real `handle_service_install` call in
199/// production; tests inject a recording side effect.
200async fn wizard_pre_install_step<F, Fut>(install: F) -> Result<()>
201where
202    F: FnOnce(bool) -> Fut,
203    Fut: std::future::Future<Output = Result<()>>,
204{
205    let iroh_required = crate::config::HyprConfig::load()
206        .map_err(|e| anyhow::anyhow!("wizard configuration load failed: {e}"))?
207        .quic
208        .iroh_required();
209    if crate::config::explicit_config_path().is_some() || iroh_required {
210        return Ok(());
211    }
212    install(iroh_required).await
213}
214
215// ─────────────────────────────────────────────────────────────────────────────
216// Text-mode wizard driver (delegates to WizardBackend)
217// ─────────────────────────────────────────────────────────────────────────────
218
219fn run_text_wizard(
220    backend: &mut impl WizardBackend,
221    options: &WizardOptions,
222    models_dir: &Path,
223    config_services: &[String],
224) -> Result<()> {
225    let non_interactive = options.non_interactive;
226
227    println!();
228    println!("  Hyprstream Setup Wizard");
229    println!("  {}", "=".repeat(40));
230    println!();
231
232    let mut summary = TextWizardSummary::new();
233
234    // Phase 1: Environment bootstrap
235    text_phase_bootstrap(backend)?;
236
237    if options.bootstrap_only {
238        return Ok(());
239    }
240
241    // Phase 2: Binary installation (standalone — not a WizardBackend concern)
242    text_phase_binary_install(non_interactive)?;
243
244    // Phase 3: Policy template selection
245    text_phase_templates(
246        backend,
247        non_interactive,
248        options.enable_federation,
249        &mut summary,
250    )?;
251
252    // Phase 4: User/role creation
253    text_phase_users(
254        backend,
255        non_interactive,
256        &options.initial_user_role,
257        &mut summary,
258    )?;
259
260    // Phase 5: Token generation
261    text_phase_tokens(backend, non_interactive, &mut summary)?;
262
263    // Phase 6: Deployment trust (opt-in; separate from node-local trust)
264    text_phase_deployment_trust(options, models_dir, &mut summary)?;
265
266    // Phase 7: Service startup
267    text_phase_services(
268        backend,
269        config_services,
270        non_interactive,
271        options.start_services,
272    )?;
273
274    // Summary
275    print_summary(&summary);
276
277    Ok(())
278}
279
280// ─────────────────────────────────────────────────────────────────────────────
281// Phase 1: Bootstrap (via WizardBackend)
282// ─────────────────────────────────────────────────────────────────────────────
283
284fn text_phase_bootstrap(backend: &mut impl WizardBackend) -> Result<()> {
285    println!("  Phase 1: Environment Bootstrap");
286    println!("  {}", "-".repeat(40));
287    println!();
288
289    backend.start_bootstrap();
290
291    loop {
292        match backend.poll_bootstrap() {
293            BootstrapPoll::InProgress(msg) => {
294                println!("    {msg}");
295                std::thread::sleep(std::time::Duration::from_millis(100));
296            }
297            BootstrapPoll::Done(steps) => {
298                for step in &steps {
299                    print_check(step, CheckStatus::Ok, "");
300                }
301                break;
302            }
303            BootstrapPoll::Failed(e) => {
304                return Err(anyhow::anyhow!("Bootstrap failed: {e}"));
305            }
306        }
307    }
308
309    println!();
310    Ok(())
311}
312
313// ─────────────────────────────────────────────────────────────────────────────
314// Phase 2: Binary Installation (standalone — not through WizardBackend)
315// ─────────────────────────────────────────────────────────────────────────────
316
317fn text_phase_binary_install(non_interactive: bool) -> Result<()> {
318    println!("  Phase 2: Binary Installation");
319    println!("  {}", "-".repeat(40));
320    println!();
321
322    if let Some(installed_path) = is_binary_installed() {
323        let version = build_version();
324        print_check(
325            "Binary",
326            CheckStatus::Ok,
327            &format!("installed ({version}) at {}", installed_path.display()),
328        );
329        println!();
330        return Ok(());
331    }
332
333    let plan = match InstallPlan::prepare() {
334        Ok(p) => p,
335        Err(e) => {
336            print_check("Binary", CheckStatus::Warn, &format!("cannot prepare: {e}"));
337            println!();
338            return Ok(());
339        }
340    };
341
342    println!(
343        "    Source: {} ({}, {})",
344        plan.source.display(),
345        plan.type_label(),
346        format_size(plan.source_size),
347    );
348    println!("    Target: {}/hyprstream", plan.bin_dir.display());
349    if plan.available_space > 0 {
350        println!(
351            "    Disk:   {} available",
352            format_size(plan.available_space)
353        );
354    }
355    println!();
356
357    if !plan.has_sufficient_space() {
358        print_check(
359            "Binary",
360            CheckStatus::Warn,
361            &format!(
362                "insufficient disk space ({} needed, {} available)",
363                format_size(plan.source_size),
364                format_size(plan.available_space),
365            ),
366        );
367        println!();
368        return Ok(());
369    }
370
371    let should_install = if non_interactive {
372        true
373    } else {
374        Confirm::new("  Install hyprstream to your PATH?")
375            .with_default(true)
376            .prompt()
377            .unwrap_or(false)
378    };
379
380    if !should_install {
381        println!("    Skipping binary installation.");
382        println!();
383        return Ok(());
384    }
385
386    match plan.execute() {
387        Ok(result) => {
388            print_check(
389                "Binary",
390                CheckStatus::Ok,
391                &format!(
392                    "installed ({}) to {}",
393                    result.type_label(),
394                    result.bin_dir.join("hyprstream").display()
395                ),
396            );
397            println!("    Version store: {}", result.version_dir.display());
398            if !result.updated_profiles.is_empty() {
399                println!("    PATH updated:  {}", result.updated_profiles.join(", "));
400            }
401        }
402        Err(e) => {
403            print_check(
404                "Binary",
405                CheckStatus::Fail,
406                &format!("installation failed: {e}"),
407            );
408        }
409    }
410
411    println!();
412    Ok(())
413}
414
415// ─────────────────────────────────────────────────────────────────────────────
416// Phase 3: Policy Templates (via WizardBackend)
417// ─────────────────────────────────────────────────────────────────────────────
418
419/// Template name for the opt-in open-federation grant. Kept here so the
420/// wizard can show it as a separate confirm prompt (rather than
421/// burying it in the main Select alongside server-access templates).
422const FEDERATION_TEMPLATE: &str = "federation-open";
423
424fn text_phase_templates(
425    backend: &mut impl WizardBackend,
426    non_interactive: bool,
427    enable_federation: bool,
428    summary: &mut TextWizardSummary,
429) -> Result<()> {
430    println!("  Phase 3: Policy Template");
431    println!("  {}", "-".repeat(40));
432    println!();
433
434    let has_existing = backend.has_existing_policy();
435
436    if has_existing {
437        print_check("Policy", CheckStatus::Ok, "existing policy rules found");
438
439        if non_interactive {
440            println!("    Keeping existing policy (non-interactive mode).");
441            // Federation is composable, so even with an existing policy
442            // we honor --enable-federation by layering it on top.
443            if enable_federation {
444                apply_federation_template(backend, summary);
445            }
446            println!();
447            return Ok(());
448        }
449
450        let overwrite = Confirm::new("  Existing policy rules found. Replace with a template?")
451            .with_default(false)
452            .prompt()
453            .unwrap_or(false);
454
455        if !overwrite {
456            println!("    Keeping existing policy.");
457            prompt_federation_interactive(backend, summary);
458            println!();
459            return Ok(());
460        }
461    }
462
463    // Server-access templates only — federation handled separately.
464    let templates: Vec<_> = backend
465        .templates()
466        .into_iter()
467        .filter(|t| t.name != FEDERATION_TEMPLATE)
468        .collect();
469
470    if non_interactive {
471        if let Some(first) = templates.first() {
472            backend.apply_template(&first.name);
473            print_check(
474                "Template",
475                CheckStatus::Ok,
476                &format!("applied '{}'", first.name),
477            );
478            summary.templates_applied.push(first.name.clone());
479        }
480        if enable_federation {
481            apply_federation_template(backend, summary);
482        }
483        println!();
484        return Ok(());
485    }
486
487    let mut options: Vec<String> = templates
488        .iter()
489        .map(|t| format!("{} — {}", t.name, t.description))
490        .collect();
491    options.push("None — skip template".to_owned());
492
493    let selection = Select::new("  Select a policy template:", options)
494        .prompt()
495        .map_err(|e| anyhow::anyhow!("Template selection cancelled: {e}"))?;
496
497    if selection.starts_with("None") {
498        println!("    Skipping template.");
499    } else {
500        let template_name = selection.split(" —").next().unwrap_or("").trim();
501        if let Some(template) = templates.iter().find(|t| t.name == template_name) {
502            backend.apply_template(&template.name);
503            backend.save_policies();
504            print_check(
505                "Template",
506                CheckStatus::Ok,
507                &format!("applied '{}'", template.name),
508            );
509            summary.templates_applied.push(template.name.clone());
510        }
511    }
512
513    prompt_federation_interactive(backend, summary);
514    println!();
515    Ok(())
516}
517
518/// Interactive prompt for the federation-open template. Default is N
519/// — opening third-party client federation is opt-in.
520fn prompt_federation_interactive(
521    backend: &mut impl WizardBackend,
522    summary: &mut TextWizardSummary,
523) {
524    let enable = Confirm::new(
525        "  Enable open federation? \
526         Accepts third-party apps and remote peer servers from any origin \
527         (atproto-style; MCP/peer compatible).",
528    )
529    .with_default(false)
530    .prompt()
531    .unwrap_or(false);
532    if enable {
533        apply_federation_template(backend, summary);
534    } else {
535        println!("    Federation left disabled — operators can enable later with");
536        println!("    `hyprstream quick policy apply-template {FEDERATION_TEMPLATE}`.");
537    }
538}
539
540fn apply_federation_template(backend: &mut impl WizardBackend, summary: &mut TextWizardSummary) {
541    backend.apply_template(FEDERATION_TEMPLATE);
542    backend.save_policies();
543    print_check(
544        "Federation",
545        CheckStatus::Ok,
546        &format!("applied '{FEDERATION_TEMPLATE}'"),
547    );
548    summary
549        .templates_applied
550        .push(FEDERATION_TEMPLATE.to_owned());
551}
552
553// ─────────────────────────────────────────────────────────────────────────────
554// Phase 4: Users (via WizardBackend)
555// ─────────────────────────────────────────────────────────────────────────────
556
557fn text_phase_users(
558    backend: &mut impl WizardBackend,
559    non_interactive: bool,
560    initial_user_role: &str,
561    summary: &mut TextWizardSummary,
562) -> Result<()> {
563    println!("  Phase 4: Users & Roles");
564    println!("  {}", "-".repeat(40));
565    println!();
566
567    if non_interactive {
568        let local_user = backend.local_username();
569        backend.add_user(&local_user, initial_user_role);
570        print_check(&local_user, CheckStatus::Ok, initial_user_role);
571        summary
572            .users_created
573            .push((local_user, initial_user_role.to_owned()));
574        println!();
575        return Ok(());
576    }
577
578    let add_users = Confirm::new("  Add a local user?")
579        .with_default(true)
580        .prompt()
581        .unwrap_or(false);
582
583    if !add_users {
584        println!("    Skipping user creation.");
585        println!();
586        return Ok(());
587    }
588
589    loop {
590        let username = Text::new("  Username:")
591            .prompt()
592            .map_err(|e| anyhow::anyhow!("Username input cancelled: {e}"))?;
593
594        if username.trim().is_empty() {
595            println!("    Username cannot be empty.");
596            continue;
597        }
598        let username = username.trim().to_owned();
599
600        // Role selection
601        let mut role_options: Vec<String> = PREDEFINED_ROLES
602            .iter()
603            .map(|r| format!("{} — {}", r.name, r.description))
604            .collect();
605        role_options.push("custom — Define custom permissions".to_owned());
606
607        let role_selection = Select::new("  Role:", role_options)
608            .prompt()
609            .map_err(|e| anyhow::anyhow!("Role selection cancelled: {e}"))?;
610
611        let role_name = role_selection.split(" —").next().unwrap_or("").trim();
612
613        if role_name == "custom" {
614            let resource = Text::new("  Resource pattern (e.g., model:*, registry:*):")
615                .with_default("*")
616                .prompt()
617                .map_err(|e| anyhow::anyhow!("Resource input cancelled: {e}"))?;
618
619            let actions = &["infer", "train", "query", "write", "serve", "manage"];
620            let action_options: Vec<String> = actions.iter().map(|a| (*a).to_owned()).collect();
621
622            let selected_actions = inquire::MultiSelect::new("  Actions to allow:", action_options)
623                .prompt()
624                .map_err(|e| anyhow::anyhow!("Action selection cancelled: {e}"))?;
625
626            backend.add_user_custom(&username, &resource, &selected_actions);
627
628            let actions_str = selected_actions.join(",");
629            print_check(
630                &username,
631                CheckStatus::Ok,
632                &format!("custom ({actions_str} on {resource})"),
633            );
634            summary
635                .users_created
636                .push((username.clone(), format!("custom({actions_str})")));
637        } else {
638            backend.add_user(&username, role_name);
639            print_check(&username, CheckStatus::Ok, role_name);
640            summary
641                .users_created
642                .push((username.clone(), role_name.to_owned()));
643        }
644
645        let add_another = Confirm::new("  Add another user?")
646            .with_default(false)
647            .prompt()
648            .unwrap_or(false);
649
650        if !add_another {
651            break;
652        }
653    }
654
655    println!();
656    Ok(())
657}
658
659// ─────────────────────────────────────────────────────────────────────────────
660// Phase 5: Tokens (via WizardBackend)
661// ─────────────────────────────────────────────────────────────────────────────
662
663fn text_phase_tokens(
664    backend: &mut impl WizardBackend,
665    non_interactive: bool,
666    summary: &mut TextWizardSummary,
667) -> Result<()> {
668    println!("  Phase 5: API Tokens");
669    println!("  {}", "-".repeat(40));
670    println!();
671
672    if non_interactive {
673        let local_user = backend.local_username();
674        let result = backend.generate_token(&local_user, "90d");
675        print_token_result(&local_user, &result);
676        summary
677            .tokens_generated
678            .push((local_user, token_preview(&result.token), result.expires));
679        println!();
680        return Ok(());
681    }
682
683    if summary.users_created.is_empty() {
684        println!("    No users created — skipping token generation.");
685        println!();
686        return Ok(());
687    }
688
689    let expiration_options = vec!["30 days", "90 days (recommended)", "1 year", "never"];
690
691    for (username, _role) in &summary.users_created {
692        let create = Confirm::new(&format!("  Generate API token for '{username}'?"))
693            .with_default(true)
694            .prompt()
695            .unwrap_or(false);
696
697        if !create {
698            continue;
699        }
700
701        let expiry = Select::new("  Token expiration:", expiration_options.clone())
702            .prompt()
703            .map_err(|e| anyhow::anyhow!("Expiration selection cancelled: {e}"))?;
704
705        let duration_str = match expiry {
706            "30 days" => "30d",
707            "1 year" => "1y",
708            "never" => "never",
709            _ => "90d",
710        };
711
712        let result = backend.generate_token(username, duration_str);
713        print_token_result(username, &result);
714        summary.tokens_generated.push((
715            username.clone(),
716            token_preview(&result.token),
717            result.expires.clone(),
718        ));
719    }
720
721    println!();
722    Ok(())
723}
724
725fn print_token_result(username: &str, result: &TokenResult) {
726    println!();
727    println!("    Token for '{username}':");
728    println!("    {}", result.token);
729    println!();
730    println!("    Expires: {}", result.expires);
731    let display_len = std::cmp::min(30, result.token.len());
732    println!(
733        "    Usage:   curl -H \"Authorization: Bearer {}...\" http://localhost:8080/v1/models",
734        &result.token[..display_len]
735    );
736    println!();
737    println!("    \x1b[33mSave this token now — it cannot be retrieved again.\x1b[0m");
738    println!();
739}
740
741fn token_preview(token: &str) -> String {
742    if token.len() > 20 {
743        format!("{}...", &token[..20])
744    } else {
745        token.to_owned()
746    }
747}
748
749// ─────────────────────────────────────────────────────────────────────────────
750// Phase 6: Deployment trust (opt-in ceremony)
751// ─────────────────────────────────────────────────────────────────────────────
752
753/// Run the deployment-trust ceremony, if the operator asked for it.
754///
755/// Node bootstrap sets up node-local trust and stops there; this phase is the
756/// separate, deliberately opt-in deployment layer. When it is not requested the
757/// wizard behaves exactly as it did before, including under `--non-interactive`,
758/// where the phase never reaches a prompt.
759fn text_phase_deployment_trust(
760    options: &WizardOptions,
761    models_dir: &Path,
762    summary: &mut TextWizardSummary,
763) -> Result<()> {
764    use crate::cli::trust_ceremony as ceremony;
765    use crate::cli::trust_ceremony::{AgeYubikeyPlugin as _, TokenDetector as _};
766
767    let settings = &options.deployment_trust;
768    let request = ceremony::CeremonyRequest {
769        enabled: settings.enabled,
770        interactive: !options.non_interactive,
771        force_software: settings.force_software,
772        serial: settings.serial.clone(),
773        piv_slot: settings
774            .piv_slot
775            .clone()
776            .unwrap_or_else(|| ceremony::DEFAULT_PIV_SLOT.to_owned()),
777    };
778
779    if !request.enabled {
780        return Ok(());
781    }
782
783    println!("  Phase 6: Deployment Trust");
784    println!("  {}", "-".repeat(40));
785    println!();
786
787    println!("    Looking for a hardware token...");
788    let detection = ceremony::SystemTokenDetector.detect();
789    let mut plan = ceremony::plan_ceremony(&request, &detection);
790
791    if let ceremony::CeremonyPlan::ChooseToken { tokens, rationale } = &plan {
792        println!("    {rationale}.");
793        let labels: Vec<String> = tokens.iter().map(ceremony::DetectedToken::label).collect();
794        let chosen = Select::new(
795            "  Which token should hold the deployment root?",
796            labels.clone(),
797        )
798        .prompt()
799        .map_err(|e| anyhow::anyhow!("no token was chosen: {e}"))?;
800        let index = labels
801            .iter()
802            .position(|label| *label == chosen)
803            .ok_or_else(|| anyhow::anyhow!("token selection did not match an attached token"))?;
804        let token = tokens
805            .get(index)
806            .ok_or_else(|| anyhow::anyhow!("token selection did not match an attached token"))?
807            .clone();
808        plan = ceremony::select_mode_for_token(&request, &token);
809    }
810
811    let (mode, rationale) = match plan {
812        ceremony::CeremonyPlan::Skipped { reason } => {
813            println!("    {reason}.");
814            println!();
815            return Ok(());
816        }
817        ceremony::CeremonyPlan::Blocked { reason, remedy } => {
818            print_check("Deployment trust", CheckStatus::Fail, &reason);
819            println!("    {remedy}.");
820            return Err(anyhow::anyhow!(
821                "deployment trust ceremony cannot run: {reason} — {remedy}"
822            ));
823        }
824        ceremony::CeremonyPlan::ChooseToken { .. } => {
825            return Err(anyhow::anyhow!(
826                "several tokens are attached and none was chosen; pass \
827                 --deployment-trust-serial <SERIAL>"
828            ));
829        }
830        ceremony::CeremonyPlan::Proceed { mode, rationale } => (mode, rationale),
831    };
832
833    println!("    {rationale}.");
834    if mode.is_dev_grade() {
835        println!();
836        println!("    !! {}", ceremony::DEV_GRADE_LABEL);
837        println!("    !! Anyone who can read the recipient files holds the deployment root.");
838        println!("    !! Upgrade to hardware later with `hyprstream trust rotate-authority`.");
839        println!();
840    }
841
842    let missing = ceremony::missing_tools(ceremony::required_tools(&mode), ceremony::tool_on_path);
843    if !missing.is_empty() {
844        return Err(anyhow::anyhow!(
845            "the {} ceremony needs {} on PATH; install {} and re-run",
846            mode.mode_id(),
847            missing.join(", "),
848            missing.join(" and ")
849        ));
850    }
851
852    let dir = match settings.dir.clone() {
853        Some(dir) => dir,
854        None => models_dir.join("deployment-ceremony"),
855    };
856    let dir = if dir.is_absolute() {
857        dir
858    } else {
859        std::env::current_dir()
860            .map_err(|e| anyhow::anyhow!("resolve the ceremony directory: {e}"))?
861            .join(dir)
862    };
863    let paths = ceremony::CeremonyPaths::new(dir)?;
864    ceremony::create_ceremony_dir(paths.dir())?;
865    println!("    Ceremony working directory: {}", paths.dir().display());
866
867    // Primary recipient: the token's own age identity, or a software key.
868    let (primary_recipient, unlock_identity) = match &mode {
869        ceremony::CeremonyMode::HardwarePiv { token, .. }
870        | ceremony::CeremonyMode::HardwareAgeRecipient { token } => {
871            println!();
872            println!("    Generating the token's age identity (PIN + touch required for every");
873            println!("    use). Follow the prompts on your terminal and the token.");
874            let plugin = ceremony::SystemAgeYubikeyPlugin;
875            let recipient = plugin
876                .generate_identity(&format!("hyprstream deployment root ({})", token.serial))
877                .map_err(|e| anyhow::anyhow!("generate the token's age identity: {e}"))?;
878            plugin
879                .export_identity_file(&paths.yubikey_identity())
880                .map_err(|e| anyhow::anyhow!("export the token's age identity: {e}"))?;
881            (
882                recipient,
883                ceremony::UnlockIdentity::Yubikey(paths.yubikey_identity()),
884            )
885        }
886        ceremony::CeremonyMode::SoftwareDevGrade => {
887            let recipient = ceremony::generate_software_identity(&paths.primary_identity())?;
888            (
889                recipient,
890                ceremony::UnlockIdentity::Age(paths.primary_identity()),
891            )
892        }
893    };
894
895    let break_glass = prompt_break_glass(&mode, &primary_recipient, &paths, options)?;
896    println!("    Break-glass: {}", break_glass.kind_id());
897
898    // The online signer is an autonomous key: no token, no root.
899    let signer_recipient = ceremony::generate_software_identity(&paths.online_signer_identity())?;
900
901    // The credential binds the registry service key node bootstrap just made.
902    let credentials_dir = crate::auth::identity_store::credentials_dir()?;
903    let pubkeys = crate::auth::identity_store::load_bootstrap_pubkeys(&credentials_dir)?;
904    let registry_key = pubkeys.get("registry").ok_or_else(|| {
905        anyhow::anyhow!(
906            "no registry service key in {}; run node bootstrap before the ceremony",
907            credentials_dir.display()
908        )
909    })?;
910    ceremony::write_registry_public_key(&paths.registry_public_key(), registry_key.as_bytes())?;
911
912    let inputs = ceremony::CeremonyInputs {
913        mode: mode.clone(),
914        primary_recipient,
915        break_glass: break_glass.clone(),
916        unlock_identity,
917        signer_recipient,
918        paths: paths.clone(),
919    };
920
921    println!();
922    for (step, command) in ceremony::ceremony_commands(&inputs)?
923        .into_iter()
924        .enumerate()
925    {
926        println!("    Ceremony step {}/4...", step + 1);
927        crate::cli::trust::handle_trust_command(command)?;
928    }
929
930    let record = ceremony::mode_record(&mode, &break_glass, &rationale);
931    std::fs::write(paths.mode_record(), serde_json::to_vec_pretty(&record)?)?;
932
933    print_check("Deployment trust", CheckStatus::Ok, mode.grade_label());
934    println!();
935    println!("    The public artifacts are NOT installed yet. Copy them to a deployed host:");
936    println!("      {}", paths.public_ca().display());
937    println!("      {}", paths.authority_log().display());
938    println!("      {}", paths.authority_checkpoint().display());
939    println!(
940        "    Keep {} offline — it never belongs on a deployed host.",
941        paths.authority_key().display()
942    );
943    println!();
944
945    summary.deployment_trust = Some(format!("{} — {}", mode.mode_id(), mode.grade_label()));
946    Ok(())
947}
948
949/// Walk the operator through a break-glass recipient the tooling can trust.
950///
951/// The trust CLI can only see that two recipients differ; whether the second is
952/// protected is decided here, and an unprotected one is refused by default.
953fn prompt_break_glass(
954    mode: &crate::cli::trust_ceremony::CeremonyMode,
955    primary_recipient: &str,
956    paths: &crate::cli::trust_ceremony::CeremonyPaths,
957    options: &WizardOptions,
958) -> Result<crate::cli::trust_ceremony::BreakGlass> {
959    use crate::cli::trust_ceremony as ceremony;
960
961    const SECOND_TOKEN: &str = "A second hardware token (best — same protection as the primary)";
962    const PASSPHRASE: &str = "A passphrase-encrypted identity file (age-keygen | age -p)";
963    const PLAINTEXT: &str = "An unencrypted identity file (throwaway roots only)";
964
965    let policy = if options.deployment_trust.allow_plaintext_break_glass {
966        ceremony::PlaintextPolicy::AllowedByOverride
967    } else if mode.is_dev_grade() {
968        ceremony::PlaintextPolicy::AllowedForDevGradeRoot
969    } else {
970        ceremony::PlaintextPolicy::Refuse
971    };
972
973    // A scripted run cannot answer a prompt or type a passphrase. It only gets
974    // here for a dev-grade root, where an unencrypted backup adds no exposure.
975    let break_glass = if options.non_interactive {
976        let recipient = ceremony::generate_software_identity(&paths.break_glass_identity())?;
977        ceremony::BreakGlass::PlaintextIdentity {
978            identity_file: paths.break_glass_identity(),
979            recipient,
980        }
981    } else {
982        println!();
983        println!("    A deployment root needs a second recipient, or losing the primary loses");
984        println!("    the root. The root is exactly as strong as its weakest recipient.");
985        let choice = Select::new(
986            "  How should the break-glass recipient be protected?",
987            vec![SECOND_TOKEN, PASSPHRASE, PLAINTEXT],
988        )
989        .with_starting_cursor(if mode.is_dev_grade() { 1 } else { 0 })
990        .prompt()
991        .map_err(|e| anyhow::anyhow!("no break-glass recipient was chosen: {e}"))?;
992
993        match choice {
994            SECOND_TOKEN => {
995                println!("    Prepare the second token elsewhere with:");
996                println!(
997                    "      age-plugin-yubikey --generate --name \"hyprstream break-glass\" \\"
998                );
999                println!("        --pin-policy always --touch-policy always");
1000                let recipient = Text::new("  Paste its age1yubikey1… recipient:")
1001                    .prompt()
1002                    .map_err(|e| anyhow::anyhow!("no break-glass recipient was entered: {e}"))?;
1003                ceremony::BreakGlass::SecondToken {
1004                    recipient: recipient.trim().to_owned(),
1005                }
1006            }
1007            PASSPHRASE => {
1008                let destination = Text::new("  Where should the encrypted backup identity go?")
1009                    .with_default(&paths.break_glass_identity().display().to_string())
1010                    .prompt()
1011                    .map_err(|e| anyhow::anyhow!("no backup destination was entered: {e}"))?;
1012                let destination = std::path::PathBuf::from(destination.trim());
1013                println!("    Choose a passphrase and store it apart from the file itself.");
1014                let recipient = ceremony::generate_passphrase_encrypted_identity(&destination)?;
1015                match ceremony::classify_identity_file(
1016                    &std::fs::read_to_string(&destination).unwrap_or_default(),
1017                ) {
1018                    ceremony::IdentityFileKind::PassphraseEncrypted => {}
1019                    ceremony::IdentityFileKind::PlaintextAgeIdentity => {
1020                        return Err(anyhow::anyhow!(
1021                            "{} was written unencrypted; delete it and retry",
1022                            destination.display()
1023                        ));
1024                    }
1025                    ceremony::IdentityFileKind::Unconfirmed => {
1026                        println!(
1027                            "    Note: {} is encrypted, but its passphrase stanza could not be \
1028                             confirmed from here.",
1029                            destination.display()
1030                        );
1031                    }
1032                }
1033                ceremony::BreakGlass::PassphraseEncrypted {
1034                    identity_file: destination,
1035                    recipient,
1036                }
1037            }
1038            _ => {
1039                let recipient =
1040                    ceremony::generate_software_identity(&paths.break_glass_identity())?;
1041                ceremony::BreakGlass::PlaintextIdentity {
1042                    identity_file: paths.break_glass_identity(),
1043                    recipient,
1044                }
1045            }
1046        }
1047    };
1048
1049    if let Err(reason) = ceremony::validate_break_glass(&break_glass, primary_recipient, policy) {
1050        return Err(anyhow::anyhow!("{reason}"));
1051    }
1052    Ok(break_glass)
1053}
1054
1055// ─────────────────────────────────────────────────────────────────────────────
1056// Phase 7: Services
1057// ─────────────────────────────────────────────────────────────────────────────
1058
1059fn text_phase_services(
1060    backend: &mut impl WizardBackend,
1061    _config_services: &[String],
1062    non_interactive: bool,
1063    start_flag: bool,
1064) -> Result<()> {
1065    println!("  Phase 7: Services");
1066    println!("  {}", "-".repeat(40));
1067    println!();
1068
1069    let should_start = if start_flag {
1070        true
1071    } else if non_interactive {
1072        false
1073    } else {
1074        Confirm::new("  Start services now?")
1075            .with_default(true)
1076            .prompt()
1077            .unwrap_or(false)
1078    };
1079
1080    if should_start {
1081        backend.start_services();
1082
1083        loop {
1084            match backend.poll_pending() {
1085                OpStatus::InProgress => {
1086                    std::thread::sleep(std::time::Duration::from_millis(200));
1087                }
1088                OpStatus::Done => {
1089                    print_check("Services", CheckStatus::Ok, "started");
1090                    break;
1091                }
1092                OpStatus::Failed(e) => {
1093                    print_check("Services", CheckStatus::Fail, &format!("failed: {e}"));
1094                    break;
1095                }
1096            }
1097        }
1098    } else {
1099        println!("    Services not started.");
1100        println!();
1101        println!("    To start later:");
1102        println!("      hyprstream service start");
1103    }
1104
1105    println!();
1106    Ok(())
1107}
1108
1109// ─────────────────────────────────────────────────────────────────────────────
1110// Summary
1111// ─────────────────────────────────────────────────────────────────────────────
1112
1113fn print_summary(summary: &TextWizardSummary) {
1114    println!("  {}", "=".repeat(40));
1115    println!("  Setup Complete");
1116    println!("  {}", "=".repeat(40));
1117    println!();
1118
1119    if !summary.templates_applied.is_empty() {
1120        println!("  Templates: {}", summary.templates_applied.join(", "));
1121    }
1122
1123    if !summary.users_created.is_empty() {
1124        println!("  Users:");
1125        for (username, role) in &summary.users_created {
1126            println!("    {username} ({role})");
1127        }
1128    }
1129
1130    if !summary.tokens_generated.is_empty() {
1131        println!("  Tokens:");
1132        for (username, preview, expires) in &summary.tokens_generated {
1133            println!("    {username} — {preview} (expires {expires})");
1134        }
1135    }
1136
1137    if let Some(deployment_trust) = &summary.deployment_trust {
1138        println!("  Deployment trust: {deployment_trust}");
1139    }
1140
1141    if summary.templates_applied.is_empty()
1142        && summary.users_created.is_empty()
1143        && summary.tokens_generated.is_empty()
1144        && summary.deployment_trust.is_none()
1145    {
1146        println!("  Environment bootstrapped with default settings.");
1147    }
1148
1149    println!();
1150    println!("  Next steps:");
1151    println!("    hyprstream service start          # Start services");
1152    println!("    hyprstream quick list              # List available models");
1153    println!("    hyprstream quick clone <model>     # Clone a model");
1154    println!("    hyprstream quick infer <model>     # Run inference");
1155    println!();
1156}
1157
1158#[cfg(test)]
1159mod wizard_launch_routing_tests {
1160    #![allow(clippy::expect_used, clippy::unwrap_used)]
1161
1162    use super::*;
1163    use std::cell::Cell;
1164    use std::collections::VecDeque;
1165    use std::sync::Arc;
1166
1167    use parking_lot::Mutex;
1168
1169    /// Gate marking a re-exec'd child that runs one routing scenario in an
1170    /// isolated process (the pinned/explicit slots are process-global and
1171    /// write-once, so each scenario needs its own process — same pattern as
1172    /// `config::pinned_config_tests`).
1173    const PRE_INSTALL_CHILD: &str = "HYPRSTREAM_WIZARD_PRE_CHILD";
1174
1175    /// All four configuration profiles through the real pre-install decision:
1176    /// default installs with the loaded requirement; explicit-config and
1177    /// required-native skip fixed-unit installation; an unloadable
1178    /// configuration fails closed instead of falling back to defaults.
1179    #[tokio::test]
1180    async fn wizard_pre_install_step_routes_profiles_causally() -> anyhow::Result<()> {
1181        if let Ok(scenario) = std::env::var(PRE_INSTALL_CHILD) {
1182            return pre_install_child_scenario(&scenario).await;
1183        }
1184        for scenario in ["default", "explicit", "required", "invalid"] {
1185            let status = std::process::Command::new(std::env::current_exe()?)
1186                .args([
1187                    "--exact",
1188                    "cli::wizard_handlers::wizard_launch_routing_tests::wizard_pre_install_step_routes_profiles_causally",
1189                    "--nocapture",
1190                ])
1191                .env(PRE_INSTALL_CHILD, scenario)
1192                .status()?;
1193            anyhow::ensure!(
1194                status.success(),
1195                "wizard pre-install routing scenario '{scenario}' failed"
1196            );
1197        }
1198        Ok(())
1199    }
1200
1201    async fn pre_install_child_scenario(scenario: &str) -> anyhow::Result<()> {
1202        let called: Arc<Mutex<Vec<bool>>> = Arc::new(Mutex::new(Vec::new()));
1203        let sink = called.clone();
1204        let record_install = |required: bool| {
1205            sink.lock().push(required);
1206            async { Ok::<(), anyhow::Error>(()) }
1207        };
1208
1209        match scenario {
1210            "default" => {
1211                let _ = crate::config::install_pinned_config(crate::config::HyprConfig::default());
1212                wizard_pre_install_step(record_install).await?;
1213                assert_eq!(
1214                    *called.lock(),
1215                    vec![false],
1216                    "default profile must install fixed units, forwarding the loaded (non-required) profile"
1217                );
1218            }
1219            "explicit" => {
1220                let _ = crate::config::install_pinned_config(crate::config::HyprConfig::default());
1221                let explicit = tempfile::tempdir()?;
1222                let marker = explicit.path().join("operator.toml");
1223                assert!(
1224                    crate::config::install_explicit_config_path(marker),
1225                    "explicit provenance slot must be installable in a fresh child"
1226                );
1227                wizard_pre_install_step(record_install).await?;
1228                assert!(
1229                    called.lock().is_empty(),
1230                    "explicit --config provenance must skip fixed-unit installation"
1231                );
1232            }
1233            "required" => {
1234                let mut required_config = crate::config::HyprConfig::default();
1235                required_config.quic.enabled = true;
1236                required_config.quic.iroh = true;
1237                required_config.quic.native_network_profile =
1238                    crate::config::NativeNetworkProfile::NetworkIrohRequired;
1239                required_config.validate()?;
1240                let _ = crate::config::install_pinned_config(required_config);
1241                assert!(
1242                    crate::config::HyprConfig::load()?.quic.iroh_required(),
1243                    "precondition: the pinned child config must load as required-native"
1244                );
1245                wizard_pre_install_step(record_install).await?;
1246                assert!(
1247                    called.lock().is_empty(),
1248                    "required-native profile must skip fixed-unit installation"
1249                );
1250            }
1251            "invalid" => {
1252                // No pinned snapshot: force the XDG re-derivation onto a
1253                // garbage config file so HyprConfig::load() itself fails.
1254                let root = tempfile::tempdir()?;
1255                let xdg = root.path().join("xdg-config");
1256                std::env::set_var("XDG_CONFIG_HOME", &xdg);
1257                let config_dir = xdg.join("hyprstream");
1258                std::fs::create_dir_all(&config_dir)?;
1259                std::fs::write(config_dir.join("config.toml"), "this is = not [valid toml")?;
1260                let outcome = wizard_pre_install_step(record_install).await;
1261                assert!(
1262                    outcome.is_err(),
1263                    "an unloadable configuration must fail closed, not resolve to the default profile"
1264                );
1265                assert!(
1266                    called.lock().is_empty(),
1267                    "fixed-unit installation must not run when the configuration cannot be loaded"
1268                );
1269            }
1270            other => anyhow::bail!("unknown wizard routing scenario '{other}'"),
1271        }
1272        Ok(())
1273    }
1274
1275    /// Recording `WizardBackend` that only implements the services phase and
1276    /// delegates every other method to `MockWizardBackend`.
1277    struct ServicesPhaseBackend {
1278        inner: MockWizardBackend,
1279        start_calls: Cell<usize>,
1280        poll_script: std::cell::RefCell<VecDeque<OpStatus>>,
1281    }
1282
1283    impl ServicesPhaseBackend {
1284        fn new() -> Self {
1285            Self {
1286                inner: MockWizardBackend::new(),
1287                start_calls: Cell::new(0),
1288                poll_script: std::cell::RefCell::new(VecDeque::new()),
1289            }
1290        }
1291
1292        fn with_poll_script(script: Vec<OpStatus>) -> Self {
1293            Self {
1294                poll_script: std::cell::RefCell::new(script.into()),
1295                ..Self::new()
1296            }
1297        }
1298    }
1299
1300    impl WizardBackend for ServicesPhaseBackend {
1301        fn detect_environment(&mut self) -> EnvironmentInfo {
1302            self.inner.detect_environment()
1303        }
1304        fn recommend_action(&self, env: &EnvironmentInfo) -> InstallAction {
1305            self.inner.recommend_action(env)
1306        }
1307        fn start_install(&mut self, variant: &LibtorchVariant) {
1308            self.inner.start_install(variant);
1309        }
1310        fn poll_install(&mut self) -> InstallPoll {
1311            self.inner.poll_install()
1312        }
1313        fn start_bootstrap(&mut self) {
1314            self.inner.start_bootstrap();
1315        }
1316        fn poll_bootstrap(&mut self) -> BootstrapPoll {
1317            self.inner.poll_bootstrap()
1318        }
1319        fn has_existing_policy(&self) -> bool {
1320            self.inner.has_existing_policy()
1321        }
1322        fn apply_template(&mut self, name: &str) {
1323            self.inner.apply_template(name);
1324        }
1325        fn add_user(&mut self, username: &str, role: &str) {
1326            self.inner.add_user(username, role);
1327        }
1328        fn add_user_custom(&mut self, username: &str, resource: &str, actions: &[String]) {
1329            self.inner.add_user_custom(username, resource, actions);
1330        }
1331        fn save_policies(&mut self) {
1332            self.inner.save_policies();
1333        }
1334        fn generate_token(&mut self, username: &str, duration: &str) -> TokenResult {
1335            self.inner.generate_token(username, duration)
1336        }
1337        fn start_services(&mut self) {
1338            self.start_calls.set(self.start_calls.get() + 1);
1339        }
1340        fn poll_pending(&mut self) -> OpStatus {
1341            self.poll_script
1342                .borrow_mut()
1343                .pop_front()
1344                .unwrap_or(OpStatus::Done)
1345        }
1346        fn local_username(&self) -> String {
1347            self.inner.local_username()
1348        }
1349        fn templates(&self) -> Vec<TemplateInfo> {
1350            self.inner.templates()
1351        }
1352    }
1353
1354    /// Setup without startup: the non-interactive services phase with no start
1355    /// flag must never invoke the backend's service start.
1356    #[test]
1357    fn services_phase_skips_startup_without_start_flag() -> Result<()> {
1358        let mut backend = ServicesPhaseBackend::new();
1359        text_phase_services(&mut backend, &["policy".to_owned()], true, false)?;
1360        assert_eq!(
1361            backend.start_calls.get(),
1362            0,
1363            "non-interactive wizard without --start-services must not start services"
1364        );
1365        Ok(())
1366    }
1367
1368    /// A requested start drives the backend through the pending poll loop to a
1369    /// terminal status — the phase is the wizard-side boundary that decides
1370    /// whether BootstrapManager's launch routing runs at all.
1371    #[test]
1372    fn services_phase_requested_start_polls_to_done() -> Result<()> {
1373        let mut backend =
1374            ServicesPhaseBackend::with_poll_script(vec![OpStatus::InProgress, OpStatus::Done]);
1375        text_phase_services(&mut backend, &["policy".to_owned()], true, true)?;
1376        assert_eq!(
1377            backend.start_calls.get(),
1378            1,
1379            "requested startup must invoke the backend start exactly once"
1380        );
1381        Ok(())
1382    }
1383
1384    /// A failed start surfaces through the same phase without hanging.
1385    #[test]
1386    fn services_phase_surfaces_start_failure() -> Result<()> {
1387        let mut backend =
1388            ServicesPhaseBackend::with_poll_script(vec![OpStatus::Failed("boom".to_owned())]);
1389        text_phase_services(&mut backend, &[], true, true)?;
1390        assert_eq!(backend.start_calls.get(), 1);
1391        Ok(())
1392    }
1393}