phoebus_os/installer-rs/crates/phoebus-installer/src/main.rs
Phoebus c6665e550a fix(ai): refuse proposals that weaken required settings
Deterministic review now rejects encryption=none, filesystem=ext4 and the
aggressive kernel profile, so the LUKS2/Btrfs/stability posture cannot be
traded for convenience. A live provider that returns an invalid proposal is
reported and the installer continues with the proven defaults (the explicit
--ai-proposal-file test path still fails loudly).
2026-09-20 05:04:12 -07:00

383 lines
12 KiB
Rust

//! Phoebus OS installer CLI.
//!
//! With no mode flags on a terminal, the text UI starts. The deterministic
//! backend is available directly with `--plan`, `--dry-run` and `--install`.
//! Secrets are supplied through files, never on the command line.
use std::io::Write;
use std::path::PathBuf;
use std::process::ExitCode;
use clap::Parser;
use phoebus_ai::provider::ProviderKind;
use phoebus_core::{InstallConfig, Redactor, SecretString};
use phoebus_executor::{
authorize, AutoConfirm, Confirmation, DestructiveAuthorization, Exec, Logger, RealRunner,
Result,
};
use phoebus_installer::Installer;
use phoebus_tui::TuiOutcome;
/// Pinned OpenCode release manifest. Embedded so the static binary needs no
/// runtime resources. See `resources/opencode.manifest`.
const OPENCODE_MANIFEST: &str = include_str!("../resources/opencode.manifest");
/// Resolve the manifest text. `PHOEBUS_OPENCODE_MANIFEST` overrides the
/// embedded copy so a fixture can be verified end to end (tests, mirrors).
fn opencode_manifest() -> std::io::Result<String> {
match std::env::var("PHOEBUS_OPENCODE_MANIFEST") {
Ok(path) if !path.is_empty() => std::fs::read_to_string(path),
_ => Ok(OPENCODE_MANIFEST.to_string()),
}
}
#[derive(Parser, Debug)]
#[command(
name = "phoebus-installer",
version,
about = "Phoebus OS installer (deterministic backend + TUI)"
)]
struct Cli {
/// Load configuration from a file (TOML or the legacy flat format).
#[arg(long)]
config: Option<PathBuf>,
/// Render the installation plan and exit.
#[arg(long)]
plan: bool,
/// Do not execute commands or modify the target.
#[arg(long)]
dry_run: bool,
/// Run the deterministic backend without the TUI.
#[arg(long)]
install: bool,
/// Skip interactive confirmations (for unattended installs).
#[arg(long, short = 'y')]
yes: bool,
/// Read the LUKS passphrase from a 0600 file.
#[arg(long)]
luks_passphrase_file: Option<PathBuf>,
/// Read the user password from a 0600 file.
#[arg(long)]
user_password_file: Option<PathBuf>,
/// Read the root password from a 0600 file.
#[arg(long)]
root_password_file: Option<PathBuf>,
/// Write the effective configuration as TOML and exit.
#[arg(long)]
save_config: Option<PathBuf>,
/// Fetch and verify the pinned OpenCode release, then exit.
#[arg(long)]
bootstrap_opencode: bool,
/// Enable AI-assisted optimization (opt-in). The facts sent are shown first.
#[arg(long)]
ai: bool,
/// AI provider: `deepseek`, `openai`/`chatgpt`, or `none`.
#[arg(long, value_name = "PROVIDER")]
ai_provider: Option<String>,
/// Model name override for the selected provider.
#[arg(long, value_name = "MODEL")]
ai_model: Option<String>,
/// Read the provider API key from a mode-0600 file (never stored in config).
#[arg(long, value_name = "FILE")]
ai_api_key_file: Option<PathBuf>,
/// Apply a proposal from a file (a chat response or a bare proposal JSON).
#[arg(long, value_name = "FILE")]
ai_proposal_file: Option<PathBuf>,
/// Print the system facts that would be sent to the model, then exit.
#[arg(long)]
ai_facts: bool,
}
struct TerminalConfirm;
impl Confirmation for TerminalConfirm {
fn confirm_erase(&self, preview: &str) -> Result<bool> {
println!("\n{preview}");
print!("\nType ERASE to continue: ");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin().read_line(&mut line).map_err(|e| {
phoebus_executor::ExecError::operation("confirm", "erase", e.to_string())
})?;
Ok(line.trim() == "ERASE")
}
fn confirm_final(&self, message: &str) -> Result<bool> {
print!("{message} [y/N] ");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin().read_line(&mut line).map_err(|e| {
phoebus_executor::ExecError::operation("confirm", "final", e.to_string())
})?;
Ok(matches!(
line.trim().to_ascii_lowercase().as_str(),
"y" | "yes"
))
}
}
fn read_secret(path: &PathBuf) -> std::io::Result<SecretString> {
let value = std::fs::read_to_string(path)?;
Ok(SecretString::new(value.trim_end_matches(['\n', '\r'])))
}
/// The provider selected on the command line, or the one the TUI/config chose.
fn resolve_provider(
cli: &Cli,
config: &InstallConfig,
) -> std::result::Result<ProviderKind, Box<dyn std::error::Error>> {
let raw = cli
.ai_provider
.as_deref()
.unwrap_or(config.ai.provider.as_str());
ProviderKind::parse(raw)
.ok_or_else(|| format!("unknown AI provider `{raw}` (use deepseek, openai or none)").into())
}
/// Apply AI guidance to the configuration before the plan is shown or install
/// runs. The model never sees secrets and never executes anything: its response
/// is reviewed with mandatory evidence and applied atomically.
fn run_ai_guidance(
cli: &Cli,
installer: &mut Installer,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
let provider = resolve_provider(cli, &installer.config)?;
let wants_ai = cli.ai || cli.ai_proposal_file.is_some() || installer.config.ai.enabled;
if !wants_ai {
return Ok(());
}
if let Some(path) = &cli.ai_proposal_file {
let outcome = phoebus_installer::ai_guide::review_file(&mut installer.config, path)?;
println!("{}", outcome.render());
return Ok(());
}
if provider == ProviderKind::None {
eprintln!("AI assistance is enabled but no provider is selected; continuing without AI.");
return Ok(());
}
// Opt-in: show exactly what leaves the machine before sending it.
let facts = installer.system_facts();
eprintln!(
"Sending these system facts to {} (no passwords, passphrases or files):",
provider.as_str()
);
eprintln!("{}", facts.render());
let key_path = cli
.ai_api_key_file
.as_ref()
.ok_or("--ai-api-key-file is required for a live AI provider")?;
let api_key = phoebus_executor::ai::load_api_key(key_path)?;
let model = cli.ai_model.clone().unwrap_or_default();
let transport = phoebus_executor::ai::CurlTransport::new(&installer.exec, api_key);
match phoebus_installer::ai_guide::generate_and_review(
&mut installer.config,
&facts,
provider,
&model,
&transport,
) {
Ok(outcome) => println!("{}", outcome.render()),
Err(e) => eprintln!("AI proposal rejected; continuing with the proven defaults: {e}"),
}
Ok(())
}
fn main() -> ExitCode {
match run() {
Ok(code) => code,
Err(e) => {
eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
let cli = Cli::parse();
let mut config = if let Some(path) = &cli.config {
InstallConfig::load_from_path(path)?
} else {
InstallConfig::default()
};
if cli.dry_run {
config.runtime.dry_run = true;
}
if cli.yes {
config.runtime.assume_yes = true;
}
// Secrets may come from CLI files or the TUI.
let mut luks = cli
.luks_passphrase_file
.as_ref()
.map(read_secret)
.transpose()?;
let mut user_pw = cli
.user_password_file
.as_ref()
.map(read_secret)
.transpose()?;
let root_pw = cli
.root_password_file
.as_ref()
.map(read_secret)
.transpose()?;
let mut tui_confirmed = false;
let mut do_install = cli.install;
// TUI when no explicit mode and a terminal is present.
if !cli.plan && !cli.install && !cli.dry_run && !cli.bootstrap_opencode && phoebus_tui::is_tty()
{
match phoebus_tui::run(config.clone())? {
TuiOutcome::Exit => return Ok(ExitCode::SUCCESS),
TuiOutcome::Save(saved) => {
let path = cli
.config
.clone()
.unwrap_or_else(|| PathBuf::from("phoebus-install.toml"));
std::fs::write(&path, saved.to_toml_string()?)?;
println!("wrote {}", path.display());
return Ok(ExitCode::SUCCESS);
}
TuiOutcome::Install(saved, tui_luks, tui_user) => {
config = saved;
if luks.is_none() {
luks = tui_luks;
}
if user_pw.is_none() {
user_pw = tui_user;
}
do_install = true;
tui_confirmed = true;
}
}
}
let mut state_dir = PathBuf::from(&config.runtime.state_dir);
if std::fs::create_dir_all(&state_dir).is_err() {
state_dir = PathBuf::from("/tmp/phoebus-installer");
std::fs::create_dir_all(&state_dir).ok();
}
let log_path = state_dir.join("install.log");
let echo = std::env::var("PHOEBUS_LOG_ECHO")
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "yes" | "1" | "true"))
.unwrap_or(false);
let logger = Logger::open(&log_path, Redactor::new(), echo);
let root = if config.runtime.dry_run {
let sandbox = state_dir.join("dry-run-root");
std::fs::create_dir_all(&sandbox).ok();
sandbox
} else {
PathBuf::from(&config.storage.install_root)
};
let exec = Exec::new(
Box::new(RealRunner),
logger,
config.runtime.dry_run,
root,
state_dir.clone(),
);
for secret in [&luks, &user_pw, &root_pw].into_iter().flatten() {
exec.register_secret(secret);
}
if cli.bootstrap_opencode {
let manifest = phoebus_executor::opencode::Manifest::parse(&opencode_manifest()?);
let dest = phoebus_executor::opencode::bin_dir(&state_dir);
let installed = phoebus_executor::opencode::ensure(&exec, &manifest, &dest)?;
println!("OpenCode ready at {}", installed.display());
return Ok(ExitCode::SUCCESS);
}
let mut installer = Installer::new(config, exec);
if cli.ai_facts {
println!("{}", installer.system_facts().render());
return Ok(ExitCode::SUCCESS);
}
run_ai_guidance(&cli, &mut installer)?;
if let Some(path) = &cli.save_config {
std::fs::write(path, installer.config.to_toml_string()?)?;
println!("wrote {}", path.display());
}
// Plan / default mode.
if cli.plan || !do_install {
print!("{}", installer.render_plan());
let issues = installer.validate();
println!("\nValidation:");
if issues.is_empty() {
println!(" OK");
} else {
for issue in &issues {
println!(" - {issue}");
}
}
return Ok(ExitCode::SUCCESS);
}
// Install mode.
let issues = installer.validate();
if !issues.is_empty() {
eprintln!("configuration is incomplete:");
for issue in &issues {
eprintln!(" - {issue}");
}
return Ok(ExitCode::FAILURE);
}
print!("{}", installer.render_plan());
let auth: DestructiveAuthorization = if tui_confirmed || installer.config.runtime.assume_yes {
authorize(
&AutoConfirm,
&installer.destructive_preview(),
"Start installation?",
)?
} else {
let preview = installer.destructive_preview();
authorize(
&TerminalConfirm,
&preview,
"Start the installation now? This can take a long time.",
)?
};
installer.install(&auth, luks.as_ref(), user_pw.as_ref(), root_pw.as_ref())?;
if installer.config.runtime.dry_run {
println!(
"dry-run complete; log: {}",
installer.exec.log_path().display()
);
} else {
println!(
"installation complete; log: {}",
installer.exec.log_path().display()
);
}
Ok(ExitCode::SUCCESS)
}