cdk-rsx-cli 0.1.1

Build and test Internet Computer canisters with CDK RSX
use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use std::{env, path::PathBuf, process::ExitCode};

mod ashroot;
mod build;
mod cargo;
mod compat;
mod preflight;
mod profile;
mod project;
mod receipt;
mod rehearse;
mod skills;
mod takt;
mod wire;

const TOOLCHAIN: &str = "nightly-2026-10-15";

#[derive(Parser)]
#[command(version, about)]
struct Cli {
    #[command(subcommand)]
    command: Operation,
}

#[derive(Subcommand)]
enum Operation {
    /// Create a standalone application from a packaged example.
    New {
        path: PathBuf,
        #[arg(long, default_value = "quickstart")]
        example: project::Example,
        /// Install the matching SDK skills for this agent after creating the app.
        #[arg(long, value_enum)]
        agent: Option<project::Agent>,
    },
    /// Prepare installable Wasm, matching IC Wire clients, and build receipts.
    Build(build::Options),
    /// Refresh Cargo.lock after editing dependencies, using the SDK's pinned Cargo.
    Lock {
        #[arg(long, default_value = "Cargo.toml")]
        manifest_path: PathBuf,
        #[arg(long)]
        offline: bool,
    },
    /// Find a guide in the SDK package resolved by this application.
    Docs {
        package: String,
        guide: Option<PathBuf>,
        #[arg(long, default_value = "Cargo.toml")]
        manifest_path: PathBuf,
    },
    /// Install agent skills from the application's resolved SDK package.
    Skills {
        #[command(subcommand)]
        command: SkillOperation,
    },
    /// Check inputs to a retained-memory upgrade.
    Upgrade {
        #[command(subcommand)]
        command: UpgradeOperation,
    },
    /// Verify the outputs and compiler policy of a completed build.
    Verify { manifest: PathBuf },
    /// Check or scaffold Takt workflows using the app's locked generator.
    Takt(takt::Options),
    /// Inspect the installed IC Wire contract.
    Wire {
        #[command(subcommand)]
        command: WireOperation,
    },
    /// Analyze a local profile against the exact built artifact.
    Profile {
        #[command(subcommand)]
        command: profile::ProfileCommand,
    },
    /// Run low-level Wasm inspection or client-generation commands.
    #[command(trailing_var_arg = true)]
    Tool {
        #[arg(required = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
}

#[derive(Subcommand)]
enum SkillOperation {
    Install {
        name: String,
        #[arg(long, value_enum)]
        agent: project::Agent,
        #[arg(long, default_value = "Cargo.toml")]
        manifest_path: PathBuf,
    },
    /// Synchronize SDK skills for the selected canister and feature set.
    Sync {
        #[arg(long, value_enum)]
        agent: project::Agent,
        #[arg(long, default_value = "Cargo.toml")]
        manifest_path: PathBuf,
        #[arg(short, long)]
        package: Option<String>,
        #[arg(short = 'F', long)]
        features: Vec<String>,
        #[arg(long)]
        all_features: bool,
        #[arg(long)]
        no_default_features: bool,
        #[arg(long, default_value = build::WASM64, value_parser = [build::WASM64, build::WASM32])]
        wasm_target: String,
    },
}

#[derive(Subcommand)]
enum UpgradeOperation {
    /// Compare completed build receipts before a populated KEEP rehearsal.
    Preflight {
        #[arg(long)]
        baseline: PathBuf,
        #[arg(long)]
        candidate: PathBuf,
    },
    Rehearse(rehearse::Options),
}

#[derive(Subcommand)]
enum WireOperation {
    /// Export a deterministic IC Wire manifest from a verified build.
    Manifest { build_manifest: PathBuf },
}

fn run(operation: Operation) -> Result<ExitCode> {
    match operation {
        Operation::New {
            path,
            example,
            agent,
        } => {
            project::new(&path, TOOLCHAIN, example)?;
            if let Some(agent) = agent {
                skills::sync(&path.join("Cargo.toml"), None, &[], build::WASM64, agent)
                    .context("project created. To retry, run `cdk-rsx skills sync` there with the same `--agent` value")?;
            }
        }
        Operation::Build(options) => build::build(options)?,
        Operation::Lock {
            manifest_path,
            offline,
        } => cargo::refresh_lock(&manifest_path, offline)?,
        Operation::Docs {
            package,
            guide,
            manifest_path,
        } => {
            let metadata = cargo::project_metadata(&manifest_path)?;
            let path = project::docs(&metadata, &package, guide.as_deref())?;
            println!("{}", path.display());
        }
        Operation::Skills {
            command:
                SkillOperation::Install {
                    name,
                    agent,
                    manifest_path,
                },
        } => {
            let manifest = manifest_path.canonicalize()?;
            let metadata = cargo::project_metadata(&manifest)?;
            let root = manifest.parent().unwrap();
            let path = project::install_skill(&metadata, root, &name, agent)?;
            println!("{}", path.display());
        }
        Operation::Upgrade {
            command:
                UpgradeOperation::Preflight {
                    baseline,
                    candidate,
                },
        } => {
            let result = match preflight::preflight(&baseline, &candidate) {
                Ok(result) => result,
                Err(error) => {
                    eprintln!("cdk-rsx: {error:#}");
                    return Ok(ExitCode::from(2));
                }
            };
            println!("{}", serde_json::to_string_pretty(&result)?);
            return Ok(if result["status"] == "compiler-policy-match" {
                ExitCode::SUCCESS
            } else {
                ExitCode::FAILURE
            });
        }
        Operation::Upgrade {
            command: UpgradeOperation::Rehearse(options),
        } => rehearse::run(options)?,
        Operation::Skills {
            command:
                SkillOperation::Sync {
                    agent,
                    manifest_path,
                    package,
                    features,
                    all_features,
                    no_default_features,
                    wasm_target,
                },
        } => {
            let flags = cargo::feature_flags(features, all_features, no_default_features);
            skills::sync(
                &manifest_path,
                package.as_deref(),
                &flags,
                &wasm_target,
                agent,
            )?;
        }
        Operation::Verify { manifest } => {
            println!(
                "{}",
                serde_json::to_string_pretty(&preflight::verify(&manifest)?)?
            );
        }
        Operation::Tool { args } => cdk_rsx_wasm::command(&args)?,
        Operation::Takt(options) => takt::run(options)?,
        Operation::Wire {
            command: WireOperation::Manifest { build_manifest },
        } => {
            println!(
                "{}",
                serde_json::to_string_pretty(&wire::manifest(&build_manifest)?)?
            );
        }
        Operation::Profile { command } => command.run()?,
    }
    Ok(ExitCode::SUCCESS)
}

fn entrypoint() -> Result<ExitCode> {
    // The executable recorded with each artifact also implements the low-level
    // Wasm commands used by existing receipt readers and profiling tools.
    let executable = env::current_exe()?;
    if executable
        .file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.ends_with(".wasm-tool"))
    {
        cdk_rsx_wasm::command(&env::args().skip(1).collect::<Vec<_>>())?;
        return Ok(ExitCode::SUCCESS);
    }
    if !cfg!(unix) {
        bail!("CDK RSX canister builds require a Linux or macOS host");
    }
    run(Cli::parse().command)
}

fn main() -> ExitCode {
    match entrypoint() {
        Ok(code) => code,
        Err(error) => {
            eprintln!("cdk-rsx: {error:#}");
            ExitCode::FAILURE
        }
    }
}