Skip to main content

symforge/cli/
setup.rs

1//! `symforge setup` — guided operator setup wizard (009 US2).
2//!
3//! Orchestrates the shipped 004/005/006 capabilities (harness scan/apply,
4//! serve, admin dashboard) into one guided command: scan -> choose -> restate
5//! -> apply (with restorable backups) -> serve-start -> open -> persist. This
6//! module is the thin wizard layer; it does not reimplement scan/apply/serve.
7//!
8//! Phase 1 (T003) lands the clap arg surface + a `run` skeleton that returns a
9//! clear "not yet implemented" notice. The flow steps (scan/choose/apply/serve)
10//! and the `SetupSink` seam land in later phases (T009/T014-T019).
11
12use std::io::{BufRead, Write};
13use std::net::{IpAddr, Ipv4Addr, SocketAddr};
14use std::time::Duration;
15
16use anyhow::Context;
17use clap::{Args, ValueEnum};
18use serde::{Deserialize, Serialize};
19
20use crate::cli::admin::{
21    ADMIN_SERVE_START_DEADLINE, FOREGROUND_SERVE_NOTICE, ServerSessionDescriptor,
22    operator_server_reachable, start_operator_server,
23};
24use crate::cli::browser::{BrowserOpener, OsBrowserOpener};
25use crate::cli::harness::{AttachEntry, HarnessId, HarnessRegistry, HarnessState};
26use crate::cli::harness_apply::{self, ApplyOutcome, PlannedAction};
27use crate::cli::operator_profile::{AuthPosture, OperatorSetupProfile};
28use crate::server::serve::DEFAULT_LISTEN;
29
30/// Which parts of SymForge a setup run configures.
31///
32/// Mirrors the `--installation-type` contract values (contracts/setup-cli.md):
33/// `in-harness` configures harness MCP attach only; `server` starts the
34/// operator server/dashboard; `both` does both. The serde rename pair matches the
35/// clap `value(name = ...)` so the CLI flag, the profile JSON, and the wire shape
36/// all use the same `in-harness | server | both` strings.
37#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum, Serialize, Deserialize)]
38pub enum InstallationType {
39    /// Configure harness MCP attach entries only (no operator server).
40    #[value(name = "in-harness")]
41    #[serde(rename = "in-harness")]
42    InHarness,
43    /// Start the operator server / dashboard.
44    #[serde(rename = "server")]
45    Server,
46    /// Configure harnesses and start the operator server.
47    #[serde(rename = "both")]
48    Both,
49}
50
51/// Flags for `symforge setup` (see `contracts/setup-cli.md`).
52#[derive(Args, Debug, Clone)]
53pub struct SetupCliArgs {
54    /// Drive with pre-supplied answers: no terminal read, no browser, no network
55    /// probe beyond the bind (FR-014).
56    #[arg(long)]
57    pub non_interactive: bool,
58
59    /// Pre-answer the install type (`in-harness` | `server` | `both`).
60    #[arg(long, value_enum)]
61    pub installation_type: Option<InstallationType>,
62
63    /// Preferred bind port (else the verified-free suggestion).
64    #[arg(long)]
65    pub port: Option<u16>,
66
67    /// Comma-separated harness ids to configure (else all detected).
68    #[arg(long, value_delimiter = ',')]
69    pub harnesses: Vec<String>,
70
71    /// Auto-confirm the restated action plan (for scripts).
72    #[arg(long)]
73    pub yes: bool,
74}
75
76/// Operator-facing I/O seam for the setup wizard (E6, contracts/seams.md).
77///
78/// Every terminal side effect goes through this trait so the whole flow runs in
79/// tests with scripted answers and zero real terminal reads (FR-017/FR-014).
80/// Mirrors the shipped `OnboardingSink` seam (`cli::onboarding`).
81pub trait SetupSink {
82    /// Emit a progress / summary line.
83    fn status(&mut self, line: &str);
84    /// Ask the operator to pick one of `opts`; returns the chosen index.
85    fn ask_choice(&mut self, q: &str, opts: &[&str]) -> usize;
86    /// Restate the exact action plan and ask for confirmation (FR-008).
87    fn confirm(&mut self, action_plan: &str) -> bool;
88}
89
90/// Real terminal sink: prints to stderr and reads a line from stdin.
91///
92/// `ask_choice` numbers the options and parses a 1-based index (out-of-range or
93/// unparseable input falls back to the first option — a safe default that never
94/// panics). `confirm` parses a `y`/`yes` (case-insensitive) as `true`, anything
95/// else as `false`.
96pub struct StderrSetupSink;
97
98impl SetupSink for StderrSetupSink {
99    fn status(&mut self, line: &str) {
100        eprintln!("{line}");
101    }
102
103    fn ask_choice(&mut self, q: &str, opts: &[&str]) -> usize {
104        eprintln!("{q}");
105        for (i, opt) in opts.iter().enumerate() {
106            eprintln!("  {}) {opt}", i + 1);
107        }
108        eprint!("> ");
109        let _ = std::io::stderr().flush();
110        let line = read_stdin_line();
111        match line.trim().parse::<usize>() {
112            Ok(n) if (1..=opts.len()).contains(&n) => n - 1,
113            // Unparseable / out of range: default to the first option rather than
114            // looping or panicking — the caller restates before any change.
115            _ => 0,
116        }
117    }
118
119    fn confirm(&mut self, action_plan: &str) -> bool {
120        eprintln!("{action_plan}");
121        eprint!("Proceed? [y/N] ");
122        let _ = std::io::stderr().flush();
123        let line = read_stdin_line();
124        matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes")
125    }
126}
127
128/// Read one line from stdin, returning an empty string on EOF / read error so the
129/// caller's parsing applies its safe default rather than the sink panicking.
130fn read_stdin_line() -> String {
131    let mut line = String::new();
132    let stdin = std::io::stdin();
133    let _ = stdin.lock().read_line(&mut line);
134    line
135}
136
137/// Test sink: returns pre-scripted answers and records every prompt; never reads
138/// stdin (FR-014). Construct with a queue of choice indices and a single confirm
139/// answer.
140#[derive(Debug, Default)]
141pub struct ScriptedSetupSink {
142    /// Pre-supplied `ask_choice` answers, consumed front-to-back.
143    choices: std::collections::VecDeque<usize>,
144    /// The answer every `confirm` returns.
145    confirm_answer: bool,
146    /// Every `status` line emitted, in order.
147    pub statuses: Vec<String>,
148    /// Every `ask_choice` question + its options, in order.
149    pub questions: Vec<String>,
150    /// Every `confirm` action plan presented, in order.
151    pub confirmations: Vec<String>,
152}
153
154impl ScriptedSetupSink {
155    /// Build a scripted sink with the given choice answers and confirm result.
156    pub fn new(choices: impl IntoIterator<Item = usize>, confirm_answer: bool) -> Self {
157        Self {
158            choices: choices.into_iter().collect(),
159            confirm_answer,
160            statuses: Vec::new(),
161            questions: Vec::new(),
162            confirmations: Vec::new(),
163        }
164    }
165}
166
167impl SetupSink for ScriptedSetupSink {
168    fn status(&mut self, line: &str) {
169        self.statuses.push(line.to_string());
170    }
171
172    fn ask_choice(&mut self, q: &str, opts: &[&str]) -> usize {
173        self.questions.push(format!("{q} [{}]", opts.join(", ")));
174        // Pop the next scripted answer; if the script is exhausted, default to the
175        // first option (deterministic, never reads stdin, never panics).
176        self.choices.pop_front().unwrap_or(0)
177    }
178
179    fn confirm(&mut self, action_plan: &str) -> bool {
180        self.confirmations.push(action_plan.to_string());
181        self.confirm_answer
182    }
183}
184
185/// Injectable paths for the wizard (FR-017/018). Tests pass a temp home + project.
186#[derive(Debug, Clone)]
187pub struct SetupContext {
188    pub home: std::path::PathBuf,
189    pub working_dir: std::path::PathBuf,
190}
191
192impl SetupContext {
193    /// Build from the live process environment.
194    pub fn from_env() -> anyhow::Result<Self> {
195        let home = dirs::home_dir().context("cannot determine home directory")?;
196        let working_dir =
197            std::env::current_dir().context("cannot determine current working directory")?;
198        Ok(Self { home, working_dir })
199    }
200
201    /// Where [`OperatorSetupProfile`] is stored (`<project>/.symforge/`).
202    pub fn project_base(&self) -> std::path::PathBuf {
203        self.working_dir.clone()
204    }
205
206    /// The harness registry resolved against this context's home + working dir.
207    /// Fixture seam: tests build the context over a TempDir so the wizard scans
208    /// fixture configs, never the real operator's (FR-018).
209    pub fn registry(&self) -> HarnessRegistry {
210        HarnessRegistry::known_with(&self.home, &self.working_dir)
211    }
212}
213
214/// The result of one wizard run, returned for caller messaging and test
215/// assertions (FR-017: every effect is observable without scraping stderr).
216///
217/// Production [`run`] discards it after the sink has already narrated each step;
218/// tests inspect it to assert outcomes deterministically — the apply results,
219/// the reachable server descriptor, the persisted profile — over fixtures.
220#[derive(Debug)]
221pub struct WizardOutcome {
222    /// The installation type the wizard actually ran with.
223    pub installation_type: InstallationType,
224    /// The running operator server (started or reused) for a server mode; always
225    /// reachable when present (FR-020). `None` for in-harness-only or a decline.
226    pub session: Option<ServerSessionDescriptor>,
227    /// `true` when a server mode reused an already-reachable server instead of
228    /// starting a second one (FR-013 idempotency / SC-004).
229    pub reused_server: bool,
230    /// Per-harness apply outcomes (empty unless `installation_type == Both`).
231    pub harness_outcomes: Vec<ApplyOutcome>,
232    /// The browser-open outcome for the dashboard, if a server was reported.
233    pub browser_outcome: Option<crate::cli::browser::BrowserOpenOutcome>,
234    /// The profile persisted by this run (FR-012). On a decline this carries the
235    /// would-be choices but was NOT written to disk (`cancelled == true`).
236    pub profile: OperatorSetupProfile,
237    /// `true` when the operator declined the restated plan; nothing was changed.
238    pub cancelled: bool,
239}
240
241/// Entry point for `symforge setup`. Wires the real seams (stderr sink, OS
242/// browser, live home/cwd) into [`run_wizard`] and discards the outcome — the
243/// sink has already narrated every step to the operator.
244pub fn run(args: SetupCliArgs) -> anyhow::Result<()> {
245    let ctx = SetupContext::from_env()?;
246    if args.non_interactive {
247        // Non-interactive answers are pre-supplied (FR-014); `--yes` is the
248        // scripted confirmation, so no terminal read occurs.
249        let mut sink = ScriptedSetupSink::new([], args.yes);
250        let browser = crate::cli::browser::NoopBrowserOpener::default();
251        run_wizard(args, &ctx, &mut sink, &browser)?;
252    } else {
253        let mut sink = StderrSetupSink;
254        let browser = OsBrowserOpener;
255        let outcome = run_wizard(args, &ctx, &mut sink, &browser)?;
256        // D21 sibling: an interactive fresh-start server runs on a background
257        // thread that dies when this process exits — so the dashboard URL the
258        // wizard just printed would be dead the instant setup returns. Hold the
259        // foreground and keep serving until Ctrl-C; a reused server (owned by
260        // another process) returns immediately. The non-interactive branch above
261        // never blocks (scripting / CI must return).
262        // Manual-verification contract: the seam's reuse-vs-block behavior is unit-
263        // tested directly (setup_holds_foreground_*/setup_does_not_hold_*), but
264        // `run`'s own wiring — INTERACTIVE branch calls the seam, non-interactive
265        // branch never does — rides on `from_env` (un-seamed real home/cwd) and is
266        // pinned by an interactive TTY run, not an in-lib test.
267        serve_foreground_if_wizard_started(&outcome, block_until_ctrl_c)?;
268    }
269    Ok(())
270}
271
272/// Keep an interactive `symforge setup` in the foreground when the wizard STARTED
273/// the operator server, so the "Dashboard: <url>" it just printed actually keeps
274/// serving (D21 sibling of the admin-verb fix). A reused server is owned by
275/// another process (return immediately); a run that started nothing (in-harness
276/// mode, or a declined plan) also returns. Only a server we started ourselves
277/// must be held alive here, blocking in `wait_for_shutdown` until the operator
278/// stops the process (Ctrl-C in production).
279///
280/// The non-interactive / scripted path (FR-014) never reaches this — [`run`]
281/// returns there so scripts and CI don't hang, and its `ScriptedSetupSink` prints
282/// nothing to a human, so a transient verify-server dying with the process makes
283/// no false promise. Split from [`run`] and generic over the waiter so the
284/// reuse-vs-block decision is unit-testable without an unstoppable Ctrl-C wait.
285/// Mirrors `admin::serve_foreground_if_started`.
286fn serve_foreground_if_wizard_started(
287    outcome: &WizardOutcome,
288    wait_for_shutdown: impl FnOnce(&ServerSessionDescriptor) -> anyhow::Result<()>,
289) -> anyhow::Result<()> {
290    if outcome.reused_server {
291        return Ok(());
292    }
293    let Some(session) = outcome.session.as_ref() else {
294        return Ok(());
295    };
296    eprintln!("{FOREGROUND_SERVE_NOTICE}");
297    wait_for_shutdown(session)
298}
299
300/// Block until the operator asks the process to stop (Ctrl-C on all platforms) on
301/// a sibling current-thread runtime — [`run`] is synchronous and the operator
302/// server owns its own thread + runtime, so this is never a nested reactor.
303///
304/// ponytail: a 5-line twin of the private `admin::block_until_ctrl_c`; reusing it
305/// would mean widening that helper's visibility in admin.rs, out of scope for this
306/// fix. Collapse the two into one shared helper if a third caller ever appears.
307fn block_until_ctrl_c(_session: &ServerSessionDescriptor) -> anyhow::Result<()> {
308    let runtime = tokio::runtime::Builder::new_current_thread()
309        .enable_all()
310        .build()?;
311    runtime.block_on(tokio::signal::ctrl_c())?;
312    Ok(())
313}
314
315/// Testable wizard core: scan -> choose -> restate/confirm -> apply -> serve ->
316/// open -> persist, with every terminal / browser / process effect behind a
317/// seam (FR-017). Tests call this directly with a [`ScriptedSetupSink`], a
318/// [`crate::cli::browser::NoopBrowserOpener`], and a TempDir-backed
319/// [`SetupContext`], then assert on the returned [`WizardOutcome`] — no real
320/// terminal, no real browser, and (apart from a deliberate loopback bind) no
321/// network (FR-014/FR-018).
322pub fn run_wizard<S: SetupSink + ?Sized, B: BrowserOpener + ?Sized>(
323    args: SetupCliArgs,
324    ctx: &SetupContext,
325    sink: &mut S,
326    browser: &B,
327) -> anyhow::Result<WizardOutcome> {
328    let placement = crate::paths::process_control_state_placement();
329    run_wizard_with_control_state(args, ctx, sink, browser, placement.directory(), None)
330}
331
332#[doc(hidden)]
333pub fn run_wizard_with_control_state<S: SetupSink + ?Sized, B: BrowserOpener + ?Sized>(
334    args: SetupCliArgs,
335    ctx: &SetupContext,
336    sink: &mut S,
337    browser: &B,
338    control_state_dir: Option<&crate::domain::ControlStateDir>,
339    // Test seam: serve a small fixture root instead of CWD-discovering (and
340    // cold-scanning) the host checkout. Production (`run_wizard`) passes None.
341    workspace_root: Option<&std::path::Path>,
342) -> anyhow::Result<WizardOutcome> {
343    let registry = ctx.registry();
344    let existing_profile = control_state_dir.and_then(OperatorSetupProfile::load);
345
346    // --- Step 1: scan (read-only, FR-004) -----------------------------------
347    let suggested_port = suggest_free_port(args.port)?;
348    sink.status(&format!(
349        "SymForge setup — OS: {} — suggested port: {suggested_port}",
350        std::env::consts::OS
351    ));
352    for status in scan_harness_summary(&registry, None) {
353        sink.status(&status);
354    }
355
356    // Report (read-only) whether a remembered server is already up (FR-004/013).
357    let remembered = existing_profile.as_ref().map(|p| p.port);
358    let mut remembered_reachable: Option<SocketAddr> = None;
359    if let Some(port) = remembered {
360        let addr = loopback_addr(port);
361        if operator_server_reachable(addr, Duration::from_millis(500)) {
362            remembered_reachable = Some(addr);
363            sink.status(&format!(
364                "Operator server already reachable on {addr} (profile port {port}) — will reuse"
365            ));
366        }
367    }
368
369    // --- Step 2: choose (FR-005/006) ----------------------------------------
370    let installation_type = resolve_installation_type(&args, sink)?;
371    let selected_ids = resolve_harness_ids(&args, &registry);
372    let bind_port = args.port.unwrap_or(suggested_port);
373    let bind_addr = loopback_addr(bind_port);
374
375    let needs_server = matches!(
376        installation_type,
377        InstallationType::Server | InstallationType::Both
378    );
379    let needs_harness_http = installation_type == InstallationType::Both;
380
381    // --- Step 3: restate + confirm (FR-008) ---------------------------------
382    // The confirm always routes through the sink so a non-interactive run uses
383    // the pre-supplied (scripted) answer and the restate is recorded for
384    // assertion. `--yes` short-circuits the prompt for scripts; an interactive
385    // decline exits having changed nothing.
386    let action_plan = build_action_plan(
387        installation_type,
388        &selected_ids,
389        bind_addr,
390        needs_server,
391        needs_harness_http,
392    );
393    if !args.yes && !sink.confirm(&action_plan) {
394        sink.status("Setup cancelled — no changes made.");
395        let profile = OperatorSetupProfile::new(
396            installation_type,
397            bind_port,
398            AuthPosture::LoopbackNoKey,
399            &selected_ids,
400            now_epoch_ms(),
401        );
402        return Ok(WizardOutcome {
403            installation_type,
404            session: None,
405            reused_server: false,
406            harness_outcomes: Vec::new(),
407            browser_outcome: None,
408            profile,
409            cancelled: true,
410        });
411    }
412    if args.yes {
413        // Still surface the plan even when auto-confirming (FR-008 visibility).
414        sink.status(&action_plan);
415    }
416
417    if installation_type == InstallationType::InHarness {
418        sink.status(
419            "In-harness (stdio) mode: configure local MCP clients with `symforge init` per client.",
420        );
421    }
422
423    // --- Step 5: server mode (FR-007/010/011/013) ---------------------------
424    let mut session: Option<ServerSessionDescriptor> = None;
425    let mut reused_server = false;
426    if needs_server {
427        if let Some(addr) = remembered_reachable {
428            // FR-013: reuse the already-running server; never start a second one.
429            session = Some(ServerSessionDescriptor::for_addr(addr, true));
430            reused_server = true;
431            sink.status(&format!("Reusing running operator server on {addr}"));
432        }
433        if session.is_none() {
434            sink.status(&format!("Starting operator server on {bind_addr}…"));
435            // FR-007: a loopback bind requires no key — `AuthConfig::refuse_to_start`
436            // permits a keyless loopback serve. A routable bind would require a key
437            // sourced from the env (api_key_env), never an inline key; serve::run
438            // enforces refuse-to-start for any non-loopback address regardless.
439            // This slice binds loopback only, so no key is passed.
440            //
441            // `explicit = args.port.is_some()`: a real `--port N` is an operator
442            // demand and must fail loudly if occupied (FR-002/003) rather than
443            // silently binding and persisting a different port than the one the
444            // action plan (Step 2, above) told the operator would be used. No
445            // `--port` means `bind_addr` is only `suggested_port` — a genuine
446            // preference, correctly soft.
447            session = Some(start_operator_server(
448                Some(bind_addr),
449                args.port.is_some(),
450                None,
451                None,
452                ADMIN_SERVE_START_DEADLINE,
453                workspace_root.map(std::path::Path::to_path_buf),
454            )?);
455        }
456        let desc = session.as_ref().expect("session started or reused");
457        sink.status(&format!("Dashboard: {}", desc.dashboard_url));
458        sink.status(&format!("Attach:    {}", desc.attach_url));
459    }
460
461    // --- Step 4: apply harness attach entries (FR-009) ----------------------
462    let mut harness_outcomes = Vec::new();
463    if needs_harness_http {
464        let desc = session
465            .as_ref()
466            .context("internal error: harness HTTP attach requires a running operator server")?;
467        let attach_entry = AttachEntry::new(desc.attach_url.clone(), None);
468        let subset = registry_subset(&registry, &selected_ids);
469        let plan = harness_apply::plan(&subset, &attach_entry);
470        sink.status("Applying harness attach entries (restorable backups)…");
471        for change in &plan.changes {
472            let label = match &change.action {
473                PlannedAction::Add => "add",
474                PlannedAction::Refresh => "refresh",
475                PlannedAction::Skip(reason) => {
476                    sink.status(&format!("  [skip] {} ({reason})", change.id.display_name()));
477                    continue;
478                }
479                PlannedAction::Error(reason) => {
480                    sink.status(&format!(
481                        "  [error] {} ({reason})",
482                        change.id.display_name()
483                    ));
484                    continue;
485                }
486            };
487            sink.status(&format!(
488                "  [{label}] {} -> {}",
489                change.id.display_name(),
490                change.config_path.display()
491            ));
492        }
493        harness_outcomes = harness_apply::apply(&plan);
494        for outcome in &harness_outcomes {
495            match outcome {
496                ApplyOutcome::Wrote {
497                    id,
498                    config_path,
499                    backup,
500                } => {
501                    let backup_note = backup
502                        .as_ref()
503                        .map(|b| format!(" (backup: {})", b.backup.display()))
504                        .unwrap_or_default();
505                    sink.status(&format!(
506                        "  [written] {} -> {}{backup_note}",
507                        id.display_name(),
508                        config_path.display()
509                    ));
510                }
511                ApplyOutcome::Skipped { id, reason } => {
512                    sink.status(&format!("  [skipped] {} ({reason})", id.display_name()));
513                }
514                ApplyOutcome::Failed { id, reason } => {
515                    sink.status(&format!("  [failed] {} ({reason})", id.display_name()));
516                }
517            }
518        }
519    }
520
521    // --- Step 6: persist (FR-012) -------------------------------------------
522    let bound_port = session
523        .as_ref()
524        .map(|s| s.bound_addr.port())
525        .unwrap_or(bind_port);
526    let profile = OperatorSetupProfile::new(
527        installation_type,
528        bound_port,
529        AuthPosture::LoopbackNoKey,
530        &selected_ids,
531        now_epoch_ms(),
532    );
533    profile
534        .save(control_state_dir.context("process control state unavailable")?)
535        .context("could not persist operator setup profile")?;
536
537    // --- Step 5b: offer to open the dashboard (FR-011) ----------------------
538    let mut browser_outcome = None;
539    if let Some(desc) = &session {
540        let outcome = browser.open_url(&desc.dashboard_url);
541        sink.status(&format!(
542            "Browser: {outcome:?} — open {}",
543            desc.dashboard_url
544        ));
545        browser_outcome = Some(outcome);
546    }
547
548    sink.status("Setup complete.");
549    Ok(WizardOutcome {
550        installation_type,
551        session,
552        reused_server,
553        harness_outcomes,
554        browser_outcome,
555        profile,
556        cancelled: false,
557    })
558}
559
560fn now_epoch_ms() -> i64 {
561    std::time::SystemTime::now()
562        .duration_since(std::time::UNIX_EPOCH)
563        .unwrap_or_default()
564        .as_millis() as i64
565}
566
567fn loopback_addr(port: u16) -> SocketAddr {
568    SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)
569}
570
571fn suggest_free_port(preferred: Option<u16>) -> anyhow::Result<u16> {
572    let preferred_addr = preferred
573        .map(loopback_addr)
574        .or_else(|| DEFAULT_LISTEN.parse().ok());
575    let addr = crate::cli::admin::select_free_addr_std(preferred_addr)
576        .map_err(|e| anyhow::anyhow!("could not find a free operator-server port: {e}"))?;
577    Ok(addr.port())
578}
579
580fn scan_harness_summary(registry: &HarnessRegistry, attach: Option<&AttachEntry>) -> Vec<String> {
581    let entry = attach
582        .cloned()
583        .unwrap_or_else(|| AttachEntry::new("", None));
584    registry
585        .scan(&entry)
586        .into_iter()
587        .map(|s| {
588            format!(
589                "  {} — {} ({})",
590                s.id.display_name(),
591                format_harness_state(&s.state),
592                s.config_path.display()
593            )
594        })
595        .collect()
596}
597
598fn format_harness_state(state: &HarnessState) -> &'static str {
599    match state {
600        HarnessState::NotInstalled => "not installed",
601        HarnessState::Absent => "not configured",
602        HarnessState::PresentCurrent => "configured (current)",
603        HarnessState::PresentStale => "configured (stale)",
604        HarnessState::Malformed(_) => "unreadable",
605    }
606}
607
608fn resolve_installation_type<S: SetupSink + ?Sized>(
609    args: &SetupCliArgs,
610    sink: &mut S,
611) -> anyhow::Result<InstallationType> {
612    if let Some(t) = args.installation_type {
613        return Ok(t);
614    }
615    if args.non_interactive {
616        return Ok(InstallationType::Both);
617    }
618    let idx = sink.ask_choice(
619        "Installation type?",
620        &[
621            "in-harness only (stdio via symforge init)",
622            "operator server + dashboard",
623            "both (server + harness HTTP attach)",
624        ],
625    );
626    Ok(match idx {
627        0 => InstallationType::InHarness,
628        1 => InstallationType::Server,
629        _ => InstallationType::Both,
630    })
631}
632
633fn resolve_harness_ids(args: &SetupCliArgs, registry: &HarnessRegistry) -> Vec<HarnessId> {
634    if !args.harnesses.is_empty() {
635        return args
636            .harnesses
637            .iter()
638            .filter_map(|slug| harness_id_from_slug(slug))
639            .collect();
640    }
641    let entry = AttachEntry::new("", None);
642    registry
643        .scan(&entry)
644        .into_iter()
645        .filter(|s| !matches!(s.state, HarnessState::NotInstalled))
646        .map(|s| s.id)
647        .collect()
648}
649
650fn harness_id_from_slug(slug: &str) -> Option<HarnessId> {
651    let slug = slug.trim().to_ascii_lowercase();
652    [
653        HarnessId::ClaudeCode,
654        HarnessId::ClaudeDesktop,
655        HarnessId::Codex,
656        HarnessId::Gemini,
657        HarnessId::KiloCode,
658        HarnessId::Cursor,
659    ]
660    .into_iter()
661    .find(|id| id.slug() == slug)
662}
663
664fn registry_subset(registry: &HarnessRegistry, ids: &[HarnessId]) -> HarnessRegistry {
665    let targets = registry
666        .targets()
667        .iter()
668        .filter(|t| ids.contains(&t.id))
669        .cloned()
670        .collect();
671    HarnessRegistry::from_targets(targets)
672}
673
674fn build_action_plan(
675    installation_type: InstallationType,
676    harnesses: &[HarnessId],
677    bind_addr: SocketAddr,
678    needs_server: bool,
679    needs_harness_http: bool,
680) -> String {
681    let mut lines = vec![format!(
682        "Planned actions ({}):",
683        installation_type_label(installation_type)
684    )];
685    if needs_server {
686        lines.push(format!("  • start operator server on {bind_addr}"));
687    }
688    if needs_harness_http {
689        for id in harnesses {
690            lines.push(format!(
691                "  • configure {} HTTP attach (backup + write)",
692                id.display_name()
693            ));
694        }
695    }
696    if installation_type == InstallationType::InHarness {
697        lines.push("  • no server; use `symforge init` for stdio MCP clients".to_string());
698    }
699    lines.join("\n")
700}
701
702fn installation_type_label(t: InstallationType) -> &'static str {
703    match t {
704        InstallationType::InHarness => "in-harness",
705        InstallationType::Server => "server",
706        InstallationType::Both => "both",
707    }
708}
709
710#[cfg(test)]
711mod tests {
712    use super::*;
713
714    fn control_over(home: &std::path::Path) -> crate::domain::ControlStateDir {
715        crate::domain::ControlStateDir::new(home.join("control"))
716    }
717
718    #[test]
719    fn scripted_sink_returns_scripted_answers_and_records_prompts() {
720        let mut sink = ScriptedSetupSink::new([1, 0], true);
721
722        sink.status("scanning harnesses");
723        let first = sink.ask_choice("install type?", &["in-harness", "server", "both"]);
724        let second = sink.ask_choice("which harness?", &["claude", "codex"]);
725        let proceed = sink.confirm("will configure: claude");
726
727        // Scripted answers are returned front-to-back.
728        assert_eq!(first, 1, "first ask_choice pops the first scripted answer");
729        assert_eq!(second, 0, "second ask_choice pops the next scripted answer");
730        assert!(proceed, "confirm returns the scripted bool");
731
732        // Every prompt is recorded for assertion.
733        assert_eq!(sink.statuses, vec!["scanning harnesses"]);
734        assert_eq!(sink.questions.len(), 2);
735        assert!(sink.questions[0].contains("install type?"));
736        assert!(sink.questions[0].contains("in-harness, server, both"));
737        assert_eq!(sink.confirmations, vec!["will configure: claude"]);
738    }
739
740    #[test]
741    fn scripted_sink_defaults_to_first_when_script_exhausted() {
742        // An empty script must never read stdin / panic: it defaults to index 0.
743        let mut sink = ScriptedSetupSink::new([], false);
744        assert_eq!(sink.ask_choice("pick", &["a", "b"]), 0);
745        assert!(!sink.confirm("plan"));
746    }
747
748    #[test]
749    fn installation_type_serde_uses_contract_strings() {
750        // The profile + wire shape must use the documented strings, matching the
751        // clap `value(name = ...)`.
752        assert_eq!(
753            serde_json::to_string(&InstallationType::InHarness).unwrap(),
754            "\"in-harness\""
755        );
756        assert_eq!(
757            serde_json::to_string(&InstallationType::Both).unwrap(),
758            "\"both\""
759        );
760        let parsed: InstallationType = serde_json::from_str("\"server\"").unwrap();
761        assert_eq!(parsed, InstallationType::Server);
762    }
763
764    #[test]
765    fn non_interactive_setup_configures_fixture_and_persists_profile() {
766        use crate::cli::admin::operator_server_reachable;
767        use crate::cli::browser::NoopBrowserOpener;
768        use crate::cli::harness::{HarnessFormat, HarnessTarget, SYMFORGE_SERVER_NAME};
769        use crate::cli::harness_apply::{PlannedAction, plan};
770
771        let home = tempfile::tempdir().expect("temp home");
772        let project = tempfile::tempdir().expect("temp project");
773        let control = control_over(home.path());
774        let cfg = home.path().join(".claude.json");
775        std::fs::write(&cfg, "{}\n").expect("fixture harness config");
776
777        let ctx = SetupContext {
778            home: home.path().to_path_buf(),
779            working_dir: project.path().to_path_buf(),
780        };
781
782        let mut sink = ScriptedSetupSink::new([], true);
783        let browser = NoopBrowserOpener::default();
784
785        let outcome = run_wizard_with_control_state(
786            SetupCliArgs {
787                non_interactive: true,
788                installation_type: Some(InstallationType::Both),
789                port: None,
790                harnesses: vec!["claude".into()],
791                yes: true,
792            },
793            &ctx,
794            &mut sink,
795            &browser,
796            Some(&control),
797            Some(project.path()),
798        )
799        .expect("setup should succeed");
800
801        assert!(!outcome.cancelled);
802        assert_eq!(outcome.installation_type, InstallationType::Both);
803
804        assert!(
805            sink.statuses.iter().any(|l| l.contains("Claude Code")),
806            "scan must list harnesses: {:?}",
807            sink.statuses
808        );
809
810        let profile = OperatorSetupProfile::load(&control).expect("profile persisted");
811        assert_eq!(profile.installation_type, InstallationType::Both);
812        assert!(profile.port > 0);
813        assert_eq!(profile.harnesses, vec!["claude"]);
814
815        let after = std::fs::read_to_string(&cfg).expect("config exists");
816        assert!(after.contains(SYMFORGE_SERVER_NAME));
817
818        // The reported attach URL comes straight off the reachable descriptor.
819        let session = outcome.session.as_ref().expect("server started");
820        assert!(session.reachable);
821        let attach_url = session.attach_url.clone();
822        assert!(attach_url.contains("/mcp"));
823
824        assert!(
825            operator_server_reachable(session.bound_addr, Duration::from_millis(500)),
826            "server must be reachable on reported port"
827        );
828        assert_eq!(browser.opened_urls().len(), 1);
829
830        let entry = AttachEntry::new(attach_url, None);
831        let reg = HarnessRegistry::from_targets(vec![HarnessTarget {
832            id: HarnessId::ClaudeCode,
833            config_path: cfg,
834            format: HarnessFormat::Json,
835        }]);
836        let p2 = plan(&reg, &entry);
837        assert!(matches!(p2.changes[0].action, PlannedAction::Skip(_)));
838    }
839
840    #[test]
841    fn non_interactive_decline_writes_nothing_and_is_not_an_error() {
842        use crate::cli::browser::NoopBrowserOpener;
843
844        let home = tempfile::tempdir().expect("temp home");
845        let project = tempfile::tempdir().expect("temp project");
846        let control = control_over(home.path());
847        let cfg = home.path().join(".claude.json");
848        let original = "{\n  \"mcpServers\": {}\n}\n";
849        std::fs::write(&cfg, original).expect("fixture");
850
851        let ctx = SetupContext {
852            home: home.path().to_path_buf(),
853            working_dir: project.path().to_path_buf(),
854        };
855        // No `--yes`: the scripted confirm answer (false) declines the plan.
856        let mut sink = ScriptedSetupSink::new([], false);
857        let browser = NoopBrowserOpener::default();
858
859        let outcome = run_wizard_with_control_state(
860            SetupCliArgs {
861                non_interactive: true,
862                installation_type: Some(InstallationType::Both),
863                port: None,
864                harnesses: vec!["claude".into()],
865                yes: false,
866            },
867            &ctx,
868            &mut sink,
869            &browser,
870            Some(&control),
871            Some(project.path()),
872        )
873        .expect("a decline is a clean no-op, not an error");
874
875        // Declined: nothing applied, no server, no profile, config untouched.
876        assert!(outcome.cancelled);
877        assert!(outcome.session.is_none());
878        assert!(outcome.harness_outcomes.is_empty());
879        assert_eq!(std::fs::read_to_string(&cfg).unwrap(), original);
880        assert!(OperatorSetupProfile::load(&control).is_none());
881        // The restate was still presented before the decline (FR-008).
882        assert_eq!(sink.confirmations.len(), 1);
883    }
884
885    #[test]
886    fn setup_holds_foreground_after_fresh_start_until_shutdown() {
887        // No server running -> the wizard's Server mode starts one on a background
888        // thread. serve_foreground_if_wizard_started must then KEEP setup in the
889        // foreground (invoke the waiter), and while "blocked" the freshly-started
890        // server must be reachable AND STAY reachable. D21 sibling: pre-fix
891        // `setup::run` returned immediately, so the serve thread died with the process
892        // and the "Dashboard: <url>" the interactive wizard printed was refused.
893        use crate::cli::admin::operator_server_reachable;
894        use crate::cli::browser::NoopBrowserOpener;
895
896        let home = tempfile::tempdir().expect("temp home");
897        let project = tempfile::tempdir().expect("temp project");
898        let control = control_over(home.path());
899        let ctx = SetupContext {
900            home: home.path().to_path_buf(),
901            working_dir: project.path().to_path_buf(),
902        };
903        let mut sink = ScriptedSetupSink::new([], true);
904        let browser = NoopBrowserOpener::default();
905
906        let outcome = run_wizard_with_control_state(
907            SetupCliArgs {
908                non_interactive: true,
909                installation_type: Some(InstallationType::Server),
910                port: None,
911                harnesses: vec![],
912                yes: true,
913            },
914            &ctx,
915            &mut sink,
916            &browser,
917            Some(&control),
918            Some(project.path()),
919        )
920        .expect("server-mode setup should start a server when none runs");
921        assert!(
922            !outcome.reused_server,
923            "no server ran; the wizard must start one"
924        );
925        assert!(
926            outcome.session.is_some(),
927            "a fresh start yields a live session"
928        );
929
930        let waited = std::cell::Cell::new(false);
931        serve_foreground_if_wizard_started(&outcome, |session| {
932            waited.set(true);
933            // Probe twice with a gap: the started server must be serving now AND still
934            // serving a moment later — not fire-and-return (D21).
935            assert!(
936                operator_server_reachable(session.bound_addr, Duration::from_millis(500)),
937                "freshly-started server must be reachable while setup holds the foreground"
938            );
939            std::thread::sleep(Duration::from_millis(300));
940            assert!(
941                operator_server_reachable(session.bound_addr, Duration::from_millis(500)),
942                "the started server must STAY reachable (D21: it must not die after start)"
943            );
944            Ok(())
945        })
946        .expect("foreground wait returns cleanly on shutdown");
947
948        assert!(
949            waited.get(),
950            "a freshly-started server must hold the foreground (D21 fix); pre-fix `run` returned immediately"
951        );
952        // The fresh branch prints FOREGROUND_SERVE_NOTICE right before the waiter, so
953        // an interactive fresh start is not a silent block; pin the wording (stderr
954        // capture is impractical in-lib, and `waited.get()` proves the branch ran).
955        assert!(
956            FOREGROUND_SERVE_NOTICE.contains("Ctrl-C"),
957            "the foreground notice must tell the operator how to stop it"
958        );
959    }
960
961    #[test]
962    fn setup_does_not_hold_foreground_when_reusing() {
963        // A server already runs and the profile points at it -> the wizard reuses it.
964        // serve_foreground_if_wizard_started must NOT block: another process owns the
965        // server, so setup returns without invoking the waiter (reuse path unchanged).
966        use crate::cli::browser::NoopBrowserOpener;
967
968        let preferred = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
969        let workspace = tempfile::tempdir().expect("temp workspace");
970        let running = start_operator_server(
971            Some(preferred),
972            false,
973            None,
974            None,
975            ADMIN_SERVE_START_DEADLINE,
976            Some(workspace.path().to_path_buf()),
977        )
978        .expect("operator server should come up");
979
980        let home = tempfile::tempdir().expect("temp home");
981        let project = tempfile::tempdir().expect("temp project");
982        let control = control_over(home.path());
983        OperatorSetupProfile::new(
984            InstallationType::Server,
985            running.bound_addr.port(),
986            AuthPosture::LoopbackNoKey,
987            &[],
988            1,
989        )
990        .save(&control)
991        .expect("persist profile");
992
993        let ctx = SetupContext {
994            home: home.path().to_path_buf(),
995            working_dir: project.path().to_path_buf(),
996        };
997        let mut sink = ScriptedSetupSink::new([], true);
998        let browser = NoopBrowserOpener::default();
999
1000        let outcome = run_wizard_with_control_state(
1001            SetupCliArgs {
1002                non_interactive: true,
1003                installation_type: Some(InstallationType::Server),
1004                port: None,
1005                harnesses: vec![],
1006                yes: true,
1007            },
1008            &ctx,
1009            &mut sink,
1010            &browser,
1011            Some(&control),
1012            Some(project.path()),
1013        )
1014        .expect("server-mode setup should reuse the running server");
1015        assert!(
1016            outcome.reused_server,
1017            "must reuse the already-running server"
1018        );
1019
1020        let waited = std::cell::Cell::new(false);
1021        serve_foreground_if_wizard_started(&outcome, |_| {
1022            waited.set(true);
1023            Ok(())
1024        })
1025        .expect("reuse path returns cleanly");
1026        assert!(
1027            !waited.get(),
1028            "the reuse path must not hold the foreground (another process owns the server)"
1029        );
1030    }
1031}