surjection 1.1.0

Surjection CLI: manage MCP servers, skills and secret references for AI coding clients
//! `surject migrate skilldock [--apply]` (SPEC 15.1, 14): bring SkillDock's
//! `~/.skilldock` into the store. Without `--apply` it is a dry run that
//! prints the report and writes nothing. `--apply` asks for confirmation
//! (`--yes` answers it; without a terminal and without `--yes` it fails
//! with `confirmation_required`), then tags the store
//! `auto/pre-migrate/<ts>` and migrates in one commit. `~/.skilldock` is
//! only read; no client file is written (the first apply is a separate,
//! previewed step).

use std::io::{BufRead, IsTerminal, Write};

use clap::{Args, Subcommand};
use serde_json::json;
use surjection_core::migrate::loadout::{self as legacy, StepStatus};
use surjection_core::migrate::{self, Offer, Report};
use surjection_core::{CoreError, ErrorCode, brand};

use super::{Context, JSON_SCHEMA, print_json};

#[derive(Debug, Args)]
pub struct MigrateArgs {
    #[command(subcommand)]
    command: MigrateCommand,
}

#[derive(Debug, Subcommand)]
enum MigrateCommand {
    /// From SkillDock (~/.skilldock, read only): servers, skills, tags,
    /// settings, the backup repository.
    Skilldock(SkilldockArgs),
    /// From Loadout 1.0.x (this product's former name): moves the data
    /// folder, renames files, copies the app profile, repairs client
    /// entries that start the former `loadout` launcher and swaps the
    /// bundled agent skill. Runs once by itself at the first start.
    Loadout(LoadoutArgs),
}

#[derive(Debug, Args)]
struct LoadoutArgs {
    /// Only show what would be done; write nothing.
    #[arg(long)]
    dry_run: bool,
    /// Print nothing unless a step fails (the Windows installer).
    #[arg(long, conflicts_with = "dry_run")]
    quiet: bool,
}

#[derive(Debug, Args)]
struct SkilldockArgs {
    /// Migrate (one commit after a pre-migrate tag); without it, only
    /// report what would happen.
    #[arg(long)]
    apply: bool,
}

/// Whether `args` is `migrate loadout`.
pub fn is_loadout(args: Option<&MigrateArgs>) -> bool {
    args.is_some_and(|args| matches!(args.command, MigrateCommand::Loadout(_)))
}

/// Whether `args` is `migrate loadout --dry-run`.
pub fn is_dry_run(args: Option<&MigrateArgs>) -> bool {
    args.is_some_and(|args| matches!(&args.command, MigrateCommand::Loadout(args) if args.dry_run))
}

pub fn run(ctx: &Context, args: &MigrateArgs) -> Result<u8, CoreError> {
    match &args.command {
        MigrateCommand::Skilldock(args) => skilldock(ctx, args),
        MigrateCommand::Loadout(args) => loadout(ctx, args),
    }
}

fn skilldock(ctx: &Context, args: &SkilldockArgs) -> Result<u8, CoreError> {
    let ax = ctx.apply_env();
    if !args.apply || !ctx.yes {
        let store = ctx.open_store()?;
        let migration = migrate::plan(store.as_ref(), &ax)?;
        if !args.apply {
            if ctx.json {
                print_json(&json!({
                    "schema": JSON_SCHEMA,
                    "dry_run": true,
                    "report": migration.report,
                    "files": migration.files().collect::<Vec<_>>(),
                }));
            } else {
                print_items(&migration.report);
                println!(
                    "Dry run: nothing was written. Run `{} migrate skilldock --apply` to migrate.",
                    brand::BIN_NAME
                );
            }
            return Ok(0);
        }
        if ctx.json || !std::io::stdin().is_terminal() {
            return Err(CoreError::new(
                ErrorCode::ConfirmationRequired,
                "migrating writes to the store; pass --yes to confirm",
            ));
        }
        print_items(&migration.report);
        if !confirm(&migration.report)? {
            println!("Nothing migrated.");
            return Ok(0);
        }
    }
    let store = ctx.open_store_for_change()?;
    let applied = migrate::apply(&store, &ax)?;
    if ctx.json {
        print_json(&json!({
            "schema": JSON_SCHEMA,
            "dry_run": false,
            "report": applied.report,
            "tag": applied.tag,
            "post_tag": applied.post_tag,
            "commit": applied.commit.as_ref().map(ToString::to_string),
            "backup_import": applied.backup_import,
        }));
    } else {
        if ctx.yes {
            print_items(&applied.report);
        }
        match &applied.commit {
            Some(commit) => println!(
                "Migrated {} server{} and {} skill{} (commit {}, tag {}).",
                applied.report.servers.len(),
                plural(applied.report.servers.len()),
                applied.report.skills.len(),
                plural(applied.report.skills.len()),
                commit.short(),
                applied.tag
            ),
            None => println!("Nothing left to migrate (tag {}).", applied.tag),
        }
        if let Some(path) = &applied.backup_import {
            println!("SkillDock's backup repository is at <SURJECTION_HOME>/{path}.");
        }
        println!(
            "Client files are unchanged; review the plan with `{bin} apply --dry-run`, then run \
             `{bin} apply`. Keep SkillDock's MCP sync off from now on: both apps writing the same \
             files causes churn. ~/.skilldock is left as it was, for rollback.",
            bin = brand::BIN_NAME
        );
    }
    Ok(0)
}

fn plural(n: usize) -> &'static str {
    if n == 1 { "" } else { "s" }
}

fn confirm(report: &Report) -> Result<bool, CoreError> {
    print!(
        "Migrate {} server{} and {} skill{} into the store? [y/N] ",
        report.servers.len(),
        plural(report.servers.len()),
        report.skills.len(),
        plural(report.skills.len())
    );
    std::io::stdout().flush().ok();
    let mut line = String::new();
    std::io::stdin()
        .lock()
        .read_line(&mut line)
        .map_err(|err| CoreError::new(ErrorCode::IoError, format!("cannot read stdin: {err}")))?;
    Ok(matches!(line.trim(), "y" | "Y" | "yes" | "Yes"))
}

/// One line per item, its follow-ups indented, then the counts.
fn print_items(report: &Report) {
    for item in &report.items {
        let id = item
            .id
            .as_ref()
            .filter(|id| **id != item.name)
            .map_or_else(String::new, |id| format!(" -> {id}"));
        let code = item
            .code
            .map_or_else(String::new, |code| format!(" [{code}]"));
        println!(
            "{:<13} {:<12} {}{id}: {}{code}",
            item.status.as_str(),
            item.kind.as_str(),
            item.name,
            item.detail
        );
        for offer in &item.offers {
            match offer {
                Offer::ReplaceWrapper { command, .. } => {
                    println!("{:27}replace the wrapper: {command}", "");
                }
                Offer::ReviewEntry { command, .. } => println!("{:27}overwrite: {command}", ""),
                Offer::SetSecret { command, .. } => println!("{:27}store the value: {command}", ""),
                Offer::MachinePath { .. } => {}
                Offer::KeyringToken { command } => println!("{:27}{command}", ""),
                Offer::AddRemote { url } => {
                    println!("{:27}{} remote add git <NAME> {url}", "", brand::BIN_NAME)
                }
            }
        }
    }
    let (migrated, review, skipped) = report.counts();
    println!(
        "{} item{}: {migrated} migrated, {review} to review, {skipped} skipped; {} value{} for the \
         secret extraction wizard.",
        report.items.len(),
        plural(report.items.len()),
        report.extractions.len(),
        plural(report.extractions.len())
    );
}

/// `surject migrate loadout`: step 1 ran before the data folder was
/// resolved (see `main.rs`), as `ctx.legacy_step`.
fn loadout(ctx: &Context, args: &LoadoutArgs) -> Result<u8, CoreError> {
    let report = run_loadout(ctx, args.dry_run)?;
    if ctx.json {
        print_json(&json!({ "schema": JSON_SCHEMA, "migration": report }));
    } else if !args.quiet || report.failed() {
        print_loadout(&report, args.quiet);
    }
    Ok(u8::from(report.failed()))
}

fn run_loadout(ctx: &Context, dry_run: bool) -> Result<legacy::Report, CoreError> {
    let first = ctx
        .legacy_step
        .clone()
        .unwrap_or_else(|| legacy::data_folder(&ctx.env, dry_run));
    let store = ctx.open_store()?;
    let ax = ctx.apply_env();
    let sx = super::skills::skills_env(ctx);
    legacy::run_in_home(vec![first], store.as_ref(), &ax, &sx, dry_run)
}

/// The automatic run at a command's first start: once per machine; a note
/// on stderr when something changed. A failure is a warning, never the
/// command's error (the next start tries again).
pub fn auto(ctx: &Context) {
    if legacy::is_done(ctx.fs(), &ctx.home) {
        return;
    }
    match run_loadout(ctx, false) {
        Ok(report) if report.changed() || report.failed() => print_loadout(&report, true),
        Ok(_) => {}
        Err(err) => eprintln!(
            "warning: the migration from {} did not finish: {}",
            brand::legacy::PRODUCT_NAME,
            err.message()
        ),
    }
}

fn print_loadout(report: &legacy::Report, brief: bool) {
    let from = brand::legacy::PRODUCT_NAME;
    for step in &report.steps {
        let shown = match step.status {
            StepStatus::Done | StepStatus::Planned | StepStatus::Failed => true,
            StepStatus::Skipped | StepStatus::NotNeeded => !brief,
        };
        if !shown {
            continue;
        }
        let status = match step.status {
            StepStatus::Done => "done",
            StepStatus::Planned => "planned",
            StepStatus::NotNeeded => "not needed",
            StepStatus::Skipped => "skipped",
            StepStatus::Failed => "failed",
        };
        let line = format!(
            "{from} migration, {}: {status}: {}",
            step_name(step.step),
            step.detail
        );
        if brief {
            eprintln!("{line}");
        } else {
            println!("{line}");
        }
        for item in &step.items {
            if brief {
                eprintln!("  {item}");
            } else {
                println!("  {item}");
            }
        }
    }
    if report.dry_run && !brief {
        println!(
            "Dry run: nothing was written. Run `{} migrate loadout` to migrate.",
            brand::BIN_NAME
        );
    }
}

fn step_name(step: legacy::StepKind) -> &'static str {
    match step {
        legacy::StepKind::DataFolder => "data folder",
        legacy::StepKind::FileNames => "file names",
        legacy::StepKind::WebviewProfile => "app profile",
        legacy::StepKind::Launchers => "client entries",
        legacy::StepKind::AgentSkill => "agent skill",
    }
}