Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

208 KB
Raw Blame
mod base_client;
mod cli_arg_scan;
mod client;
mod commands;
mod config;
mod config_agent;
mod config_command_ui;
mod config_wizard;
mod error;
mod error_ui;
mod handlers;
mod health_ui;
mod help_ui;
mod i18n;
mod openviking_assets;
mod output;
mod status_ui;
mod terminal_ui;
mod theme;
mod tui;
mod utils;

use clap::{ArgAction, Args, CommandFactory, Parser, Subcommand};
use colored::Colorize;
use config::Config;
use error::{Error, Result};
use output::OutputFormat;
use std::{
    ffi::OsString,
    io::{self, IsTerminal},
};

const MAX_TIME_DECAY_DURATION_DAYS: u128 = 3000 * 365;

fn parse_event_time_decay_protection(value: &str) -> std::result::Result<String, String> {
    if value == "0" {
        return Ok(value.to_string());
    }
    let Some((amount, unit)) = value.split_at_checked(value.len().saturating_sub(1)) else {
        return Err("must be '0' or a non-negative integer followed by m, h, or d".to_string());
    };
    if amount.is_empty() || !amount.bytes().all(|byte| byte.is_ascii_digit()) {
        return Err("must be '0' or a non-negative integer followed by m, h, or d".to_string());
    }
    let amount = amount
        .parse::<u128>()
        .map_err(|_| "exceeds the maximum duration of 1095000d".to_string())?;
    let duration_minutes = match unit {
        "m" => amount,
        "h" => amount.saturating_mul(60),
        "d" => amount.saturating_mul(24 * 60),
        _ => {
            return Err("must be '0' or a non-negative integer followed by m, h, or d".to_string());
        }
    };
    if duration_minutes > MAX_TIME_DECAY_DURATION_DAYS * 24 * 60 {
        return Err("exceeds the maximum duration of 1095000d".to_string());
    }
    Ok(value.to_string())
}

/// CLI context shared across commands
#[derive(Debug, Clone)]
pub struct CliContext {
    pub config: Config,
    pub output_format: OutputFormat,
    pub compact: bool,
    pub sudo: bool,
    /// Whether to show upload progress (override config)
    pub show_progress: Option<bool>,
    /// Whether to enable verbose output (override config)
    pub verbose: Option<bool>,
    pub profile: Option<bool>,
}

impl CliContext {
    fn from_config(
        mut config: Config,
        output_format: OutputFormat,
        compact: bool,
        account: Option<String>,
        user: Option<String>,
        actor_peer_id: Option<String>,
        sudo: bool,
        show_progress: Option<bool>,
        verbose: Option<bool>,
        profile: Option<bool>,
    ) -> Self {
        if account.is_some() {
            config.account = account;
        }
        if user.is_some() {
            config.user = user;
        }
        if actor_peer_id.is_some() {
            config.actor_peer_id = actor_peer_id;
            config.agent_id = None;
        }
        Self {
            config,
            output_format,
            compact,
            sudo,
            show_progress,
            verbose,
            profile,
        }
    }

    /// Check if progress should be shown
    pub fn should_show_progress(&self) -> bool {
        self.show_progress.unwrap_or(self.config.show_progress)
    }

    /// Check if verbose output is enabled
    pub fn is_verbose(&self) -> bool {
        self.verbose.unwrap_or(self.config.verbose)
    }

    pub fn get_client(&self) -> client::HttpClient {
        self.get_client_with_timeout(None)
    }

    pub fn get_client_with_timeout(&self, timeout_secs: Option<f64>) -> client::HttpClient {
        let auth = self.config.effective_auth(self.sudo);
        let mut client = client::HttpClient::new(
            &self.config.url,
            auth.api_key,
            auth.account,
            auth.user,
            self.config.effective_actor_peer_id(),
            timeout_secs.unwrap_or(self.config.timeout),
            self.profile.unwrap_or(self.config.profile),
            self.config.effective_extra_headers(),
        )
        .with_gateway_token(self.config.effective_gateway_token());

        // Add LDAP or OIDC authentication if configured
        if let Some(auth_mode) = &self.config.auth_mode {
            match auth_mode.as_str() {
                "ldap" => {
                    client = client.with_auth_mode(Some("ldap".to_string()));
                    if let Some(ldap_username) = &self.config.ldap_username {
                        client = client.with_ldap_username(Some(ldap_username.clone()));
                    }
                    if let Some(ldap_password) = &self.config.ldap_password {
                        client = client.with_ldap_password(Some(ldap_password.clone()));
                    }
                }
                "oidc" => {
                    client = client.with_auth_mode(Some("oidc".to_string()));
                    if let Some(token) = &self.config.oidc_token {
                        client = client.with_oidc_token(Some(token.clone()));
                    } else if let Some(api_key) = &self.config.api_key {
                        // Fallback: use api_key as OIDC token if it looks like a JWT
                        client = client.with_oidc_token(Some(api_key.clone()));
                    }
                }
                _ => {}
            }
        }

        client
    }
}

#[derive(Parser)]
#[command(name = "openviking")]
#[command(about = "OpenViking - An Agent-native context database")]
#[command(version = env!("OPENVIKING_CLI_VERSION"))]
#[command(arg_required_else_help = true)]
struct Cli {
    /// Choose human table output or machine-readable JSON
    #[arg(
        short,
        long,
        value_enum,
        global = true,
        hide = true,
        value_name = "table|json"
    )]
    output: Option<OutputFormat>,

    /// Use compact table/JSON rendering
    #[arg(
        short,
        long,
        global = true,
        default_value = "true",
        default_missing_value = "true",
        hide = true,
        num_args = 0..=1,
        require_equals = true,
        action = ArgAction::Set,
        value_name = "bool"
    )]
    compact: bool,

    /// Override X-OpenViking-Account for this command
    #[arg(long, global = true, hide = true)]
    account: Option<String>,

    /// Override X-OpenViking-User for this command
    #[arg(long, global = true, hide = true)]
    user: Option<String>,

    /// Peer actor scope to send as X-OpenViking-Actor-Peer
    #[arg(long = "actor-peer-id", global = true, hide = true)]
    actor_peer_id: Option<String>,

    /// Use root API key for admin, system, reindex, and task status/list commands
    #[arg(long, global = true, hide = true)]
    sudo: bool,

    /// Enable HTTP request profiling for this command
    #[arg(long, global = true, hide = true)]
    profile: bool,

    /// Show upload progress (legacy pre-command placement; prefer command-local --progress)
    #[arg(long, hide = true)]
    progress: bool,

    /// Disable upload progress (legacy pre-command placement; prefer command-local --no-progress)
    #[arg(long = "no-progress", hide = true, conflicts_with = "progress")]
    no_progress: bool,

    /// Enable upload diagnostics (legacy pre-command placement; prefer command-local --verbose)
    #[arg(short, long, hide = true)]
    verbose: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Args, Debug, Clone, Copy, Default)]
struct UploadCliOptions {
    /// Show local file upload progress (overrides config file)
    #[arg(
        long,
        conflicts_with = "no_progress",
        help_heading = "Advanced options"
    )]
    progress: bool,

    /// Disable local file upload progress (overrides config file)
    #[arg(
        long = "no-progress",
        conflicts_with = "progress",
        help_heading = "Advanced options"
    )]
    no_progress: bool,

    /// Print extra diagnostics during local file upload
    #[arg(short, long, help_heading = "Advanced options")]
    verbose: bool,
}

impl UploadCliOptions {
    fn is_set(self) -> bool {
        self.progress || self.no_progress || self.verbose
    }

    fn merged_with_legacy(self, legacy: Self) -> Self {
        Self {
            progress: self.progress || (!self.no_progress && legacy.progress),
            no_progress: self.no_progress || (!self.progress && legacy.no_progress),
            verbose: self.verbose || legacy.verbose,
        }
    }

    fn show_progress_override(self) -> Option<bool> {
        if self.progress {
            Some(true)
        } else if self.no_progress {
            Some(false)
        } else {
            None
        }
    }

    fn verbose_override(self) -> Option<bool> {
        if self.verbose { Some(true) } else { None }
    }
}

impl CliContext {
    fn with_upload_options(mut self, options: UploadCliOptions) -> Self {
        self.show_progress = options.show_progress_override();
        self.verbose = options.verbose_override();
        self
    }
}

#[derive(Subcommand)]
enum AttrsCommands {
    /// Get logical extended attributes
    Get {
        /// Viking URI to get attributes for
        #[arg(value_name = "uri")]
        uri: String,
        /// Optional attrs key, for example tags, memory, or memory.tags
        #[arg(value_name = "key")]
        key: Option<String>,
    },
    /// Update explicit retrieval tags metadata for a file or directory
    SetTags {
        /// Viking URI
        uri: String,
        /// Comma-separated k=v tags, e.g. env=prod,team=search
        #[arg(long = "tags", value_delimiter = ',')]
        tags: Vec<String>,
        /// Tag update mode: replace or append (append replaces existing values by key)
        #[arg(long, default_value = "replace")]
        mode: String,
        /// Recursively update descendant files and semantic nodes when target is a directory
        #[arg(long, default_value = "false")]
        recursive: bool,
    },
}

#[derive(Subcommand)]
enum AclCommands {
    Get {
        uri: String,
    },
    Set {
        uri: String,
        #[arg(long = "entry")]
        entries: Vec<String>,
        /// Whether this node uses inherited grants or direct grants only
        #[arg(long, value_parser = ["inherit", "restricted"])]
        acl_mode: Option<String>,
    },
    Grant {
        uri: String,
        #[arg(long)]
        principal: String,
        #[arg(long)]
        level: String,
    },
    Revoke {
        uri: String,
        #[arg(long)]
        principal: String,
    },
    Rm {
        uri: String,
    },
}

// Commands are organized with category tags in their doc comments.
//
// # Command Tagging System
//
// Tags are added at the beginning of command doc comments, e.g.:
// - `[Data]` - Data operations category
// - `[Interactive]` - Interactive tools category
// - `[Status]` - Status & observability category
// - `[Admin]` - Admin tools category
// - `[Experimental]` - Experimental/preview features (API may change)
//
// Some tags can be combined, e.g. `[Experimental][Data]`
#[derive(Subcommand)]
enum Commands {
    // --- Data Operations ---
    /// [Data] Add resources into OpenViking
    AddResource {
        /// Local path or URL to import
        #[arg(
            value_name = "path-or-url",
            required_unless_present = "manifest",
            conflicts_with = "manifest"
        )]
        path: Option<String>,
        /// Apply an OpenViking Assets manifest (openviking-assets/1): create or sync every selected
        /// asset. Run options go into --args (supported keys: catalog, dry_run, skip_failed)
        #[arg(
            short = 'm',
            long = "manifest",
            value_name = "file",
            help_heading = "Common options",
            conflicts_with_all = [
                "add_type", "to", "parent", "parent_auto_create",
                "strict_mode", "ignore_dirs", "include", "exclude",
                "no_directly_upload_media", "tags", "tag_mode", "acl",
                "reason", "instruction"
            ]
        )]
        manifest: Option<String>,
        /// Explicit Connector source type (e.g. "tos", "git"). Routes the import
        /// through the Connector integration (must be enabled server-side); the
        /// path is sent verbatim and never treated as a local file. Requires --to
        /// and cannot be combined with --manifest, --parent, or
        /// --parent-auto-create
        #[arg(
            long = "add-type",
            value_name = "type",
            requires = "to",
            conflicts_with_all = ["manifest", "parent", "parent_auto_create"],
            help_heading = "Common options"
        )]
        add_type: Option<String>,
        /// Exact target URI (must not exist yet) (cannot be used with --parent)
        #[arg(long, value_name = "uri", help_heading = "Common options")]
        to: Option<String>,
        /// Target parent URI (must already exist and be a directory) (cannot be used with --to)
        #[arg(long, value_name = "uri", help_heading = "Common options")]
        parent: Option<String>,
        /// Target parent URI (create parent directory if it does not exist) (cannot be used with --to or --parent)
        #[arg(
            short = 'p',
            long = "parent-auto-create",
            value_name = "uri",
            help_heading = "Common options"
        )]
        parent_auto_create: Option<String>,
        /// Reason for import
        #[arg(
            long,
            default_value = "",
            value_name = "text",
            help_heading = "Advanced options"
        )]
        reason: String,
        /// Additional instruction
        #[arg(
            long,
            default_value = "",
            value_name = "text",
            help_heading = "Advanced options"
        )]
        instruction: String,
        /// Wait until processing is complete
        #[arg(long, help_heading = "Common options")]
        wait: bool,
        /// Enable strict mode for directory scanning (fail if any unsupported files found)
        #[arg(
            long = "strict",
            action = ArgAction::SetTrue,
            help_heading = "Advanced options"
        )]
        strict_mode: bool,
        /// Ignore directories, e.g. --ignore-dirs "node_modules,dist"
        #[arg(long, value_name = "dirs", help_heading = "Advanced options")]
        ignore_dirs: Option<String>,
        /// Include files extensions, e.g. --include "*.pdf,*.md"
        #[arg(long, value_name = "pattern", help_heading = "Common options")]
        include: Option<String>,
        /// Exclude files extensions, e.g. --exclude "*.tmp,*.log"
        #[arg(long, value_name = "pattern", help_heading = "Common options")]
        exclude: Option<String>,
        /// Do not directly upload media files
        #[arg(
            long = "no-directly-upload-media",
            default_value_t = false,
            help_heading = "Advanced options"
        )]
        no_directly_upload_media: bool,
        /// Watch interval in minutes for automatic resource monitoring (0 = no monitoring)
        #[arg(long, value_name = "minutes", help_heading = "Advanced options")]
        watch_interval: Option<f64>,
        /// Resource processing mode
        #[arg(
            long = "processing-mode",
            default_value = "semantic_and_vectors",
            value_parser = ["semantic_and_vectors", "vectors_only"],
            help_heading = "Advanced options"
        )]
        processing_mode: String,
        /// Extra options as key:value pairs or a JSON object. With a path/URL:
        /// parser-specific import options sent to the server, e.g.
        /// --args feishu_access_token:u-xxx. With --manifest: run options consumed
        /// locally, e.g. --args dry_run:true (supported keys: catalog, dry_run, skip_failed)
        #[arg(long = "args")]
        resource_args: Option<String>,
        /// Comma-separated k=v retrieval tags to apply after import
        #[arg(long = "tags", value_delimiter = ',', value_name = "k=v", help_heading = "Common options")]
        tags: Vec<String>,
        /// Tag update mode; clear does not require --tags
        #[arg(
            long = "tag-mode",
            default_value = "replace",
            value_parser = ["replace", "append", "clear"],
            help_heading = "Common options"
        )]
        tag_mode: String,
        #[command(flatten)]
        upload_options: UploadCliOptions,
        /// ACL JSON, for example {"acl_mode":"restricted","entries":[]}
        #[arg(long, value_parser = |s: &str| serde_json::from_str::<serde_json::Value>(s))]
        acl: Option<serde_json::Value>,
    },
    /// [Data] Add skills from a source (same as `skills add`)
    AddSkill(SkillAddArgs),
    /// [Data] Manage installed skills
    Skills {
        #[command(subcommand)]
        action: SkillCommands,
    },
    /// [Data] List directory contents
    #[command(alias = "list")]
    Ls {
        /// Viking URI to list (default: viking://)
        #[arg(default_value = "viking://", value_name = "uri")]
        uri: String,
        /// Simple path output (just paths, no table)
        #[arg(short, long, help_heading = "Common options")]
        simple: bool,
        /// List all subdirectories recursively
        #[arg(short, long, help_heading = "Common options")]
        recursive: bool,
        /// Abstract content limit (only for agent output)
        #[arg(
            long = "abs-limit",
            short = 'l',
            default_value = "256",
            value_name = "n",
            help_heading = "Advanced options"
        )]
        abs_limit: i32,
        /// Include directory L0 abstracts (defaults to the selected output mode)
        #[arg(
            long = "include-abstract",
            default_missing_value = "true",
            num_args = 0..=1,
            require_equals = true,
            action = ArgAction::Set,
            value_name = "bool",
            help_heading = "Output options"
        )]
        include_abstract: Option<bool>,
        /// Include directory L1 overviews
        #[arg(
            long = "include-overview",
            default_missing_value = "true",
            num_args = 0..=1,
            require_equals = true,
            action = ArgAction::Set,
            value_name = "bool",
            help_heading = "Output options"
        )]
        include_overview: Option<bool>,
        /// Maximum overview content length
        #[arg(
            long = "overview-limit",
            default_value = "4000",
            value_parser = clap::value_parser!(i32).range(1..),
            value_name = "n",
            help_heading = "Advanced options"
        )]
        overview_limit: i32,
        /// Show all hidden files
        #[arg(short, long, help_heading = "Common options")]
        all: bool,
        /// Maximum number of nodes to list
        #[arg(
            long = "node-limit",
            short = 'n',
            default_value = "256",
            value_parser = clap::value_parser!(i32).range(0..),
            value_name = "n",
            help_heading = "Common options"
        )]
        node_limit: i32,
        /// Number of visible entries to skip
        #[arg(
            long,
            default_value = "0",
            value_parser = clap::value_parser!(i32).range(0..),
            value_name = "n",
            help_heading = "Common options"
        )]
        offset: i32,
        /// Maximum number of visible entries to return
        #[arg(
            long,
            value_parser = clap::value_parser!(i32).range(1..),
            value_name = "n",
            help_heading = "Common options"
        )]
        limit: Option<i32>,
        /// Sort entries by name or modification time
        #[arg(long, value_parser = ["name", "mtime"], value_name = "field", help_heading = "Common options")]
        sort_by: Option<String>,
        /// Sort direction
        #[arg(
            long,
            requires = "sort_by",
            value_parser = ["asc", "desc"],
            value_name = "order",
            help_heading = "Common options"
        )]
        sort_order: Option<String>,
        /// Comma-separated fields to display (name,uri,path,type,size,mode,mtime,locked,id,count,tags,abstract,overview)
        #[arg(
            short = 'f',
            long = "fields",
            value_delimiter = ',',
            value_name = "FIELDS",
            help_heading = "Output options"
        )]
        fields: Option<Vec<String>>,
        /// Comma-separated k=v retrieval tags; all tags must match
        #[arg(long = "tags", value_delimiter = ',', value_name = "k=v", help_heading = "Common options")]
        tags: Vec<String>,
    },
    /// [Data] Get directory tree
    Tree {
        /// Viking URI to get tree for
        #[arg(value_name = "uri")]
        uri: String,
        /// Maximum returned abstract length
        #[arg(
            long = "abs-limit",
            short = 'l',
            default_value = "128",
            value_name = "n",
            help_heading = "Advanced options"
        )]
        abs_limit: i32,
        /// Include directory L0 abstracts (defaults to the selected output mode)
        #[arg(
            long = "include-abstract",
            default_missing_value = "true",
            num_args = 0..=1,
            require_equals = true,
            action = ArgAction::Set,
            value_name = "bool",
            help_heading = "Output options"
        )]
        include_abstract: Option<bool>,
        /// Include directory L1 overviews
        #[arg(
            long = "include-overview",
            default_missing_value = "true",
            num_args = 0..=1,
            require_equals = true,
            action = ArgAction::Set,
            value_name = "bool",
            help_heading = "Output options"
        )]
        include_overview: Option<bool>,
        /// Maximum overview content length
        #[arg(
            long = "overview-limit",
            default_value = "4000",
            value_parser = clap::value_parser!(i32).range(1..),
            value_name = "n",
            help_heading = "Advanced options"
        )]
        overview_limit: i32,
        /// Show all hidden files
        #[arg(short, long, help_heading = "Common options")]
        all: bool,
        /// Only include directories
        #[arg(long = "directories-only", help_heading = "Common options")]
        directories_only: bool,
        /// Maximum number of nodes to list
        #[arg(
            long = "node-limit",
            short = 'n',
            default_value = "256",
            value_parser = clap::value_parser!(i32).range(0..),
            value_name = "n",
            help_heading = "Common options"
        )]
        node_limit: i32,
        /// Number of visible entries to skip
        #[arg(
            long,
            default_value = "0",
            value_parser = clap::value_parser!(i32).range(0..),
            value_name = "n",
            help_heading = "Common options"
        )]
        offset: i32,
        /// Maximum number of visible entries to return
        #[arg(
            long,
            value_parser = clap::value_parser!(i32).range(1..),
            value_name = "n",
            help_heading = "Common options"
        )]
        limit: Option<i32>,
        /// Maximum depth level to traverse (default: 3)
        #[arg(
            short = 'L',
            long = "level-limit",
            default_value = "3",
            value_name = "n",
            help_heading = "Common options"
        )]
        level_limit: i32,
        /// Simple path output (just paths, no tree formatting)
        #[arg(short, long, help_heading = "Common options")]
        simple: bool,
        /// Comma-separated fields to display (name,uri,path,type,size,mode,mtime,locked,id,count,tags,abstract,overview)
        #[arg(short = 'f', long = "fields", value_delimiter = ',', value_name = "FIELDS", help_heading = "Output options")]
        fields: Option<Vec<String>>,
        /// Comma-separated k=v retrieval tags; all tags must match
        #[arg(long = "tags", value_delimiter = ',', value_name = "k=v", help_heading = "Common options")]
        tags: Vec<String>,
    },
    /// [Data] Create directory
    Mkdir {
        /// Directory URI to create
        #[arg(value_name = "uri")]
        uri: String,
        /// Initial directory description
        #[arg(long, value_name = "text", help_heading = "Common options")]
        description: Option<String>,
        /// ACL JSON, for example {"acl_mode":"restricted","entries":[]}
        #[arg(long, value_parser = |s: &str| serde_json::from_str::<serde_json::Value>(s))]
        acl: Option<serde_json::Value>,
    },
    /// [Data] Remove resource
    #[command(alias = "del", alias = "delete")]
    Rm {
        /// Viking URI to remove
        #[arg(value_name = "uri")]
        uri: String,
        /// Remove recursively
        #[arg(short, long, help_heading = "Common options")]
        recursive: bool,
        /// Wait until semantic refresh is complete
        #[arg(long, help_heading = "Common options")]
        wait: bool,
    },
    /// [Data] Copy a file or directory
    Cp {
        /// Source URI
        #[arg(value_name = "source")]
        from_uri: String,
        /// Target URI
        #[arg(value_name = "target")]
        to_uri: String,
        /// Copy a directory recursively
        #[arg(short, long, help_heading = "Common options")]
        recursive: bool,
    },
    /// [Data] Move or rename resource
    #[command(alias = "rename")]
    Mv {
        /// Source URI
        #[arg(value_name = "from-uri")]
        from_uri: String,
        /// Target URI
        #[arg(value_name = "to-uri")]
        to_uri: String,
    },
    /// [Data] Get resource metadata
    Stat {
        /// Viking URI to get metadata for
        #[arg(value_name = "uri")]
        uri: String,
    },
    /// [Data] Get logical extended attributes
    Attrs {
        #[command(subcommand)]
        action: AttrsCommands,
    },
    /// [Data] Manage resource ACL
    Acl {
        #[command(subcommand)]
        action: AclCommands,
    },
    /// [Data] Read file content (Level 2)
    Read {
        /// Viking URI
        #[arg(value_name = "uri")]
        uri: String,
        /// Starting line offset (0-indexed)
        #[arg(long, default_value_t = 0, value_parser = clap::value_parser!(i64).range(0..), help_heading = "Common options")]
        offset: i64,
        /// Number of lines to read; -1 reads to the end
        #[arg(long, default_value_t = -1, allow_negative_numbers = true, value_parser = clap::value_parser!(i64).range(-1..), help_heading = "Common options")]
        limit: i64,
    },
    /// [Data] Read abstract content (Level 0)
    Abstract {
        /// Directory URI
        #[arg(value_name = "directory-uri")]
        uri: String,
    },
    /// [Data] Read overview content (Level 1)
    Overview {
        /// Directory URI
        #[arg(value_name = "directory-uri")]
        uri: String,
    },
    /// [Data] Write text content to an existing file
    Write {
        /// Viking URI
        #[arg(value_name = "uri")]
        uri: String,
        /// Content to write
        #[arg(
            long,
            conflicts_with = "from_file",
            value_name = "text",
            help_heading = "Common options"
        )]
        content: Option<String>,
        /// Read content from a local file
        #[arg(
            long = "from-file",
            conflicts_with = "content",
            value_name = "path",
            help_heading = "Common options"
        )]
        from_file: Option<String>,
        /// Append instead of replacing the file
        #[arg(long, help_heading = "Common options")]
        append: bool,
        /// Write mode: replace, append, or create (default: replace)
        #[arg(
            long,
            value_name = "replace|append|create",
            conflicts_with = "append",
            help_heading = "Advanced options"
        )]
        mode: Option<String>,
        /// Wait for async processing to finish
        #[arg(long, default_value = "false", help_heading = "Common options")]
        wait: bool,
        /// Content post-write processing mode
        #[arg(
            long = "processing-mode",
            default_value = "semantic_and_vectors",
            value_parser = ["semantic_and_vectors", "vectors_only"],
            help_heading = "Advanced options"
        )]
        processing_mode: String,
        /// Comma-separated k=v retrieval tags to write with the content
        #[arg(long = "tags", value_delimiter = ',')]
        tags: Vec<String>,
        /// Tag update mode; clear does not require --tags
        #[arg(long = "tag-mode", default_value = "replace", value_parser = ["replace", "append", "clear"])]
        tag_mode: String,
        /// ACL JSON, for example {"acl_mode":"restricted","entries":[]}
        #[arg(long, value_parser = |s: &str| serde_json::from_str::<serde_json::Value>(s))]
        acl: Option<serde_json::Value>,
        /// Who made the edit, recorded in Compile output versions
        #[arg(
            long = "edit-source",
            default_value = "agent",
            value_parser = ["manual", "agent", "compile"],
            help_heading = "Advanced options"
        )]
        edit_source: String,
    },
    /// [Data] Update explicit retrieval tags metadata for a file or directory
    #[command(hide = true)]
    SetTags {
        /// Viking URI
        uri: String,
        /// Comma-separated k=v tags, e.g. env=prod,team=search
        #[arg(long = "tags", value_delimiter = ',')]
        tags: Vec<String>,
        /// Tag update mode: replace or append (append replaces existing values by key)
        #[arg(long, default_value = "replace")]
        mode: String,
        /// Recursively update descendant files and semantic nodes when target is a directory
        #[arg(long, default_value = "false")]
        recursive: bool,
    },
    /// [Data] Download file to local path (supports binaries/images)
    Get {
        /// Viking URI
        #[arg(value_name = "uri")]
        uri: String,
        /// Local path (must not exist yet)
        #[arg(value_name = "local-path")]
        local_path: String,
    },
    /// [Data] Run semantic retrieval
    Find {
        /// Search query
        #[arg(value_name = "query")]
        query: Option<String>,
        /// Image query: local path, data URI, HTTP URL, or viking:// URI
        #[arg(
            long = "image",
            value_name = "path|uri",
            help_heading = "Common options"
        )]
        image: Option<String>,
        /// Target URI
        #[arg(
            short,
            long,
            default_value = "",
            value_name = "uri",
            help_heading = "Common options"
        )]
        uri: String,
        /// Maximum final results returned
        #[arg(
            short = 'n',
            long = "node-limit",
            alias = "limit",
            default_value = "10",
            value_parser = clap::value_parser!(i32).range(0..),
            value_name = "n",
            help_heading = "Common options"
        )]
        node_limit: i32,
        /// Score threshold
        #[arg(short, long, value_name = "score", help_heading = "Common options")]
        threshold: Option<f64>,
        /// Only include results on or after this time (e.g. 48h, 7d, 2026-03-10, ISO-8601)
        #[arg(long = "after", value_name = "time", help_heading = "Advanced options")]
        after: Option<String>,
        /// Only include results on or before this time (e.g. 24h, 2026-03-15, ISO-8601)
        #[arg(
            long = "before",
            value_name = "time",
            help_heading = "Advanced options"
        )]
        before: Option<String>,
        /// Only include results with specific level(s) (0=abstract, 1=overview, 2=file)
        #[arg(
            short = 'L',
            long = "level",
            value_delimiter = ',',
            value_name = "0,1,2",
            help_heading = "Common options"
        )]
        level: Option<Vec<i32>>,
        /// Only include results with specific context type(s) (memory, resource, skill)
        #[arg(
            long = "context-type",
            value_delimiter = ',',
            value_name = "type",
            help_heading = "Common options"
        )]
        context_type: Option<Vec<String>>,
        /// Only include results matching all of these explicit tags
        #[arg(long = "tags", value_delimiter = ',')]
        tags: Option<Vec<String>>,
        /// Include the full visible content for every matched URI
        #[arg(long, help_heading = "Advanced options")]
        read_content: bool,
        /// Enable event decay with protection duration: 0 (immediate) or Xm/Xh/Xd
        #[arg(
            long,
            alias = "events_time_decay_protection",
            value_parser = parse_event_time_decay_protection,
            help_heading = "Advanced options"
        )]
        events_time_decay_protection: Option<String>,
    },
    /// [Experimental][Data] Run context-aware retrieval
    Search {
        /// Search query
        #[arg(value_name = "query")]
        query: Option<String>,
        /// Image query: local path, data URI, HTTP URL, or viking:// URI
        #[arg(
            long = "image",
            value_name = "path|uri",
            help_heading = "Common options"
        )]
        image: Option<String>,
        /// Retrieval type
        #[arg(
            long,
            default_value = "semantic",
            value_parser = ["semantic", "keywords"],
            help_heading = "Common options"
        )]
        search_type: String,
        /// Return ranked hits (list) or assembled context (context)
        #[arg(
            long,
            default_value = "list",
            value_parser = ["list", "context"],
            value_name = "list|context",
            help_heading = "Common options"
        )]
        mode: String,
        /// Target URI (list mode only)
        #[arg(
            short,
            long,
            default_value = "",
            value_name = "uri",
            help_heading = "Common options"
        )]
        uri: String,
        /// Session ID for context-aware search
        #[arg(long, value_name = "id", help_heading = "Common options")]
        session_id: Option<String>,
        /// Maximum results per search pass. Search may merge multiple passes.
        #[arg(
            short = 'n',
            long = "node-limit",
            alias = "limit",
            default_value = "10",
            value_parser = clap::value_parser!(i32).range(0..),
            value_name = "n",
            help_heading = "Common options"
        )]
        node_limit: i32,
        /// Score threshold
        #[arg(short, long, value_name = "score", help_heading = "Advanced options")]
        threshold: Option<f64>,
        /// Only include results on or after this time (e.g. 48h, 7d, 2026-03-10, ISO-8601)
        #[arg(long = "after", value_name = "time", help_heading = "Advanced options")]
        after: Option<String>,
        /// Only include results on or before this time (e.g. 24h, 2026-03-15, ISO-8601)
        #[arg(
            long = "before",
            value_name = "time",
            help_heading = "Advanced options"
        )]
        before: Option<String>,
        /// Filter levels (0=abstract, 1=overview, 2=file); ignored in context mode
        #[arg(
            short = 'L',
            long = "level",
            value_delimiter = ',',
            value_name = "0,1,2",
            help_heading = "Advanced options"
        )]
        level: Option<Vec<i32>>,
        /// Only include results with specific context type(s) (memory, resource, skill)
        #[arg(
            long = "context-type",
            value_delimiter = ',',
            value_name = "type",
            help_heading = "Advanced options"
        )]
        context_type: Option<Vec<String>>,
        /// Only include results matching all of these explicit tags
        #[arg(long = "tags", value_delimiter = ',')]
        tags: Option<Vec<String>>,
        /// Include the full visible content for every matched URI (list mode only)
        #[arg(long, help_heading = "Advanced options")]
        read_content: bool,
        /// Enable event decay with protection duration: 0 (immediate) or Xm/Xh/Xd
        #[arg(
            long,
            alias = "events_time_decay_protection",
            value_parser = parse_event_time_decay_protection,
            help_heading = "Advanced options"
        )]
        events_time_decay_protection: Option<String>,
    },
    /// [Data] Run content pattern search
    Grep {
        /// Target URI
        #[arg(
            short,
            long,
            default_value = "viking://",
            value_name = "uri",
            help_heading = "Common options"
        )]
        uri: String,
        /// Excluded URI range. Any entry whose URI falls under this URI prefix is skipped
        #[arg(
            short = 'x',
            long = "exclude-uri",
            value_name = "uri",
            help_heading = "Advanced options"
        )]
        exclude_uri: Option<String>,
        /// Search pattern
        #[arg(value_name = "pattern")]
        pattern: String,
        /// Case insensitive
        #[arg(short, long, help_heading = "Common options")]
        ignore_case: bool,
        /// Number of lines to show after each match
        #[arg(
            short = 'a',
            long = "after-context",
            default_value = "0",
            value_parser = clap::value_parser!(i32).range(0..),
            value_name = "n",
            help_heading = "Common options"
        )]
        after_context: i32,
        /// Number of lines to show before each match
        #[arg(
            short = 'b',
            long = "before-context",
            default_value = "0",
            value_parser = clap::value_parser!(i32).range(0..),
            value_name = "n",
            help_heading = "Common options"
        )]
        before_context: i32,
        /// Maximum number of results
        #[arg(
            short = 'n',
            long = "node-limit",
            alias = "limit",
            default_value = "256",
            value_parser = clap::value_parser!(i32).range(0..),
            value_name = "n",
            help_heading = "Common options"
        )]
        node_limit: i32,
        /// Maximum depth level to traverse (default: 10)
        #[arg(
            short = 'L',
            long = "level-limit",
            default_value = "10",
            value_name = "n",
            help_heading = "Advanced options"
        )]
        level_limit: i32,
        /// Comma-separated k=v retrieval tags; all tags must match
        #[arg(long = "tags", value_delimiter = ',', value_name = "k=v", help_heading = "Common options")]
        tags: Vec<String>,
        /// Fields to include in output (currently: tags)
        #[arg(short = 'f', long = "fields", value_delimiter = ',', value_name = "FIELDS", help_heading = "Output options")]
        fields: Option<Vec<String>>,
    },
    /// [Data] Run file glob pattern search
    Glob {
        /// Glob pattern
        #[arg(value_name = "pattern")]
        pattern: String,
        /// Search root URI
        #[arg(
            short,
            long,
            default_value = "viking://",
            value_name = "uri",
            help_heading = "Common options"
        )]
        uri: String,
        /// Maximum number of results
        #[arg(
            short = 'n',
            long = "node-limit",
            alias = "limit",
            default_value = "256",
            value_parser = clap::value_parser!(i32).range(0..),
            value_name = "n",
            help_heading = "Common options"
        )]
        node_limit: i32,
        /// Simple output (one entry per line)
        #[arg(short, long, help_heading = "Common options")]
        simple: bool,
        /// Comma-separated k=v retrieval tags; all tags must match
        #[arg(long = "tags", value_delimiter = ',', value_name = "k=v", help_heading = "Common options")]
        tags: Vec<String>,
        /// Comma-separated fields to display (name,uri,path,type,size,mode,mtime,locked,id,tags)
        #[arg(short = 'f', long = "fields", value_delimiter = ',', value_name = "FIELDS", help_heading = "Output options")]
        fields: Option<Vec<String>>,
    },
    /// [Data] Session management commands
    Session {
        #[command(subcommand)]
        action: SessionCommands,
    },
    /// [Experimental][Data] Add memory in one shot (creates session, adds messages, commits)
    AddMemory {
        /// Content to memorize. Plain string (treated as user message),
        /// JSON {"role":"...","content":"..."} for a single message,
        /// or JSON array of such objects for multiple messages.
        #[arg(value_name = "content")]
        content: String,
    },
    /// [Data] Privacy config management commands
    Privacy {
        #[command(subcommand)]
        action: Box<PrivacyCommands>,
    },
    /// [Data] Export context as .ovpack
    Export {
        /// Source URI
        #[arg(value_name = "uri")]
        uri: String,
        /// Output .ovpack file path
        #[arg(value_name = "output.ovpack")]
        to: String,
        /// Include dense vector snapshot when compatible metadata is available
        #[arg(long, default_value_t = false, help_heading = "Common options")]
        include_vectors: bool,
    },
    /// [Data] Back up public OpenViking scopes as a restore-only .ovpack
    Backup {
        /// Output .ovpack file path
        #[arg(value_name = "output.ovpack")]
        to: String,
        /// Include dense vector snapshot when compatible metadata is available
        #[arg(long, default_value_t = false, help_heading = "Common options")]
        include_vectors: bool,
    },
    /// [Data] Import .ovpack into target URI
    Import {
        /// Input .ovpack file path
        #[arg(value_name = "file.ovpack")]
        file_path: String,
        /// Target parent URI
        #[arg(value_name = "target-uri")]
        target_uri: String,
        /// Conflict policy: fail, overwrite, or skip
        #[arg(
            long,
            value_parser = ["fail", "overwrite", "skip"],
            value_name = "policy",
            help_heading = "Common options"
        )]
        on_conflict: Option<String>,
        /// Vector handling: auto restores compatible snapshots, recompute ignores them, require fails if unavailable
        #[arg(
            long,
            value_parser = ["auto", "recompute", "require"],
            value_name = "mode",
            help_heading = "Common options"
        )]
        vector_mode: Option<String>,
    },
    /// [Data] Restore a backup .ovpack to original public scope roots
    Restore {
        /// Input backup .ovpack file path
        #[arg(value_name = "backup.ovpack")]
        file_path: String,
        /// Conflict policy: fail, overwrite, or skip
        #[arg(
            long,
            value_parser = ["fail", "overwrite", "skip"],
            value_name = "policy",
            help_heading = "Common options"
        )]
        on_conflict: Option<String>,
        /// Vector handling: auto restores compatible snapshots, recompute ignores them, require fails if unavailable
        #[arg(
            long,
            value_parser = ["auto", "recompute", "require"],
            value_name = "mode",
            help_heading = "Common options"
        )]
        vector_mode: Option<String>,
    },
    // --- Interactive Tools ---
    /// [Interactive] Interactive TUI file explorer
    Tui {
        /// Viking URI to start browsing (default: /)
        #[arg(default_value = "/", value_name = "uri")]
        uri: String,
    },
    /// [Interactive] Chat with vikingbot agent
    Chat {
        /// Message to send to the agent
        #[arg(short, long, value_name = "text", help_heading = "Common options")]
        message: Option<String>,
        /// Session ID (defaults to machine unique ID)
        #[arg(short, long, value_name = "id", help_heading = "Common options")]
        session: Option<String>,
        /// Sender ID
        #[arg(
            long,
            default_value = "user",
            value_name = "id",
            help_heading = "Advanced options"
        )]
        sender: String,
        /// Stream the response (default: true)
        #[arg(
            long,
            default_value_t = true,
            value_name = "bool",
            help_heading = "Advanced options"
        )]
        stream: bool,
        /// Disable rich formatting / markdown rendering
        #[arg(long, help_heading = "Common options")]
        no_format: bool,
        /// Disable command history
        #[arg(long, help_heading = "Advanced options")]
        no_history: bool,
    },
    /// [Interactive] Compile source materials with a VikingBot Skill
    Compile {
        /// Source file or directory; repeat the flag or separate entries with commas.
        /// Omitted with `--skill memory`, which consolidates `--to` in place.
        #[arg(
            long = "from",
            value_delimiter = ',',
            value_name = "uri"
        )]
        from_uris: Vec<String>,
        /// Target resource directory or skills namespace
        #[arg(long, value_name = "uri")]
        to: String,
        /// Skill directory or SKILL.md Viking URI; the literal `memory` runs memory consolidation
        #[arg(long, value_name = "uri")]
        skill: String,
        /// Additional instructions for this Compile task
        #[arg(long, value_name = "text")]
        instruction: Option<String>,
        /// Provider arguments as JSON; VikingBot wiki_links defaults to false
        #[arg(long, value_name = "json")]
        args: Option<String>,
    },

    // --- Status & Observability ---
    /// [Status] Wait for queued async processing to complete
    Wait,
    /// [Status] Track async resource processing tasks
    Task {
        #[command(subcommand)]
        action: TaskCommands,
    },
    /// [Version] Manage workspace snapshots (commit, restore, show, diff, log)
    Snapshot {
        #[command(subcommand)]
        cmd: SnapshotCmd,
    },
    /// [Status] All OpenViking Server components status
    Status {
        /// Show full component tables
        #[arg(long, help_heading = "Common options")]
        verbose: bool,
    },
    /// [Status] Observe OpenViking Server components status
    Observer {
        #[command(subcommand)]
        action: ObserverCommands,
    },
    /// [Status] Quick health check
    Health,
    /// [Status] Configuration management; run without a subcommand to add, edit, or delete configs
    Config {
        #[command(subcommand)]
        action: Option<ConfigCommands>,
    },
    /// [Status] Choose CLI display language
    #[command(alias = "lang")]
    Language {
        /// Language code: en or zh-CN
        #[arg(value_name = "en|zh-CN")]
        language: Option<String>,
    },
    /// [Status] Show CLI version
    Version,

    // --- Admin Tools ---
    /// [Admin] Account and user management commands (multi-tenant)
    Admin {
        #[command(subcommand)]
        action: AdminCommands,
    },
    /// [Admin] System utility commands
    System {
        #[command(subcommand)]
        action: SystemCommands,
    },
    /// [Admin] Reindex semantic/vector artifacts for a URI
    Reindex {
        /// Viking URI
        #[arg(value_name = "uri")]
        uri: String,
        /// Reindex mode: vectors_only rebuilds vectors; semantic_and_vectors regenerates semantic artifacts, then vectors
        #[arg(
            long,
            default_value = "vectors_only",
            value_parser = ["vectors_only", "semantic_and_vectors"],
            value_name = "mode",
            help_heading = "Common options"
        )]
        mode: String,
        /// Wait for reindex to complete
        #[arg(
            long,
            default_value_t = true,
            action = ArgAction::Set,
            value_name = "bool",
            help_heading = "Common options"
        )]
        wait: bool,
        /// Rebuild all selected semantic/vector data without comparing fingerprints
        #[arg(long, help_heading = "Common options")]
        force: bool,
        /// Comma-separated k=v retrieval tags for rebuilt vector records
        #[arg(long = "tags", value_delimiter = ',', value_name = "k=v", help_heading = "Common options")]
        tags: Vec<String>,
        /// Tag update mode; clear does not require --tags
        #[arg(
            long = "tag-mode",
            default_value = "replace",
            value_parser = ["replace", "append", "clear"],
            help_heading = "Common options"
        )]
        tag_mode: String,
        /// Recursively reindex subdirectories (only affects semantic_and_vectors)
        #[arg(
            long,
            default_value_t = true,
            action = ArgAction::Set,
            value_name = "bool",
            help_heading = "Common options"
        )]
        recursive: bool,
    },
}

impl Commands {
    /// Returns true if this command supports running with the root API key.
    fn supports_sudo(&self) -> bool {
        match self {
            Self::Admin { .. } | Self::System { .. } | Self::Reindex { .. } => true,
            Self::Task { action } => matches!(
                action,
                TaskCommands::Status { .. } | TaskCommands::List { .. }
            ),
            _ => false,
        }
    }

    fn supports_upload_options(&self) -> bool {
        matches!(
            self,
            Self::AddResource { .. }
                | Self::AddSkill(_)
                | Self::Skills {
                    action: SkillCommands::Add(_)
                }
        )
    }
}

fn legacy_upload_option_error(
    options: UploadCliOptions,
    command: &Commands,
) -> Option<&'static str> {
    if options.is_set() && !command.supports_upload_options() {
        Some(
            "--progress, --no-progress, and --verbose are only supported for add-resource, add-skill, and skills add.",
        )
    } else {
        None
    }
}

#[derive(Subcommand)]
enum TaskCommands {
    /// Show status of a specific task
    Status {
        /// Task ID returned by an asynchronous command, including compile
        #[arg(value_name = "task-id")]
        task_id: String,
    },
    /// Cancel a task
    Cancel {
        /// Task ID returned by an asynchronous command, including compile
        #[arg(value_name = "task-id")]
        task_id: String,
    },
    /// List all tracked tasks
    List {
        /// Filter by task type (e.g. add_resource, add_skill, session_commit, reindex)
        #[arg(long, value_name = "type")]
        task_type: Option<String>,
        /// Filter by status (pending, running, cancelling, completed, failed, cancelled)
        #[arg(long, value_name = "status")]
        status: Option<String>,
    },
    /// Watch task management (auto-refresh subscriptions)
    Watch {
        #[command(subcommand)]
        action: WatchCommands,
    },
}

#[derive(Subcommand)]
pub(crate) enum SnapshotCmd {
    /// Create a snapshot of current workspace state
    Commit {
        #[arg(short = 'm', long)]
        message: String,
        /// Limit to specific viking:// URIs (comma-separated); accepts files and directories. Directories are expanded recursively with the snapshot pruning rules. Required for USER/ADMIN callers; only local ROOT mode may omit paths to snapshot the full account tree.
        #[arg(long, value_delimiter = ',')]
        paths: Option<Vec<String>>,
        #[arg(long, default_value = "main")]
        branch: String,
        #[arg(long)]
        author_name: Option<String>,
        #[arg(long)]
        author_email: Option<String>,
    },
    /// Restore a project directory or the full account tree to a past snapshot (forward commit)
    Restore {
        /// Commit oid, branch, or tag
        source_commit: String,
        /// Optional viking:// directory or relative tree path; omit for full-tree restore
        project_dir: Option<String>,
        #[arg(long, default_value = "main")]
        branch: String,
        #[arg(long)]
        dry_run: bool,
        #[arg(short = 'm', long)]
        message: Option<String>,
        #[arg(long)]
        author_name: Option<String>,
        #[arg(long)]
        author_email: Option<String>,
    },
    /// Show a commit's metadata, or a single blob at a path
    Show {
        target_ref: String,
        /// viking:// URI of a file; omit to show commit metadata
        #[arg(long)]
        path: Option<String>,
        /// Write blob bytes to this file (default: stdout)
        #[arg(long = "out-file")]
        out_path: Option<std::path::PathBuf>,
    },
    /// Walk commit history (newest first)
    Log {
        #[arg(long, default_value = "main")]
        branch: String,
        #[arg(long, default_value_t = 20)]
        limit: u32,
        /// Show only commits touching any of these viking:// URIs (comma-separated); accepts files and directories.
        #[arg(long, value_delimiter = ',')]
        paths: Option<Vec<String>>,
    },
    /// Compare one file between two snapshots
    Diff {
        /// viking:// URI of the file to compare
        path: String,
        /// Older commit oid, branch, or tag; omit to compare an empty file
        #[arg(long = "from")]
        from_ref: Option<String>,
        /// Newer commit oid, branch, or tag
        #[arg(long = "to")]
        to_ref: String,
    },
    /// List changed source files under directories between two snapshots
    DiffPaths {
        /// Directory URIs (comma-separated)
        #[arg(long, value_delimiter = ',', required = true, num_args = 1..)]
        paths: Vec<String>,
        /// Older commit oid, branch, or tag; omit to compare an empty tree
        #[arg(long = "from")]
        from_ref: Option<String>,
        /// Newer commit oid, branch, or tag
        #[arg(long = "to")]
        to_ref: String,
        #[arg(long, default_value_t = 0)]
        offset: u32,
        #[arg(long, default_value_t = 100, value_parser = clap::value_parser!(u32).range(1..=1000))]
        limit: u32,
    },
    /// Get the account .ovgitignore content
    IgnoreGet,
    /// Set the account .ovgitignore content
    IgnoreSet {
        /// .ovgitignore content passed inline
        #[arg(long = "content")]
        content: Option<String>,
        /// File to read the content from; takes precedence over --content
        #[arg(long = "file")]
        file: Option<std::path::PathBuf>,
    },
    /// Delete the account .ovgitignore
    IgnoreDelete,
}

#[derive(Subcommand)]
enum SystemCommands {
    /// Wait for queued async processing to complete
    Wait,
    /// Show component status
    Status,
    /// Quick health check
    Health,
    /// Check filesystem and vector-index consistency for a URI subtree
    Consistency {
        /// Viking URI to check
        #[arg(value_name = "uri")]
        uri: String,
    },
    /// Cryptographic key management commands
    Crypto {
        #[command(subcommand)]
        action: commands::crypto::CryptoCommands,
    },
}

#[derive(Subcommand)]
enum ObserverCommands {
    /// Get queue status
    Queue,
    /// Get VikingDB status
    Vikingdb,
    /// Get models status (VLM, Embedding, Rerank)
    Models,
    /// Get retrieval quality metrics
    Retrieval,
    /// Get filesystem operation metrics
    #[command(alias = "fs")]
    Filesystem,
    /// Get overall system status
    System,
}

#[derive(Subcommand)]
enum SessionCommands {
    /// Create a new session
    New {
        /// Optional session ID
        #[arg(long = "session-id", value_name = "session-id")]
        session_id: Option<String>,
        /// Default event-memory tags as comma-separated key=value pairs
        #[arg(long = "event-tags", value_name = "key=value", value_delimiter = ',')]
        event_tags: Vec<String>,
        /// Auto-commit policy as a JSON object
        #[arg(
            long = "auto-commit-policy-json",
            value_name = "json",
            conflicts_with = "no_auto_commit"
        )]
        auto_commit_policy_json: Option<String>,
        /// Disable automatic commits for this session
        #[arg(long = "no-auto-commit", conflicts_with = "auto_commit_policy_json")]
        no_auto_commit: bool,
    },
    /// List sessions
    List,
    /// Get session details
    Get {
        /// Session ID
        #[arg(value_name = "session-id")]
        session_id: String,
    },
    /// Get full merged session context
    GetSessionContext {
        /// Session ID
        #[arg(value_name = "session-id")]
        session_id: String,
        /// Token budget for latest archive overview inclusion
        #[arg(long = "token-budget", default_value = "128000", value_name = "tokens")]
        token_budget: i32,
    },
    /// Get one completed archive for a session
    GetSessionArchive {
        /// Session ID
        #[arg(value_name = "session-id")]
        session_id: String,
        /// Archive ID
        #[arg(value_name = "archive-id")]
        archive_id: String,
    },
    /// Delete a session
    Delete {
        /// Session ID
        #[arg(value_name = "session-id")]
        session_id: String,
    },
    /// Add one message to a session
    AddMessage {
        /// Session ID
        #[arg(value_name = "session-id")]
        session_id: String,
        /// Message role, e.g. user/assistant
        #[arg(long, value_name = "role")]
        role: String,
        /// Message content
        #[arg(long, value_name = "content")]
        content: String,
        /// Stable interaction peer id. Omit for self memory.
        #[arg(long = "peer-id", value_name = "peer-id")]
        peer_id: Option<String>,
    },
    /// Add multiple messages to a session
    AddMessages {
        /// Session ID
        #[arg(value_name = "session-id")]
        session_id: String,
        /// Messages as JSON array of {role, content} objects
        #[arg(value_name = "messages-json")]
        messages: String,
    },
    /// Update mutable session configuration
    Config {
        #[command(subcommand)]
        action: SessionConfigCommands,
    },
    /// Commit a session (archive messages and extract memories)
    Commit {
        /// Session ID
        #[arg(value_name = "session-id")]
        session_id: String,
        /// Event-memory tags for this commit as comma-separated key=value pairs
        #[arg(
            long = "event-tags",
            value_name = "key=value",
            value_delimiter = ',',
            conflicts_with = "no_event_tags"
        )]
        event_tags: Vec<String>,
        /// Do not apply the session's default event tags to this commit
        #[arg(long = "no-event-tags", conflicts_with = "event_tags")]
        no_event_tags: bool,
    },
}

#[derive(Subcommand)]
enum SessionConfigCommands {
    /// Set mutable session configuration
    Set {
        /// Session ID
        #[arg(value_name = "session-id")]
        session_id: String,
        /// Default event-memory tags as comma-separated key=value pairs
        #[arg(
            long = "event-tags",
            value_name = "key=value",
            value_delimiter = ',',
            required_unless_present_any = [
                "no_event_tags",
                "auto_commit_policy_json",
                "no_auto_commit"
            ],
            conflicts_with = "no_event_tags"
        )]
        event_tags: Vec<String>,
        /// Clear the session's default event-memory tags
        #[arg(
            long = "no-event-tags",
            required_unless_present_any = [
                "event_tags",
                "auto_commit_policy_json",
                "no_auto_commit"
            ],
            conflicts_with = "event_tags"
        )]
        no_event_tags: bool,
        /// Auto-commit policy fields as a JSON object
        #[arg(
            long = "auto-commit-policy-json",
            value_name = "json",
            required_unless_present_any = ["event_tags", "no_event_tags", "no_auto_commit"],
            conflicts_with = "no_auto_commit"
        )]
        auto_commit_policy_json: Option<String>,
        /// Disable automatic commits for this session
        #[arg(
            long = "no-auto-commit",
            required_unless_present_any = [
                "event_tags",
                "no_event_tags",
                "auto_commit_policy_json"
            ],
            conflicts_with = "auto_commit_policy_json"
        )]
        no_auto_commit: bool,
    },
}

#[derive(Args)]
struct SkillAddArgs {
    /// Local skill file/directory, Git repository or GitHub tree URL, or raw content
    #[arg(value_name = "source")]
    source: String,
    /// Install only the named skill(s); use '*' to install all skills in a source
    #[arg(short = 's', long = "skill", value_name = "NAME", num_args = 1.., value_delimiter = ',')]
    skills: Vec<String>,
    /// List available skills in the source without installing
    #[arg(short = 'l', long = "list")]
    list: bool,
    /// Wait until processing is complete
    #[arg(short = 'w', long)]
    wait: bool,
    /// Skip confirmation prompt
    #[arg(short = 'y', long = "yes")]
    yes: bool,
    /// Parent skill root URI (e.g. viking://agent/skills); defaults to user-private skills
    #[arg(short = 'p', long = "parent-auto-create", value_name = "uri")]
    parent: Option<String>,
    #[command(flatten)]
    upload_options: UploadCliOptions,
}

#[derive(Subcommand)]
enum SkillCommands {
    /// Add skills from a source
    Add(SkillAddArgs),
    /// List installed agent skills
    #[command(alias = "ls")]
    List {
        /// Maximum number of skills to list
        #[arg(
            short = 'n',
            long = "node-limit",
            alias = "limit",
            default_value = "1000",
            value_parser = clap::value_parser!(i32).range(0..),
            value_name = "n"
        )]
        node_limit: i32,
        /// Restrict listing to a specific skill root URI (defaults to merged user + agent)
        #[arg(short = 'p', long = "uri", value_name = "uri")]
        parent: Option<String>,
    },
    /// Find installed agent skills semantically
    Find {
        /// Search query
        #[arg(value_name = "query")]
        query: String,
        /// Maximum number of results
        #[arg(
            short = 'n',
            long = "node-limit",
            alias = "limit",
            default_value = "10",
            value_parser = clap::value_parser!(i32).range(0..),
            value_name = "n"
        )]
        node_limit: i32,
        /// Score threshold
        #[arg(short, long, value_name = "score")]
        threshold: Option<f64>,
        /// Only include results with specific level(s) (0=abstract, 1=overview, 2=file)
        #[arg(
            short = 'L',
            long = "level",
            value_delimiter = ',',
            value_name = "0,1,2"
        )]
        level: Option<Vec<i32>>,
        /// Restrict search to a specific skill root URI (defaults to merged user + agent)
        #[arg(short = 'p', long = "uri", value_name = "uri")]
        parent: Option<String>,
    },
    /// Show one installed skill
    Show {
        /// Skill name
        #[arg(value_name = "name")]
        name: String,
        /// Detail level to show (0=abstract, 1=overview, 2=SKILL.md content)
        #[arg(
            short = 'L',
            long = "level",
            value_parser = clap::value_parser!(i32).range(0..=2),
            value_name = "0|1|2"
        )]
        level: Option<i32>,
        /// Include files under the skill directory
        #[arg(short = 'f', long = "files")]
        files: bool,
        /// Include source metadata when available
        #[arg(long = "source")]
        source: bool,
        /// Output format for this command
        #[arg(long = "format", value_parser = ["table", "json"], value_name = "table|json")]
        format: Option<String>,
        /// Include full SKILL.md content (legacy alias for --level 2)
        #[arg(long, hide = true)]
        content: bool,
        /// Resolve the skill under a specific root URI (e.g. viking://agent/skills)
        #[arg(short = 'p', long = "uri", value_name = "uri")]
        parent: Option<String>,
    },
    /// Update installed skills from their recorded source
    Update {
        /// Skill name(s) to update; omit to update all installed skills
        #[arg(value_name = "skill")]
        skills: Vec<String>,
        /// Wait until processing is complete
        #[arg(short = 'w', long)]
        wait: bool,
        /// Skip confirmation prompt
        #[arg(short = 'y', long = "yes")]
        yes: bool,
        /// Resolve the skill under a specific root URI (e.g. viking://agent/skills)
        #[arg(short = 'p', long = "parent-auto-create", value_name = "uri")]
        parent: Option<String>,
    },
    /// Remove installed skills
    #[command(alias = "rm", alias = "delete")]
    Remove {
        /// Skill name(s) to remove
        #[arg(value_name = "skill")]
        skills: Vec<String>,
        /// Remove all installed skills
        #[arg(long = "all")]
        all: bool,
        /// Skip confirmation prompt
        #[arg(short = 'y', long = "yes")]
        yes: bool,
        /// Resolve the skill under a specific root URI (e.g. viking://agent/skills)
        #[arg(short = 'p', long = "parent-auto-create", value_name = "uri")]
        parent: Option<String>,
    },
    /// Validate a local SKILL.md file or skill directory
    Validate {
        /// SKILL.md file or skill directory path
        #[arg(value_name = "path")]
        path: String,
        /// Strict mode; warnings such as name mismatch are reported as errors
        #[arg(long = "strict")]
        strict: bool,
    },
}

#[derive(Subcommand)]
enum WatchCommands {
    /// List watch tasks (auto-refresh subscriptions)
    Ls {
        /// Only show active (non-paused) tasks
        #[arg(long, default_value_t = false)]
        active_only: bool,
    },
    /// Show details of a single watch task
    Show {
        /// task_id (UUID) or to_uri (viking:// URI)
        #[arg(value_name = "task-or-uri")]
        key: String,
    },
    /// Delete a watch task
    Rm {
        /// task_id (UUID) or to_uri (viking:// URI)
        #[arg(value_name = "task-or-uri")]
        key: String,
    },
    /// Pause a watch task (preserves cadence, stops scheduling)
    Pause {
        /// task_id (UUID) or to_uri (viking:// URI)
        #[arg(value_name = "task-or-uri")]
        key: String,
    },
    /// Resume a paused watch task
    Resume {
        /// task_id (UUID) or to_uri (viking:// URI)
        #[arg(value_name = "task-or-uri")]
        key: String,
    },
    /// Update one or more mutable fields of a watch task.
    /// At least one flag is required.
    Update {
        /// task_id (UUID) or to_uri (viking:// URI)
        #[arg(value_name = "task-or-uri")]
        key: String,
        /// New refresh interval in minutes (must be > 0)
        #[arg(long, value_name = "minutes")]
        interval: Option<f64>,
        /// Set active (true) / paused (false) — alternative to pause/resume shortcuts
        #[arg(long, value_name = "bool")]
        active: Option<bool>,
        /// Human-readable reason for the watch task
        #[arg(long, value_name = "text")]
        reason: Option<String>,
        /// Processing instruction forwarded to the refresh handler
        #[arg(long, value_name = "text")]
        instruction: Option<String>,
    },
    /// Trigger an immediate refresh, bypassing the schedule
    Trigger {
        /// task_id (UUID) or to_uri (viking:// URI)
        #[arg(value_name = "task-or-uri")]
        key: String,
    },
}

#[derive(Subcommand)]
enum PrivacyCommands {
    /// List privacy config categories
    Categories,
    /// List all privacy targets and fields as a tree (current version, no values)
    Tree {
        /// Limit the tree to one category
        #[arg(long, value_name = "category")]
        category: Option<String>,
        /// Append the owner-bound reference for each field
        #[arg(long)]
        references: bool,
    },
    /// List targets by category
    List {
        /// Privacy config category
        #[arg(value_name = "category")]
        category: String,
    },
    /// Get current active config for target
    Get {
        /// Privacy config category
        #[arg(value_name = "category")]
        category: String,
        /// Privacy config target key
        #[arg(value_name = "target-key")]
        target_key: String,
    },
    /// Show an owner-bound reference for one active field without revealing its value
    Reference {
        /// Privacy config category
        #[arg(value_name = "category")]
        category: String,
        /// Privacy config target key
        #[arg(value_name = "target-key")]
        target_key: String,
        /// Field in the current values object
        #[arg(value_name = "field")]
        field: Option<String>,
    },
    /// Reveal one active field value for immediate use
    Resolve {
        /// Owner-bound reference, field URI, or privacy category
        #[arg(value_name = "reference-or-uri-or-category")]
        selector_or_category: String,
        /// Privacy config target key (category form only)
        #[arg(value_name = "target-key")]
        target_key: Option<String>,
        /// Field in current values (category form only)
        #[arg(value_name = "field")]
        field: Option<String>,
    },
    /// Upsert privacy config values
    Upsert {
        /// Privacy config category
        #[arg(value_name = "category")]
        category: String,
        /// Privacy config target key
        #[arg(value_name = "target-key")]
        target_key: String,
        /// JSON object string for values
        #[arg(long, conflicts_with = "values_file", value_name = "json")]
        values_json: Option<String>,
        /// JSON file path for values
        #[arg(
            long = "values-file",
            conflicts_with = "values_json",
            value_name = "path"
        )]
        values_file: Option<String>,
        /// Field updates in field=value format (repeatable; --key is a compatibility alias)
        #[arg(long = "field", alias = "key", value_name = "field=value")]
        field: Vec<String>,
        /// Change reason
        #[arg(long, default_value = "", value_name = "text")]
        change_reason: String,
        /// Optional labels JSON object string
        #[arg(long = "labels-json", value_name = "json")]
        labels_json: Option<String>,
    },
    /// List versions for target
    Versions {
        /// Privacy config category
        #[arg(value_name = "category")]
        category: String,
        /// Privacy config target key
        #[arg(value_name = "target-key")]
        target_key: String,
    },
    /// Get one version by number
    Version {
        /// Privacy config category
        #[arg(value_name = "category")]
        category: String,
        /// Privacy config target key
        #[arg(value_name = "target-key")]
        target_key: String,
        /// Version number
        #[arg(value_name = "version")]
        version: i32,
    },
    /// Activate a version
    Activate {
        /// Privacy config category
        #[arg(value_name = "category")]
        category: String,
        /// Privacy config target key
        #[arg(value_name = "target-key")]
        target_key: String,
        /// Version number
        #[arg(value_name = "version")]
        version: i32,
    },
    /// Delete a target or make one active field unavailable
    Delete {
        /// Privacy reference, URI, or config category
        #[arg(value_name = "reference-or-uri-or-category")]
        selector_or_category: String,
        /// Privacy config target key (category form only)
        #[arg(value_name = "target-key")]
        target_key: Option<String>,
        /// Field to remove from active values (optional)
        #[arg(value_name = "field")]
        field: Option<String>,
        /// Skip the confirmation prompt
        #[arg(long)]
        yes: bool,
    },
    /// Scan persisted content for registered Privacy values
    Scan {
        /// Exact viking:// file or directory to scan
        #[arg(long, value_name = "uri")]
        uri: String,
        /// Rewrite unambiguous matches and refresh derived indexes
        #[arg(long)]
        fix: bool,
        /// Maximum files/nodes enumerated per root
        #[arg(
            long,
            default_value_t = 1000,
            value_parser = clap::value_parser!(u16).range(1..=1000)
        )]
        node_limit: u16,
    },
}

#[derive(Subcommand)]
enum AdminCommands {
    /// Create a new account with its first admin user
    CreateAccount {
        /// Account ID to create
        #[arg(value_name = "account-id")]
        account_id: String,
        /// First admin user ID
        #[arg(long = "admin", value_name = "user-id")]
        admin_user_id: String,
        /// Deterministic API key seed
        #[arg(long, value_name = "seed")]
        seed: Option<String>,
        /// Initial config for the first admin user as JSON
        #[arg(long = "user-config-json", value_name = "json")]
        user_config_json: Option<String>,
    },
    /// List all accounts (ROOT only)
    ListAccounts {
        /// Filter accounts by ID (supports wildcard * and ?)
        #[arg(long, value_name = "pattern")]
        name: Option<String>,
        /// Page size; omit to list all accounts
        #[arg(long, value_name = "n")]
        limit: Option<u32>,
        /// 1-based page number (requires --limit)
        #[arg(long, default_value = "1", value_name = "n")]
        page: u32,
    },
    /// Delete an account and all associated users (ROOT only)
    DeleteAccount {
        /// Account ID to delete
        #[arg(value_name = "account-id")]
        account_id: String,
    },
    /// Register a new user in an account
    RegisterUser {
        /// Account ID
        #[arg(value_name = "account-id")]
        account_id: String,
        /// User ID to register
        #[arg(value_name = "user-id")]
        user_id: String,
        /// Role: admin or user
        #[arg(long, default_value = "user", value_name = "role")]
        role: String,
        /// Deterministic API key seed
        #[arg(long, value_name = "seed")]
        seed: Option<String>,
        /// Initial config for the new user as JSON
        #[arg(long = "user-config-json", value_name = "json")]
        user_config_json: Option<String>,
    },
    /// List all users in an account
    ListUsers {
        /// Account ID
        #[arg(value_name = "account-id")]
        account_id: String,
        /// Page size; omit to list all users
        #[arg(long, value_name = "n")]
        limit: Option<u32>,
        /// Filter users by name (supports wildcard * and ?)
        #[arg(long, value_name = "pattern")]
        name: Option<String>,
        /// Filter users by role
        #[arg(long, value_name = "role")]
        role: Option<String>,
        /// 1-based page number (requires --limit)
        #[arg(long, default_value = "1", value_name = "n")]
        page: u32,
        /// Show plaintext API keys instead of masked values (ROOT sees all keys; ADMIN/USER only its own)
        #[arg(long)]
        reveal_api_keys: bool,
    },
    /// Create an empty account-scoped group
    CreateGroup {
        #[arg(value_name = "account-id")]
        account_id: String,
        #[arg(value_name = "group-id")]
        group_id: String,
    },
    /// List groups in an account
    ListGroups {
        #[arg(value_name = "account-id")]
        account_id: String,
    },
    /// List the users in a group
    ListGroupMembers {
        #[arg(value_name = "account-id")]
        account_id: String,
        #[arg(value_name = "group-id")]
        group_id: String,
    },
    /// Add an existing account user to a group
    AddGroupMember {
        #[arg(value_name = "account-id")]
        account_id: String,
        #[arg(value_name = "group-id")]
        group_id: String,
        #[arg(value_name = "user-id")]
        user_id: String,
    },
    /// Remove a user from a group
    RemoveGroupMember {
        #[arg(value_name = "account-id")]
        account_id: String,
        #[arg(value_name = "group-id")]
        group_id: String,
        #[arg(value_name = "user-id")]
        user_id: String,
    },
    /// Delete an empty group
    DeleteGroup {
        #[arg(value_name = "account-id")]
        account_id: String,
        #[arg(value_name = "group-id")]
        group_id: String,
    },
    /// Remove a user from an account
    RemoveUser {
        /// Account ID
        #[arg(value_name = "account-id")]
        account_id: String,
        /// User ID to remove
        #[arg(value_name = "user-id")]
        user_id: String,
    },
    /// Change a user's role for identity management (ROOT or own-account ADMIN)
    SetRole {
        /// Account ID
        #[arg(value_name = "account-id")]
        account_id: String,
        /// User ID
        #[arg(value_name = "user-id")]
        user_id: String,
        /// New role: admin or user (case-insensitive)
        #[arg(value_name = "role")]
        role: String,
    },
    /// Regenerate a user's API key; self-rotation updates the active ovcli.conf
    RegenerateKey {
        /// Account ID
        #[arg(value_name = "account-id")]
        account_id: String,
        /// User ID
        #[arg(value_name = "user-id")]
        user_id: String,
        /// Deterministic API key seed
        #[arg(long, value_name = "seed")]
        seed: Option<String>,
    },
    /// Update allowlisted settings for an account
    SetAccountSettings {
        /// Account ID
        #[arg(value_name = "account-id")]
        account_id: String,
        /// Enable ACL authorization for shared resources
        #[arg(
            long,
            required = true,
            action = ArgAction::Set,
            value_name = "true|false"
        )]
        acl_enabled: bool,
    },
}

impl Commands {
    fn requires_cli_config_file(&self) -> bool {
        !matches!(
            self,
            Commands::Config {
                action: None
                    | Some(
                        ConfigCommands::Switch { .. }
                            | ConfigCommands::Add { .. }
                            | ConfigCommands::Edit(_)
                            | ConfigCommands::Delete(_)
                            | ConfigCommands::List,
                    ),
            } | Commands::Skills {
                action: SkillCommands::Validate { .. },
            } | Commands::Version
        )
    }

    fn allows_invalid_runtime_config(&self) -> bool {
        matches!(self, Commands::Config { .. })
    }
}

#[derive(Subcommand)]
enum ConfigCommands {
    /// Show current configuration
    Show,
    /// Validate configuration file
    Validate,
    /// Switch between saved configs
    Switch {
        /// Saved config name to activate. Omit to open the interactive selector.
        #[arg(value_name = "name")]
        name: Option<String>,
    },
    /// List saved configs
    List,
    /// Delete a saved config
    Delete(ConfigDeleteArgs),
    /// Add a saved config without opening the interactive wizard
    Add {
        #[command(subcommand)]
        target: ConfigAddTarget,
    },
    /// Edit a saved config without opening the interactive wizard
    Edit(ConfigEditArgs),
}

#[derive(Subcommand)]
enum ConfigAddTarget {
    /// Add an OpenViking Service config
    OvService(ConfigAddOvServiceArgs),
    /// Add a custom config
    Custom(ConfigAddCustomArgs),
}

#[derive(Args, Debug, Clone)]
struct ConfigAddOvServiceArgs {
    /// Saved config name. Agents should pass this for idempotent retries; generated when omitted.
    #[arg(long, value_name = "name", help_heading = "Common options")]
    name: Option<String>,
    /// Read API key from stdin
    #[arg(long, conflicts_with = "api_key_env", help_heading = "Common options")]
    api_key_stdin: bool,
    /// Read API key from an environment variable
    #[arg(
        long,
        conflicts_with = "api_key_stdin",
        value_name = "env",
        help_heading = "Common options"
    )]
    api_key_env: Option<String>,
    /// Account identifier to send as X-OpenViking-Account
    #[arg(long, value_name = "account", help_heading = "Advanced options")]
    account: Option<String>,
    /// User identifier to send as X-OpenViking-User
    #[arg(long, value_name = "user", help_heading = "Advanced options")]
    user: Option<String>,
    /// Peer actor scope to send as X-OpenViking-Actor-Peer
    #[arg(long = "actor-peer-id", hide = true)]
    actor_peer_id: Option<String>,
    /// Make the saved config active after validation
    #[arg(long, help_heading = "Common options")]
    activate: bool,
    /// Replace an existing saved config
    #[arg(long, help_heading = "Common options")]
    force: bool,
}

#[derive(Args, Debug, Clone)]
struct ConfigAddCustomArgs {
    /// Saved config name. Agents should pass this for idempotent retries; generated when omitted.
    #[arg(long, value_name = "name", help_heading = "Common options")]
    name: Option<String>,
    /// OpenViking server URL
    #[arg(long, value_name = "url", help_heading = "Common options")]
    url: Option<String>,
    /// Read API key from stdin
    #[arg(
        long,
        conflicts_with_all = ["api_key_env", "root_api_key_stdin"],
        help_heading = "Common options"
    )]
    api_key_stdin: bool,
    /// Read API key from an environment variable
    #[arg(
        long,
        conflicts_with = "api_key_stdin",
        value_name = "env",
        help_heading = "Common options"
    )]
    api_key_env: Option<String>,
    /// Read root API key from stdin
    #[arg(
        long,
        conflicts_with_all = ["root_api_key_env", "api_key_stdin"],
        help_heading = "Common options"
    )]
    root_api_key_stdin: bool,
    /// Read root API key from an environment variable
    #[arg(
        long,
        conflicts_with = "root_api_key_stdin",
        value_name = "env",
        help_heading = "Common options"
    )]
    root_api_key_env: Option<String>,
    /// Account identifier to send as X-OpenViking-Account
    #[arg(long, value_name = "account", help_heading = "Advanced options")]
    account: Option<String>,
    /// User identifier to send as X-OpenViking-User
    #[arg(long, value_name = "user", help_heading = "Advanced options")]
    user: Option<String>,
    /// Peer actor scope to send as X-OpenViking-Actor-Peer
    #[arg(long = "actor-peer-id", hide = true)]
    actor_peer_id: Option<String>,
    /// Make the saved config active after validation
    #[arg(long, help_heading = "Common options")]
    activate: bool,
    /// Replace an existing saved config
    #[arg(long, help_heading = "Common options")]
    force: bool,
}

#[derive(Args, Debug, Clone)]
struct ConfigEditArgs {
    /// Saved config name to edit
    #[arg(value_name = "name")]
    name: String,
    /// Rename the saved config
    #[arg(long, value_name = "name", help_heading = "Common options")]
    new_name: Option<String>,
    /// New server URL. OpenViking Service configs use a fixed URL.
    #[arg(long, value_name = "url", help_heading = "Common options")]
    url: Option<String>,
    /// Read replacement API key from stdin
    #[arg(
        long,
        conflicts_with_all = ["api_key_env", "clear_api_key", "root_api_key_stdin"],
        help_heading = "Common options"
    )]
    api_key_stdin: bool,
    /// Read replacement API key from an environment variable
    #[arg(
        long,
        conflicts_with_all = ["api_key_stdin", "clear_api_key"],
        value_name = "env",
        help_heading = "Common options"
    )]
    api_key_env: Option<String>,
    /// Remove the API key
    #[arg(
        long,
        conflicts_with_all = ["api_key_stdin", "api_key_env"],
        help_heading = "Common options"
    )]
    clear_api_key: bool,
    /// Read replacement root API key from stdin
    #[arg(
        long,
        conflicts_with_all = ["root_api_key_env", "clear_root_api_key", "api_key_stdin"],
        help_heading = "Common options"
    )]
    root_api_key_stdin: bool,
    /// Read replacement root API key from an environment variable
    #[arg(
        long,
        conflicts_with_all = ["root_api_key_stdin", "clear_root_api_key"],
        value_name = "env",
        help_heading = "Common options"
    )]
    root_api_key_env: Option<String>,
    /// Remove the root API key
    #[arg(
        long,
        conflicts_with_all = ["root_api_key_stdin", "root_api_key_env"],
        help_heading = "Common options"
    )]
    clear_root_api_key: bool,
    /// Account identifier to send as X-OpenViking-Account
    #[arg(long, value_name = "account", help_heading = "Advanced options")]
    account: Option<String>,
    /// User identifier to send as X-OpenViking-User
    #[arg(long, value_name = "user", help_heading = "Advanced options")]
    user: Option<String>,
    /// Peer actor scope to send as X-OpenViking-Actor-Peer
    #[arg(
        long = "actor-peer-id",
        hide = true,
        conflicts_with = "clear_actor_peer_id"
    )]
    actor_peer_id: Option<String>,
    /// Remove the peer actor scope
    #[arg(
        long = "clear-actor-peer-id",
        hide = true,
        conflicts_with = "actor_peer_id"
    )]
    clear_actor_peer_id: bool,
    /// Make the saved config active after validation
    #[arg(long, help_heading = "Common options")]
    activate: bool,
    /// Replace an existing saved config when renaming
    #[arg(long, help_heading = "Common options")]
    force: bool,
}

#[derive(Args, Debug, Clone)]
struct ConfigDeleteArgs {
    /// Saved config name to delete
    #[arg(value_name = "name")]
    name: String,
    /// Delete even when the saved config file cannot be parsed
    #[arg(long, help_heading = "Common options")]
    force: bool,
}

fn find_command_index(args: &[OsString]) -> Option<usize> {
    let root_value_options = cli_root_value_options();
    let mut i = 1;
    while i < args.len() {
        let token = args[i].to_string_lossy();
        let token_ref = token.as_ref();

        if token_ref == "--compact" || token_ref == "-c" {
            i += compact_option_width(args, i);
            continue;
        }
        if token_ref.starts_with('-') {
            i += if root_value_options.consumes_value(token_ref) && !token_ref.contains('=') {
                2
            } else {
                1
            };
            continue;
        }

        return Some(i);
    }
    None
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct PlainHelpMisuse {
    help_command: String,
}

fn plain_help_misuse(args: &[OsString]) -> Option<PlainHelpMisuse> {
    let tokens = command_tokens_for_plain_help(args);
    let help_index = tokens.iter().position(|token| token == "help")?;
    if help_index == 0 {
        return Some(PlainHelpMisuse {
            help_command: "ov --help".to_string(),
        });
    }

    let command = tokens
        .first()
        .map(|token| canonical_plain_help_token(token))?;
    if allows_plain_help_as_user_input(command) {
        return None;
    }

    let mut path = vec![command.to_string()];
    if is_plain_help_group(command) {
        if help_index == 1 {
            return Some(PlainHelpMisuse {
                help_command: prefixed_help_command(&path),
            });
        }
        if let Some(subcommand) = tokens.get(1).map(|token| canonical_plain_help_token(token)) {
            path.push(subcommand.to_string());
        }
        if command == "task"
            && path.get(1).is_some_and(|token| token == "watch")
            && let Some(watch_subcommand) =
                tokens.get(2).map(|token| canonical_plain_help_token(token))
            && watch_subcommand != "help"
        {
            path.push(watch_subcommand.to_string());
        }
        return Some(PlainHelpMisuse {
            help_command: prefixed_help_command(&path),
        });
    }

    Some(PlainHelpMisuse {
        help_command: prefixed_help_command(&path),
    })
}

fn command_tokens_for_plain_help(args: &[OsString]) -> Vec<String> {
    let value_options = cli_value_options();

    let mut tokens = Vec::new();
    let mut i = 1;
    while i < args.len() {
        let token = args[i].to_string_lossy();
        let token_ref = token.as_ref();
        if value_options.consumes_value(token_ref) {
            i += if token_ref.contains('=') { 1 } else { 2 };
            continue;
        }
        if token_ref.starts_with('-') {
            i += 1;
            continue;
        }
        tokens.push(token.into_owned());
        i += 1;
    }
    tokens
}

fn cli_value_options() -> cli_arg_scan::ValueOptions {
    let mut command = Cli::command();
    command.build();
    cli_arg_scan::ValueOptions::from_command(&command)
}

fn cli_root_value_options() -> cli_arg_scan::ValueOptions {
    let mut command = Cli::command();
    command.build();
    cli_arg_scan::ValueOptions::from_command_arguments(&command)
}

fn canonical_plain_help_token(token: &str) -> &str {
    match token {
        "list" => "ls",
        "del" | "delete" => "rm",
        "rename" => "mv",
        "lang" => "language",
        other => other,
    }
}

fn allows_plain_help_as_user_input(command: &str) -> bool {
    matches!(
        command,
        "add-resource" | "add-skill" | "find" | "search" | "grep" | "glob" | "add-memory"
    )
}

fn is_plain_help_group(command: &str) -> bool {
    matches!(
        command,
        "config" | "task" | "admin" | "system" | "session" | "privacy" | "observer" | "skills"
    )
}

fn prefixed_help_command(path: &[String]) -> String {
    if path.is_empty() {
        "ov --help".to_string()
    } else {
        format!("ov {} --help", path.join(" "))
    }
}

fn pre_parse_requires_cli_config_file(args: &[OsString]) -> bool {
    let tokens = command_tokens_for_config_gate(args);
    let Some(command) = tokens
        .first()
        .map(|token| canonical_plain_help_token(token))
    else {
        return false;
    };

    match command {
        "config" => config_command_requires_cli_config_file(&tokens),
        "language" | "version" => false,
        "task" => known_task_command_requires_config(&tokens),
        "admin" => tokens
            .get(1)
            .map(|token| is_admin_subcommand(token))
            .unwrap_or(false),
        "system" => known_system_command_requires_config(&tokens),
        "session" => tokens
            .get(1)
            .map(|token| is_session_subcommand(token))
            .unwrap_or(false),
        "privacy" => tokens
            .get(1)
            .map(|token| is_privacy_subcommand(token))
            .unwrap_or(false),
        "skills" => tokens
            .get(1)
            .map(|token| is_skill_subcommand(token))
            .unwrap_or(false),
        "observer" => tokens
            .get(1)
            .map(|token| is_observer_subcommand(token))
            .unwrap_or(false),
        _ => is_top_level_server_command(command),
    }
}

fn config_command_requires_cli_config_file(tokens: &[String]) -> bool {
    matches!(tokens.get(1).map(String::as_str), Some("show" | "validate"))
}

fn is_config_agent_command_request(args: &[OsString]) -> bool {
    let tokens = command_tokens_for_config_gate(args);
    if tokens.first().map(String::as_str) != Some("config") {
        return false;
    }

    match tokens.get(1).map(String::as_str) {
        Some("add" | "edit" | "delete" | "list") => true,
        Some("switch") => tokens.get(2).is_some(),
        _ => false,
    }
}

fn command_tokens_for_config_gate(args: &[OsString]) -> Vec<String> {
    let value_options = cli_value_options();
    let root_value_options = cli_root_value_options();
    let mut tokens = Vec::new();
    let mut seen_command = false;
    let mut i = 1;

    while i < args.len() {
        let token = args[i].to_string_lossy();
        let token_ref = token.as_ref();

        if token_ref == "--" {
            tokens.extend(
                args.iter()
                    .skip(i + 1)
                    .map(|arg| arg.to_string_lossy().to_string()),
            );
            break;
        }

        if !seen_command {
            if token_ref == "--compact" || token_ref == "-c" {
                i += compact_option_width(args, i);
                continue;
            }
            if token_ref.starts_with("--") {
                i += if root_value_options.consumes_value(token_ref) && !token_ref.contains('=') {
                    2
                } else {
                    1
                };
                continue;
            }
            if token_ref.starts_with('-') {
                i += if root_value_options.consumes_value(token_ref) && !token_ref.contains('=') {
                    2
                } else {
                    1
                };
                continue;
            }
            seen_command = true;
            tokens.push(token.into_owned());
            i += 1;
            continue;
        }

        if token_ref == "--compact" || token_ref == "-c" {
            i += compact_option_width(args, i);
            continue;
        }
        if value_options.consumes_value(token_ref) {
            i += if token_ref.contains('=') { 1 } else { 2 };
            continue;
        }
        if token_ref.starts_with('-') {
            i += 1;
            continue;
        }
        tokens.push(token.into_owned());
        i += 1;
    }

    tokens
}

fn known_task_command_requires_config(tokens: &[String]) -> bool {
    match tokens.get(1).map(String::as_str) {
        Some("status" | "cancel" | "list") => true,
        Some("watch") => match tokens.get(2).map(String::as_str) {
            None => true,
            Some(token) => is_watch_subcommand(token),
        },
        _ => false,
    }
}

fn known_system_command_requires_config(tokens: &[String]) -> bool {
    match tokens.get(1).map(String::as_str) {
        Some("wait" | "status" | "health" | "consistency") => true,
        Some("crypto") => matches!(tokens.get(2).map(String::as_str), None | Some("init-key")),
        _ => false,
    }
}

fn is_top_level_server_command(command: &str) -> bool {
    matches!(
        command,
        "add-resource"
            | "add-skill"
            | "ls"
            | "tree"
            | "mkdir"
            | "rm"
            | "mv"
            | "stat"
            | "read"
            | "abstract"
            | "overview"
            | "write"
            | "get"
            | "find"
            | "search"
            | "grep"
            | "glob"
            | "add-memory"
            | "export"
            | "backup"
            | "import"
            | "restore"
            | "tui"
            | "chat"
            | "wait"
            | "status"
            | "health"
            | "reindex"
    )
}

fn is_watch_subcommand(token: &str) -> bool {
    matches!(
        token,
        "ls" | "show" | "rm" | "pause" | "resume" | "update" | "trigger"
    )
}

fn is_skill_subcommand(token: &str) -> bool {
    matches!(
        token,
        "add" | "list" | "ls" | "find" | "show" | "update" | "remove" | "rm" | "delete"
    )
}

fn is_admin_subcommand(token: &str) -> bool {
    matches!(
        token,
        "create-account"
            | "list-accounts"
            | "delete-account"
            | "register-user"
            | "list-users"
            | "create-group"
            | "list-groups"
            | "list-group-members"
            | "add-group-member"
            | "remove-group-member"
            | "delete-group"
            | "remove-user"
            | "set-role"
            | "regenerate-key"
            | "set-account-settings"
    )
}

fn is_observer_subcommand(token: &str) -> bool {
    matches!(
        token,
        "queue" | "vikingdb" | "models" | "transaction" | "retrieval" | "filesystem" | "system"
    )
}

fn is_session_subcommand(token: &str) -> bool {
    matches!(
        token,
        "new"
            | "list"
            | "get"
            | "get-session-context"
            | "get-session-archive"
            | "delete"
            | "add-message"
            | "add-messages"
            | "commit"
    )
}

fn is_privacy_subcommand(token: &str) -> bool {
    matches!(
        token,
        "categories"
            | "tree"
            | "list"
            | "get"
            | "reference"
            | "resolve"
            | "upsert"
            | "versions"
            | "version"
            | "activate"
            | "delete"
            | "scan"
    )
}

fn preprocess_privacy_get_shortcut(args: Vec<OsString>) -> Vec<OsString> {
    let Some(cmd_idx) = find_command_index(&args) else {
        return args;
    };
    if args[cmd_idx].to_string_lossy() != "privacy" {
        return args;
    }
    let Some(next) = args.get(cmd_idx + 1) else {
        return args;
    };
    let next_token = next.to_string_lossy();
    if next_token.starts_with('-') || is_privacy_subcommand(&next_token) {
        return args;
    }

    let mut out = Vec::with_capacity(args.len() + 1);
    out.extend(args[..=cmd_idx].iter().cloned());
    out.push(OsString::from("get"));
    out.extend(args[cmd_idx + 1..].iter().cloned());
    out
}

fn preprocess_privacy_upsert_field_flags(args: Vec<OsString>) -> Vec<OsString> {
    let Some(cmd_idx) = find_command_index(&args) else {
        return args;
    };
    if args[cmd_idx].to_string_lossy() != "privacy" {
        return args;
    }
    if args
        .get(cmd_idx + 1)
        .map(|s| s.to_string_lossy().to_string())
        != Some("upsert".to_string())
    {
        return args;
    }

    let mut converted: Vec<OsString> = Vec::with_capacity(args.len());
    let mut i = 0;

    while i < args.len() {
        let arg_lossy = args[i].to_string_lossy();

        if i > cmd_idx + 1 && arg_lossy == "--" {
            i += 1;
            continue;
        }

        let dynamic_field = arg_lossy
            .strip_prefix("--field-")
            .or_else(|| arg_lossy.strip_prefix("--key-"));
        if i > cmd_idx + 1 && dynamic_field.is_some() {
            let suffix = dynamic_field.expect("checked above");
            if suffix.is_empty() {
                converted.push(args[i].clone());
                i += 1;
                continue;
            }

            if let Some((key, value)) = suffix.split_once('=') {
                converted.push(OsString::from("--field"));
                converted.push(OsString::from(format!("{}={}", key, value)));
                i += 1;
                continue;
            }

            if i + 1 < args.len() {
                let next_val = args[i + 1].to_string_lossy();
                converted.push(OsString::from("--field"));
                converted.push(OsString::from(format!("{}={}", suffix, next_val)));
                i += 2;
                continue;
            }

            converted.push(args[i].clone());
            i += 1;
            continue;
        }

        converted.push(args[i].clone());
        i += 1;
    }

    converted
}

fn preprocess_compact_args(args: Vec<OsString>) -> Vec<OsString> {
    if args.is_empty() {
        return args;
    }

    let mut converted = Vec::with_capacity(args.len());
    converted.push(args[0].clone());
    let mut i = 1;

    while i < args.len() {
        let token = args[i].to_string_lossy();
        if token == "--compact" || token == "-c" {
            if let Some(next) = args.get(i + 1) {
                let next_value = next.to_string_lossy();
                if is_bool_arg(&next_value) {
                    converted.push(OsString::from(format!("--compact={next_value}")));
                    i += 2;
                    continue;
                }
            }
            converted.push(OsString::from("--compact=true"));
            i += 1;
            continue;
        }

        converted.push(args[i].clone());
        i += 1;
    }

    converted
}

fn preprocess_cli_args(args: Vec<OsString>) -> Vec<OsString> {
    let args = preprocess_compact_args(args);
    preprocess_privacy_args(args)
}

fn pre_parse_output_options(args: &[OsString]) -> (OutputFormat, bool) {
    let Ok(matches) = Cli::command()
        .ignore_errors(true)
        .try_get_matches_from(args)
    else {
        return (OutputFormat::Table, true);
    };
    (
        matches
            .get_one::<OutputFormat>("output")
            .copied()
            .unwrap_or(OutputFormat::Table),
        matches.get_one::<bool>("compact").copied().unwrap_or(true),
    )
}

fn preprocess_privacy_args(args: Vec<OsString>) -> Vec<OsString> {
    let args = preprocess_privacy_get_shortcut(args);
    preprocess_privacy_upsert_field_flags(args)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LanguageGateAction {
    Continue,
    Prompt,
    ExitNonInteractive,
}

fn language_gate_action(
    args: &[OsString],
    has_saved_language: bool,
    is_interactive: bool,
) -> LanguageGateAction {
    if has_saved_language
        || is_language_command_request(args)
        || is_config_agent_command_request(args)
    {
        LanguageGateAction::Continue
    } else if is_interactive {
        LanguageGateAction::Prompt
    } else {
        LanguageGateAction::ExitNonInteractive
    }
}

async fn ensure_language_selected_before_command(args: &[OsString]) -> Result<bool> {
    match language_gate_action(
        args,
        i18n::has_saved_language(),
        io::stdin().is_terminal() && io::stdout().is_terminal(),
    ) {
        LanguageGateAction::Continue => Ok(true),
        LanguageGateAction::Prompt => {
            handlers::handle_language(None).await?;
            Ok(i18n::has_saved_language())
        }
        LanguageGateAction::ExitNonInteractive => {
            eprintln!("{}", language_required_message());
            std::process::exit(2);
        }
    }
}

fn is_language_command_request(args: &[OsString]) -> bool {
    matches!(
        first_command_token(args).as_deref(),
        Some("language" | "lang")
    )
}

fn first_command_token(args: &[OsString]) -> Option<String> {
    let root_value_options = cli_root_value_options();
    let mut index = 1usize;

    while index < args.len() {
        let token = args[index].to_string_lossy();
        if token == "--" {
            return args
                .get(index + 1)
                .map(|value| value.to_string_lossy().to_string());
        }
        if token == "--compact" || token == "-c" {
            index += compact_option_width(args, index);
            continue;
        }
        if token.starts_with("--") {
            index += if root_value_options.consumes_value(&token) && !token.contains('=') {
                2
            } else {
                1
            };
            continue;
        }
        if token.starts_with('-') {
            index += if root_value_options.consumes_value(&token) && !token.contains('=') {
                2
            } else {
                1
            };
            continue;
        }
        return Some(token.to_string());
    }

    None
}

fn compact_option_width(args: &[OsString], index: usize) -> usize {
    if args
        .get(index + 1)
        .is_some_and(|value| is_bool_arg(&value.to_string_lossy()))
    {
        2
    } else {
        1
    }
}

fn is_bool_arg(value: &str) -> bool {
    matches!(
        value,
        "true" | "false" | "True" | "False" | "TRUE" | "FALSE"
    )
}

fn language_required_message() -> String {
    format!(
        "{} {}\n{}:\n  {}\n  {}",
        theme::brand_title("OpenViking").bold(),
        theme::body("needs a display language before running commands."),
        theme::strong("Run one of"),
        theme::command("ov language en").bold(),
        theme::command("ov language zh-CN").bold(),
    )
}

fn language_command_can_run_picker(has_language_value: bool, is_interactive: bool) -> bool {
    has_language_value || is_interactive
}

fn resolve_output_format(cli_output: Option<OutputFormat>, config: &Config) -> OutputFormat {
    cli_output.unwrap_or_else(|| OutputFormat::from(config.output.as_str()))
}

fn render_pre_language_help_request(args: &[OsString]) -> Option<String> {
    if !args
        .iter()
        .skip(1)
        .any(|arg| matches!(arg.to_str(), Some("-h" | "--help")))
    {
        return None;
    }

    let error = Cli::try_parse_from(args).err()?;
    if error.kind() != clap::error::ErrorKind::DisplayHelp {
        return None;
    }

    if help_ui::is_top_level_help_request(args) {
        return Some(help_ui::render_top_level_help());
    }
    help_ui::render_command_help_request(args).or_else(|| Some(error.to_string()))
}

#[tokio::main]
async fn main() {
    let args = preprocess_cli_args(std::env::args_os().collect());
    let command_display = error_ui::display_command(&args);
    let (pre_parse_output_format, pre_parse_compact) = pre_parse_output_options(&args);
    if let Some(help) = render_pre_language_help_request(&args) {
        print!("{help}");
        return;
    }
    match ensure_language_selected_before_command(&args).await {
        Ok(true) => {}
        Ok(false) => return,
        Err(e) => {
            error_ui::print_runtime_error(
                &command_display,
                &e,
                pre_parse_output_format,
                pre_parse_compact,
                false,
            );
            std::process::exit(2);
        }
    }

    if help_ui::is_top_level_help_request(&args) {
        print!("{}", help_ui::render_top_level_help());
        return;
    }
    if let Some(help) = help_ui::render_command_help_request(&args) {
        print!("{help}");
        return;
    }
    if let Some(misuse) = plain_help_misuse(&args) {
        let report = error_ui::report_for_plain_help_error(&command_display, misuse.help_command);
        error_ui::print_report(&report, false);
        std::process::exit(2);
    }

    let mut preloaded_required_config = if pre_parse_requires_cli_config_file(&args) {
        match Config::load_required() {
            Ok(config) => Some(config),
            Err(e) => {
                error_ui::print_runtime_error(
                    &command_display,
                    &e,
                    pre_parse_output_format,
                    pre_parse_compact,
                    false,
                );
                std::process::exit(2);
            }
        }
    } else {
        None
    };

    let cli = match Cli::try_parse_from(args.clone()) {
        Ok(cli) => cli,
        Err(error) => {
            if error.exit_code() == 0 {
                let _ = error.print();
            } else {
                let report = error_ui::report_for_clap_error(&args, &error.to_string());
                error_ui::print_report(&report, false);
            }
            std::process::exit(error.exit_code());
        }
    };

    let output_override = cli.output;
    let compact = cli.compact;
    let legacy_upload_options = UploadCliOptions {
        progress: cli.progress,
        no_progress: cli.no_progress,
        verbose: cli.verbose,
    };
    if let Some(message) = legacy_upload_option_error(legacy_upload_options, &cli.command) {
        let report = error_ui::report_for_message_error(
            &command_display,
            "Command Error",
            message,
            vec![
                error_ui::ErrorAction::new("ov add-resource --help", "Show add-resource options"),
                error_ui::ErrorAction::new("ov add-skill --help", "Show add-skill options"),
            ],
        );
        error_ui::print_report(&report, false);
        std::process::exit(2);
    }

    // Check this before loading config so misplaced --sudo reports the command rule directly.
    if cli.sudo && !cli.command.supports_sudo() {
        let language = i18n::Language::current();
        let (title, message, actions) = match language {
            i18n::Language::En => (
                "Command Error",
                "--sudo is only supported for admin, system, reindex, task status, and task list commands.",
                vec![
                    error_ui::ErrorAction::new("ov admin --help", "Show admin commands"),
                    error_ui::ErrorAction::new("ov system --help", "Show system commands"),
                    error_ui::ErrorAction::new("ov reindex --help", "Show reindex options"),
                    error_ui::ErrorAction::new("ov task --help", "Show task commands"),
                ],
            ),
            i18n::Language::ZhCn => (
                "命令错误",
                "--sudo 只支持 admin、system、reindex、task status 和 task list 命令。",
                vec![
                    error_ui::ErrorAction::new("ov admin --help", "查看管理命令"),
                    error_ui::ErrorAction::new("ov system --help", "查看系统命令"),
                    error_ui::ErrorAction::new("ov reindex --help", "查看重建索引选项"),
                    error_ui::ErrorAction::new("ov task --help", "查看任务命令"),
                ],
            ),
        };
        let report = error_ui::report_for_message_error(&command_display, title, message, actions);
        error_ui::print_report(&report, false);
        std::process::exit(2);
    }

    if let Commands::Language { language } = &cli.command {
        if !language_command_can_run_picker(
            language.is_some(),
            io::stdin().is_terminal() && io::stdout().is_terminal(),
        ) {
            eprintln!("{}", language_required_message());
            std::process::exit(2);
        }
        if let Err(e) = handlers::handle_language(language.clone()).await {
            error_ui::print_runtime_error(
                &command_display,
                &e,
                pre_parse_output_format,
                compact,
                cli.verbose,
            );
            std::process::exit(2);
        }
        return;
    }

    let config_result = if cli.command.requires_cli_config_file() {
        match preloaded_required_config.take() {
            Some(config) => Ok(config),
            None => Config::load_required(),
        }
    } else {
        Config::load_default()
    };
    let config = match config_result {
        Ok(config) => config,
        Err(e) => {
            error_ui::print_runtime_error(
                &command_display,
                &e,
                pre_parse_output_format,
                compact,
                cli.verbose,
            );
            std::process::exit(2);
        }
    };
    let output_format = resolve_output_format(output_override, &config);
    if !cli.command.allows_invalid_runtime_config()
        && let Err(e) = config.validate_runtime_values()
    {
        error_ui::print_runtime_error(&command_display, &e, output_format, compact, cli.verbose);
        std::process::exit(2);
    }
    let ctx = CliContext::from_config(
        config,
        output_format,
        compact,
        cli.account.clone(),
        cli.user.clone(),
        cli.actor_peer_id.clone(),
        cli.sudo,
        None,
        None,
        if cli.profile { Some(true) } else { None },
    );
    let verbose_errors = ctx.is_verbose();

    // Check if --sudo is used but root_api_key is not configured
    if ctx.sudo && ctx.config.root_api_key.is_none() {
        let language = i18n::Language::current();
        let (title, message, actions) = match language {
            i18n::Language::En => (
                "Configuration Error",
                "--sudo requires root_api_key in ~/.openviking/ovcli.conf.",
                vec![
                    error_ui::ErrorAction::new("ov config", "Edit the active config"),
                    error_ui::ErrorAction::new("ov config show", "Show the active config"),
                ],
            ),
            i18n::Language::ZhCn => (
                "配置错误",
                "--sudo 需要在 ~/.openviking/ovcli.conf 中配置 root_api_key。",
                vec![
                    error_ui::ErrorAction::new("ov config", "编辑当前配置"),
                    error_ui::ErrorAction::new("ov config show", "显示当前配置"),
                ],
            ),
        };
        let report = error_ui::report_for_message_error(&command_display, title, message, actions);
        error_ui::print_report(&report, false);
        std::process::exit(2);
    };

    let result = match cli.command {
        Commands::AddResource {
            path,
            add_type,
            manifest,
            to,
            parent,
            parent_auto_create,
            reason,
            instruction,
            wait,
            tags,
            tag_mode,
            acl,
            strict_mode,
            ignore_dirs,
            include,
            exclude,
            no_directly_upload_media,
            watch_interval,
            processing_mode,
            resource_args,
            upload_options,
        } => {
            let ctx =
                ctx.with_upload_options(upload_options.merged_with_legacy(legacy_upload_options));
            if let Some(manifest) = manifest {
                match handlers::parse_add_resource_args(resource_args.as_deref())
                    .and_then(|args| openviking_assets::parse_manifest_run_args(args.as_ref()))
                {
                    Err(e) => Err(e),
                    Ok(run) => {
                        openviking_assets::handle_manifest_apply(
                            manifest,
                            run.catalog,
                            openviking_assets::ManifestRunOptions {
                                dry_run: run.dry_run,
                                skip_failed: run.skip_failed,
                                wait,
                                watch_interval,
                                processing_mode,
                                external_connector: run.external_connector,
                            },
                            ctx,
                        )
                        .await
                    }
                }
            } else if let Some(path) = path {
                handlers::handle_add_resource(
                    path,
                    add_type,
                    to,
                    parent,
                    parent_auto_create,
                    reason,
                    instruction,
                    wait,
                    strict_mode,
                    ignore_dirs,
                    include,
                    exclude,
                    no_directly_upload_media,
                    watch_interval.unwrap_or(0.0),
                    processing_mode,
                    resource_args,
                    tags,
                    tag_mode,
                    acl,
                    ctx,
                )
                .await
            } else {
                Err(error::Error::Client(
                    "a path/URL or --manifest is required".to_string(),
                ))
            }
        }
        Commands::AddSkill(args) => {
            handlers::handle_add_skill(args, legacy_upload_options, ctx).await
        }
        Commands::Skills { action } => match action {
            SkillCommands::Add(args) => {
                handlers::handle_add_skill(args, legacy_upload_options, ctx).await
            }
            SkillCommands::List { node_limit, parent } => {
                let client = ctx.get_client();
                commands::skills::list(
                    &client,
                    node_limit,
                    ctx.output_format,
                    ctx.compact,
                    parent.as_deref(),
                )
                .await
            }
            SkillCommands::Find {
                query,
                node_limit,
                threshold,
                level,
                parent,
            } => {
                let client = ctx.get_client();
                commands::skills::find(
                    &client,
                    &query,
                    node_limit,
                    threshold,
                    level,
                    ctx.output_format,
                    ctx.compact,
                    parent.as_deref(),
                )
                .await
            }
            SkillCommands::Show {
                name,
                level,
                files,
                source,
                format,
                content,
                parent,
            } => {
                let client = ctx.get_client();
                let output_format = format
                    .as_deref()
                    .map(OutputFormat::from)
                    .unwrap_or(ctx.output_format);
                let level = if content { Some(2) } else { level };
                commands::skills::show(
                    &client,
                    &name,
                    level,
                    files,
                    source,
                    output_format,
                    ctx.compact,
                    parent.as_deref(),
                )
                .await
            }
            SkillCommands::Update {
                skills,
                wait,
                yes,
                parent,
            } => {
                let client = ctx.get_client();
                commands::skills::update(
                    &client,
                    skills,
                    wait,
                    yes,
                    ctx.output_format,
                    ctx.compact,
                    parent.as_deref(),
                )
                .await
            }
            SkillCommands::Remove {
                skills,
                all,
                yes,
                parent,
            } => {
                let client = ctx.get_client();
                commands::skills::remove(
                    &client,
                    skills,
                    all,
                    yes,
                    ctx.output_format,
                    ctx.compact,
                    parent.as_deref(),
                )
                .await
            }
            SkillCommands::Validate { path, strict } => {
                let client = ctx.get_client();
                commands::skills::validate(&client, &path, strict, ctx.output_format, ctx.compact)
                    .await
            }
        },
        Commands::Export {
            uri,
            to,
            include_vectors,
        } => handlers::handle_export(uri, to, include_vectors, ctx).await,
        Commands::Backup {
            to,
            include_vectors,
        } => handlers::handle_backup(to, include_vectors, ctx).await,
        Commands::Import {
            file_path,
            target_uri,
            on_conflict,
            vector_mode,
        } => handlers::handle_import(file_path, target_uri, on_conflict, vector_mode, ctx).await,
        Commands::Restore {
            file_path,
            on_conflict,
            vector_mode,
        } => handlers::handle_restore(file_path, on_conflict, vector_mode, ctx).await,
        Commands::Wait => {
            let client = ctx.get_client();
            commands::system::wait(&client, ctx.output_format, ctx.compact).await
        }
        Commands::Task { action } => match action {
            TaskCommands::Status { task_id } => {
                let client = ctx.get_client();
                commands::task::status(&client, &task_id, ctx.output_format, ctx.compact).await
            }
            TaskCommands::Cancel { task_id } => {
                let client = ctx.get_client();
                commands::task::cancel(&client, &task_id, ctx.output_format, ctx.compact).await
            }
            TaskCommands::List { task_type, status } => {
                let client = ctx.get_client();
                commands::task::list(
                    &client,
                    task_type.as_deref(),
                    status.as_deref(),
                    ctx.output_format,
                    ctx.compact,
                )
                .await
            }
            TaskCommands::Watch { action } => {
                let client = ctx.get_client();
                match action {
                    WatchCommands::Ls { active_only } => {
                        commands::watch::ls(&client, active_only, ctx.output_format, ctx.compact)
                            .await
                    }
                    WatchCommands::Show { key } => {
                        commands::watch::show(&client, &key, ctx.output_format, ctx.compact).await
                    }
                    WatchCommands::Rm { key } => {
                        commands::watch::rm(&client, &key, ctx.output_format, ctx.compact).await
                    }
                    WatchCommands::Pause { key } => {
                        commands::watch::pause(&client, &key, ctx.output_format, ctx.compact).await
                    }
                    WatchCommands::Resume { key } => {
                        commands::watch::resume(&client, &key, ctx.output_format, ctx.compact).await
                    }
                    WatchCommands::Update {
                        key,
                        interval,
                        active,
                        reason,
                        instruction,
                    } => {
                        commands::watch::update(
                            &client,
                            &key,
                            interval,
                            active,
                            reason,
                            instruction,
                            ctx.output_format,
                            ctx.compact,
                        )
                        .await
                    }
                    WatchCommands::Trigger { key } => {
                        commands::watch::trigger(&client, &key, ctx.output_format, ctx.compact)
                            .await
                    }
                }
            }
        },
        Commands::Snapshot { cmd } => {
            let client = ctx.get_client();
            commands::snapshot::dispatch(&client, cmd, ctx.output_format, ctx.compact).await
        }
        Commands::Status { verbose } => {
            let client = ctx.get_client();
            commands::system::diagnostic_status(
                &client,
                &ctx.config,
                ctx.output_format,
                ctx.compact,
                verbose,
            )
            .await
        }
        Commands::Health => handlers::handle_health(ctx).await,
        Commands::System { action } => handlers::handle_system(action, ctx).await,
        Commands::Observer { action } => handlers::handle_observer(action, ctx).await,
        Commands::Session { action } => handlers::handle_session(action, ctx).await,
        Commands::Admin { action } => handlers::handle_admin(action, ctx).await,
        Commands::Privacy { action } => handlers::handle_privacy(*action, ctx).await,
        Commands::Ls {
            uri,
            simple,
            recursive,
            abs_limit,
            include_abstract,
            include_overview,
            overview_limit,
            all,
            node_limit,
            offset,
            limit,
            sort_by,
            sort_order,
            fields,
            tags,
        } => {
            handlers::handle_ls(
                uri,
                simple,
                recursive,
                abs_limit,
                include_abstract,
                include_overview,
                overview_limit,
                all,
                node_limit,
                offset,
                limit,
                sort_by,
                sort_order,
                fields,
                tags,
                ctx,
            )
            .await
        }
        Commands::Tree {
            uri,
            abs_limit,
            include_abstract,
            include_overview,
            overview_limit,
            all,
            directories_only,
            node_limit,
            offset,
            limit,
            level_limit,
            simple,
            fields,
            tags,
        } => {
            handlers::handle_tree(
                uri,
                abs_limit,
                include_abstract,
                include_overview,
                overview_limit,
                all,
                directories_only,
                node_limit,
                offset,
                limit,
                level_limit,
                simple,
                fields,
                tags,
                ctx,
            )
            .await
        }
        Commands::Mkdir {
            uri,
            description,
            acl,
        } => handlers::handle_mkdir(uri, description, acl, ctx).await,
        Commands::Rm {
            uri,
            recursive,
            wait,
        } => handlers::handle_rm(uri, recursive, wait, ctx).await,
        Commands::Cp {
            from_uri,
            to_uri,
            recursive,
        } => handlers::handle_cp(from_uri, to_uri, recursive, ctx).await,
        Commands::Mv { from_uri, to_uri } => handlers::handle_mv(from_uri, to_uri, ctx).await,
        Commands::Stat { uri } => handlers::handle_stat(uri, ctx).await,
        Commands::Attrs { action } => match action {
            AttrsCommands::Get { uri, key } => handlers::handle_attrs(uri, key, ctx).await,
            AttrsCommands::SetTags {
                uri,
                tags,
                mode,
                recursive,
            } => handlers::handle_set_tags(uri, tags, mode, recursive, ctx).await,
        },
        Commands::Acl { action } => handlers::handle_acl(action, ctx).await,
        Commands::AddMemory { content } => handlers::handle_add_memory(content, ctx).await,
        Commands::Tui { uri } => handlers::handle_tui(uri, ctx).await,
        Commands::Chat {
            message,
            session,
            sender,
            stream,
            no_format,
            no_history,
        } => {
            let session_id = session.or_else(|| config::get_or_create_machine_id().ok());
            let endpoint = if let Ok(env_endpoint) = std::env::var("VIKINGBOT_ENDPOINT") {
                Some(env_endpoint)
            } else if let Ok(config_url) = std::env::var("OPENVIKING_URL") {
                Some(format!("{}/bot/v1", config_url))
            } else {
                None
            };
            let api_key = std::env::var("VIKINGBOT_API_KEY").ok();
            let cmd = commands::chat::ChatCommand {
                endpoint,
                api_key,
                account: ctx.config.account.clone(),
                user: ctx.config.user.clone(),
                actor_peer_id: ctx.config.effective_actor_peer_id(),
                session: session_id,
                sender,
                message,
                stream,
                no_format,
                no_history,
            };
            cmd.run().await
        }
        Commands::Compile {
            from_uris,
            to,
            skill,
            instruction,
            args,
        } => {
            let client = ctx.get_client();
            commands::compile::run(
                &client,
                from_uris,
                to,
                skill,
                instruction,
                args,
                ctx.output_format,
                ctx.compact,
            )
            .await
        }
        Commands::Config { action } => handlers::handle_config(action, ctx).await,
        Commands::Language { .. } => unreachable!("language command is handled before config load"),
        Commands::Version => {
            println!(
                "{}     {}",
                theme::muted("CLI:"),
                theme::version(env!("OPENVIKING_CLI_VERSION")).bold()
            );

            // Try to get server version from /health endpoint with a short timeout (3 seconds)
            let client = ctx.get_client_with_timeout(Some(3.0));
            match client.get::<serde_json::Value>("/health", &[]).await {
                Ok(health) => {
                    if let Some(version) = health.get("version").and_then(|v| v.as_str()) {
                        println!(
                            "{}  {}",
                            theme::muted("Server:"),
                            theme::sky_value(version).bold()
                        );
                    }
                }
                Err(_) => {
                    // If can't connect to server, just don't print server version
                }
            }
            Ok(())
        }
        Commands::Read { uri, offset, limit } => {
            handlers::handle_read(uri, offset, limit, ctx).await
        }
        Commands::Abstract { uri } => handlers::handle_abstract(uri, ctx).await,
        Commands::Overview { uri } => handlers::handle_overview(uri, ctx).await,
        Commands::Write {
            uri,
            content,
            from_file,
            append,
            mode,
            wait,
            processing_mode,
            tags,
            tag_mode,
            acl,
            edit_source,
        } => {
            let effective_mode = if let Some(m) = mode {
                m
            } else if append {
                "append".to_string()
            } else {
                "replace".to_string()
            };
            handlers::handle_write(
                uri,
                content,
                from_file,
                effective_mode,
                wait,
                processing_mode,
                tags,
                tag_mode,
                acl,
                edit_source,
                ctx,
            )
            .await
        }
        Commands::SetTags {
            uri,
            tags,
            mode,
            recursive,
        } => handlers::handle_set_tags(uri, tags, mode, recursive, ctx).await,
        Commands::Reindex {
            uri,
            mode,
            wait,
            force,
            tags,
            tag_mode,
            recursive,
        } => {
            handlers::handle_reindex(uri, mode, wait, force, tags, tag_mode, recursive, ctx).await
        }
        Commands::Get { uri, local_path } => handlers::handle_get(uri, local_path, ctx).await,
        Commands::Find {
            query,
            image,
            uri,
            node_limit,
            threshold,
            after,
            before,
            level,
            context_type,
            tags,
            read_content,
            events_time_decay_protection,
        } => {
            handlers::handle_find(
                query,
                uri,
                image,
                node_limit,
                threshold,
                after,
                before,
                level,
                context_type,
                tags,
                read_content,
                events_time_decay_protection,
                ctx,
            )
            .await
        }
        Commands::Search {
            query,
            image,
            search_type,
            mode,
            uri,
            session_id,
            node_limit,
            threshold,
            after,
            before,
            level,
            context_type,
            tags,
            read_content,
            events_time_decay_protection,
        } => {
            handlers::handle_search(
                query,
                uri,
                image,
                search_type,
                mode,
                session_id,
                node_limit,
                threshold,
                after,
                before,
                level,
                context_type,
                tags,
                read_content,
                events_time_decay_protection,
                ctx,
            )
            .await
        }
        Commands::Grep {
            uri,
            exclude_uri,
            pattern,
            ignore_case,
            after_context,
            before_context,
            node_limit,
            level_limit,
            tags,
            fields,
        } => {
            handlers::handle_grep(
                uri,
                exclude_uri,
                pattern,
                ignore_case,
                after_context,
                before_context,
                node_limit,
                level_limit,
                tags,
                fields,
                ctx,
            )
            .await
        }

        Commands::Glob {
            pattern,
            uri,
            node_limit,
            simple,
            fields,
            tags,
        } => handlers::handle_glob(pattern, uri, node_limit, simple, fields, tags, ctx).await,
    };

    if let Err(e) = result {
        if e.code() == "INTERRUPTED" {
            if matches!(output_format, OutputFormat::Json) {
                error_ui::print_runtime_error(
                    &command_display,
                    &e,
                    output_format,
                    compact,
                    verbose_errors,
                );
            } else if let Error::Api { message, .. } = &e {
                eprintln!("{message}");
            }
            std::process::exit(130);
        }
        if !matches!(e, Error::AlreadyReported) {
            error_ui::print_runtime_error(
                &command_display,
                &e,
                output_format,
                compact,
                verbose_errors,
            );
        }
        std::process::exit(1);
    }
}

#[cfg(test)]
mod tests {
    use super::{
        Cli, CliContext, Commands, ConfigAddTarget, ConfigCommands, LanguageGateAction,
        ObserverCommands, PrivacyCommands, SkillCommands, SnapshotCmd, UploadCliOptions,
        find_command_index, first_command_token, is_language_command_request,
        language_command_can_run_picker, language_gate_action, language_required_message,
        legacy_upload_option_error, plain_help_misuse, pre_parse_output_options,
        pre_parse_requires_cli_config_file, preprocess_cli_args, preprocess_privacy_args,
        render_pre_language_help_request, resolve_output_format,
    };
    use crate::config::{Config, DEFAULT_CUSTOM_URL};
    use crate::handlers;
    use crate::output::OutputFormat;
    use clap::{CommandFactory, Parser};
    use std::ffi::OsString;

    fn os_args(args: &[&str]) -> Vec<OsString> {
        args.iter().map(OsString::from).collect()
    }

    #[test]
    fn cli_parses_global_identity_override_flags() {
        let cli = Cli::try_parse_from([
            "ov",
            "--account",
            "acme",
            "--user",
            "alice",
            "--actor-peer-id",
            "peer-a",
            "ls",
        ])
        .expect("cli should parse");

        assert_eq!(cli.account.as_deref(), Some("acme"));
        assert_eq!(cli.user.as_deref(), Some("alice"));
        assert_eq!(cli.actor_peer_id.as_deref(), Some("peer-a"));
    }

    #[test]
    fn cli_parses_copy_recursive_flag() {
        let file = Cli::try_parse_from([
            "ov",
            "cp",
            "viking://resources/a.md",
            "viking://resources/b.md",
        ])
        .expect("file copy should parse");
        match file.command {
            Commands::Cp {
                from_uri,
                to_uri,
                recursive,
            } => {
                assert_eq!(from_uri, "viking://resources/a.md");
                assert_eq!(to_uri, "viking://resources/b.md");
                assert!(!recursive);
            }
            _ => panic!("expected cp command"),
        }

        let directory = Cli::try_parse_from([
            "ov",
            "cp",
            "-r",
            "viking://resources/src",
            "viking://resources/dst",
        ])
        .expect("recursive directory copy should parse");
        match directory.command {
            Commands::Cp { recursive, .. } => assert!(recursive),
            _ => panic!("expected cp command"),
        }
    }

    #[test]
    fn cli_parses_snapshot_diff_refs() {
        let cli = Cli::try_parse_from([
            "ov",
            "snapshot",
            "diff",
            "viking://resources/a.md",
            "--from",
            "old",
            "--to",
            "new",
        ])
        .expect("snapshot diff should parse");

        match cli.command {
            Commands::Snapshot {
                cmd:
                    SnapshotCmd::Diff {
                        path,
                        from_ref,
                        to_ref,
                    },
            } => {
                assert_eq!(path, "viking://resources/a.md");
                assert_eq!(from_ref.as_deref(), Some("old"));
                assert_eq!(to_ref, "new");
            }
            _ => panic!("expected snapshot diff"),
        }
    }

    #[test]
    fn pre_parse_output_options_preserve_json_config_errors() {
        for args in [
            os_args(&["ov", "ls", "--output", "json", "--compact=false"]),
            os_args(&["ov", "ls", "-ojson"]),
            os_args(&["ov", "ls", "-o=json"]),
        ] {
            assert_eq!(pre_parse_output_options(&args).0, OutputFormat::Json);
        }
    }

    #[test]
    fn cli_parses_find_context_type() {
        let cli =
            Cli::try_parse_from(["ov", "find", "invoice", "--context-type", "memory,resource"])
                .expect("find context type should parse");

        match cli.command {
            Commands::Find { context_type, .. } => {
                assert_eq!(
                    context_type,
                    Some(vec!["memory".to_string(), "resource".to_string()])
                );
            }
            _ => panic!("expected find command"),
        }
    }

    #[test]
    fn cli_parses_find_image_without_query() {
        let cli = Cli::try_parse_from(["ov", "find", "--image", "cat.png"])
            .expect("find image should parse");

        match cli.command {
            Commands::Find { query, image, .. } => {
                assert_eq!(query, None);
                assert_eq!(image.as_deref(), Some("cat.png"));
            }
            _ => panic!("expected find command"),
        }
    }

    #[test]
    fn cli_parses_search_context_mode_and_type() {
        let cli = Cli::try_parse_from([
            "ov",
            "search",
            "invoice",
            "--mode",
            "context",
            "--context-type",
            "skill",
        ])
        .expect("search context mode and type should parse");

        match cli.command {
            Commands::Search {
                mode, context_type, ..
            } => {
                assert_eq!(mode, "context");
                assert_eq!(context_type, Some(vec!["skill".to_string()]));
            }
            _ => panic!("expected search command"),
        }
    }

    #[test]
    fn cli_parses_search_image_with_query() {
        let cli = Cli::try_parse_from(["ov", "search", "poster", "--image", "viking://x.png"])
            .expect("search image should parse");

        match cli.command {
            Commands::Search {
                query, image, mode, ..
            } => {
                assert_eq!(query.as_deref(), Some("poster"));
                assert_eq!(image.as_deref(), Some("viking://x.png"));
                assert_eq!(mode, "list");
            }
            _ => panic!("expected search command"),
        }
    }

    #[test]
    fn cli_parses_grep_context_lines() {
        let cli = Cli::try_parse_from([
            "ov",
            "grep",
            "--uri",
            "viking://resources",
            "-a",
            "2",
            "-b",
            "3",
            "needle",
        ])
        .expect("grep context should parse");

        match cli.command {
            Commands::Grep {
                after_context,
                before_context,
                ..
            } => {
                assert_eq!(after_context, 2);
                assert_eq!(before_context, 3);
            }
            _ => panic!("expected grep command"),
        }
    }

    #[test]
    fn cli_find_and_search_reject_removed_peer_id_flag() {
        assert!(Cli::try_parse_from(["ov", "find", "invoice", "--peer-id", "peer-a"]).is_err());
        assert!(Cli::try_parse_from(["ov", "search", "invoice", "--peer-id", "peer-a"]).is_err());
    }

    #[test]
    fn cli_chat_sender_uses_long_flag_and_session_keeps_short_s() {
        Cli::command().debug_assert();

        let cli = Cli::try_parse_from([
            "ov",
            "chat",
            "-s",
            "session-1",
            "--sender",
            "agent-1",
            "--message",
            "hello",
        ])
        .expect("chat flags should parse without short alias conflicts");

        match cli.command {
            Commands::Chat {
                session, sender, ..
            } => {
                assert_eq!(session.as_deref(), Some("session-1"));
                assert_eq!(sender, "agent-1");
            }
            _ => panic!("expected chat command"),
        }
    }

    #[test]
    fn cli_compile_requires_skill_and_expands_source_flags() {
        let cli = Cli::try_parse_from([
            "ov",
            "compile",
            "--from",
            "viking://resources/a,viking://resources/b",
            "--from",
            "viking://resources/c",
            "--to",
            "viking://resources/wiki",
            "--skill",
            "viking://agent/skills/wiki",
            "--instruction",
            "Keep supporting evidence.",
            "--args",
            r#"{"model_name":"endpoint-1"}"#,
        ])
        .expect("compile flags should parse");
        match cli.command {
            Commands::Compile {
                from_uris,
                skill,
                instruction,
                args,
                ..
            } => {
                assert_eq!(from_uris.len(), 3);
                assert_eq!(skill, "viking://agent/skills/wiki");
                assert_eq!(instruction.as_deref(), Some("Keep supporting evidence."));
                assert_eq!(args.as_deref(), Some(r#"{"model_name":"endpoint-1"}"#));
            }
            _ => panic!("expected compile command"),
        }

        assert!(
            Cli::try_parse_from([
                "ov",
                "compile",
                "--from",
                "viking://resources/a",
                "--to",
                "viking://resources/wiki",
            ])
            .is_err()
        );
    }

    #[test]
    fn cli_read_line_ranges() {
        for (args, expected_offset, expected_limit) in [
            (vec![], 0, -1),
            (vec!["--offset", "10", "--limit", "5"], 10, 5),
            (vec!["--offset", "10", "--limit", "-1"], 10, -1),
            (vec!["--limit", "0"], 0, 0),
            (vec!["--offset", "10"], 10, -1),
        ] {
            let mut argv = vec!["ov", "read", "viking://resources/example.md"];
            argv.extend(args);
            let cli = Cli::try_parse_from(argv).expect("valid read range should parse");
            match cli.command {
                Commands::Read { offset, limit, .. } => {
                    assert_eq!((offset, limit), (expected_offset, expected_limit));
                }
                _ => panic!("expected read command"),
            }
        }
        for args in [["--offset", "-1"], ["--limit", "-2"], ["--limit", "abc"]] {
            assert!(
                Cli::try_parse_from(
                    ["ov", "read", "viking://resources/example.md"]
                        .into_iter()
                        .chain(args)
                )
                .is_err()
            );
        }
    }

    #[test]
    fn cli_compile_memory_mode_parses_without_from() {
        let cli = Cli::try_parse_from([
            "ov",
            "compile",
            "--to",
            "viking://user/u1/memories/entities",
            "--skill",
            "memory",
        ])
        .expect("memory-mode compile should parse without --from");
        match cli.command {
            Commands::Compile {
                from_uris, skill, ..
            } => {
                assert!(from_uris.is_empty());
                assert_eq!(skill, "memory");
            }
            _ => panic!("expected compile command"),
        }
    }


    #[test]
    fn server_commands_require_existing_cli_config() {
        let cli = Cli::try_parse_from(["ov", "ls"]).expect("ls should parse");
        let paged_ls = Cli::try_parse_from([
            "ov",
            "ls",
            "--offset",
            "4",
            "--limit",
            "5",
            "--sort-by",
            "mtime",
            "--sort-order",
            "desc",
            "--include-abstract",
            "--include-overview=false",
            "--overview-limit",
            "512",
        ])
        .expect("paged ls should parse");
        let paged_tree = Cli::try_parse_from([
            "ov",
            "tree",
            "viking://resources",
            "--offset",
            "6",
            "--limit",
            "7",
            "--directories-only",
            "--include-abstract",
            "--include-overview=false",
            "--overview-limit",
            "512",
        ])
        .expect("paged tree should parse");
        let health = Cli::try_parse_from(["ov", "health"]).expect("health should parse");

        match paged_ls.command {
            Commands::Ls {
                offset,
                limit,
                sort_by,
                sort_order,
                node_limit,
                include_abstract,
                include_overview,
                overview_limit,
                ..
            } => {
                assert_eq!(offset, 4);
                assert_eq!(limit, Some(5));
                assert_eq!(sort_by.as_deref(), Some("mtime"));
                assert_eq!(sort_order.as_deref(), Some("desc"));
                assert_eq!(node_limit, 256);
                assert_eq!(include_abstract, Some(true));
                assert_eq!(include_overview, Some(false));
                assert_eq!(overview_limit, 512);
            }
            _ => panic!("expected ls command"),
        }
        match paged_tree.command {
            Commands::Tree {
                offset,
                limit,
                node_limit,
                directories_only,
                include_abstract,
                include_overview,
                overview_limit,
                ..
            } => {
                assert_eq!(offset, 6);
                assert_eq!(limit, Some(7));
                assert_eq!(node_limit, 256);
                assert!(directories_only);
                assert_eq!(include_abstract, Some(true));
                assert_eq!(include_overview, Some(false));
                assert_eq!(overview_limit, 512);
            }
            _ => panic!("expected tree command"),
        }
        assert!(cli.command.requires_cli_config_file());
        assert!(health.command.requires_cli_config_file());
    }

    #[test]
    fn bare_config_switch_and_version_do_not_require_existing_cli_config() {
        let setup = Cli::try_parse_from(["ov", "config"]).expect("bare config should parse");
        let switch =
            Cli::try_parse_from(["ov", "config", "switch"]).expect("config switch should parse");
        let switch_named = Cli::try_parse_from(["ov", "config", "switch", "prod"])
            .expect("named config switch should parse");
        let version = Cli::try_parse_from(["ov", "version"]).expect("version should parse");

        assert!(!setup.command.requires_cli_config_file());
        assert!(!switch.command.requires_cli_config_file());
        assert!(!switch_named.command.requires_cli_config_file());
        assert!(!version.command.requires_cli_config_file());

        let skills_validate = Cli::try_parse_from(["ov", "skills", "validate", "./skills/foo"])
            .expect("skills validate should parse");
        assert!(!skills_validate.command.requires_cli_config_file());
    }

    #[test]
    fn config_agent_commands_parse_without_secret_value_flags() {
        let add_ov_service = Cli::try_parse_from([
            "ov",
            "config",
            "add",
            "ov-service",
            "--name",
            "prod",
            "--api-key-stdin",
            "--activate",
        ])
        .expect("ov-service add should parse");
        let Commands::Config {
            action:
                Some(ConfigCommands::Add {
                    target: ConfigAddTarget::OvService(ov_service),
                }),
        } = add_ov_service.command
        else {
            panic!("expected ov-service add command");
        };
        assert_eq!(ov_service.name.as_deref(), Some("prod"));
        assert!(ov_service.api_key_stdin);
        assert!(ov_service.activate);

        let add_custom = Cli::try_parse_from([
            "ov",
            "config",
            "add",
            "custom",
            "--url",
            "https://ov.example.com",
            "--api-key-env",
            "OV_KEY",
            "--actor-peer-id",
            "peer-a",
        ])
        .expect("custom add should parse");
        let Commands::Config {
            action:
                Some(ConfigCommands::Add {
                    target: ConfigAddTarget::Custom(custom),
                }),
        } = add_custom.command
        else {
            panic!("expected custom add command");
        };
        assert_eq!(custom.url.as_deref(), Some("https://ov.example.com"));
        assert_eq!(custom.api_key_env.as_deref(), Some("OV_KEY"));
        assert_eq!(custom.actor_peer_id.as_deref(), Some("peer-a"));

        let edit = Cli::try_parse_from([
            "ov",
            "config",
            "edit",
            "prod",
            "--clear-api-key",
            "--clear-actor-peer-id",
            "--activate",
        ])
        .expect("config edit should parse");
        let Commands::Config {
            action: Some(ConfigCommands::Edit(edit)),
        } = edit.command
        else {
            panic!("expected edit command");
        };
        assert_eq!(edit.name, "prod");
        assert!(edit.clear_api_key);
        assert!(edit.clear_actor_peer_id);
        assert!(edit.activate);

        assert!(
            Cli::try_parse_from(["ov", "config", "add", "ov-service", "--api-key", "secret"])
                .is_err(),
            "plain API key flag must stay rejected"
        );
        assert!(
            Cli::try_parse_from(["ov", "config", "add", "cloud", "--api-key-stdin"]).is_err(),
            "old cloud provider subcommand must stay rejected"
        );
        assert!(
            Cli::try_parse_from(["ov", "config", "add", "self-managed"]).is_err(),
            "old self-managed provider subcommand must stay rejected"
        );
        assert!(
            Cli::try_parse_from([
                "ov",
                "config",
                "add",
                "custom",
                "--use-root-key-for-normal-commands",
            ])
            .is_err(),
            "root-as-normal flag is obsolete and must stay rejected"
        );
        assert!(
            Cli::try_parse_from([
                "ov",
                "config",
                "edit",
                "prod",
                "--use-root-key-for-normal-commands",
            ])
            .is_err(),
            "root-as-normal edit flag is obsolete and must stay rejected"
        );
    }

    #[test]
    fn pre_parse_config_gate_catches_incomplete_known_server_commands() {
        for args in [
            &["ov", "find"][..],
            &["ov", "task", "status"],
            &["ov", "task", "cancel"],
            &["ov", "task", "watch", "show"],
            &["ov", "config", "validate"],
            &["ov", "config", "show"],
            &["ov", "system", "consistency"],
            &["ov", "admin", "list-accounts"],
        ] {
            assert!(
                pre_parse_requires_cli_config_file(&os_args(args)),
                "{args:?} should require ovcli.conf before Clap positional validation"
            );
        }
    }

    #[test]
    fn pre_parse_config_gate_covers_known_top_level_server_commands() {
        for command in [
            "add-resource",
            "add-skill",
            "ls",
            "tree",
            "mkdir",
            "rm",
            "mv",
            "stat",
            "read",
            "abstract",
            "overview",
            "write",
            "get",
            "find",
            "search",
            "grep",
            "glob",
            "add-memory",
            "export",
            "backup",
            "import",
            "restore",
            "tui",
            "chat",
            "wait",
            "status",
            "health",
            "reindex",
        ] {
            assert!(
                pre_parse_requires_cli_config_file(&os_args(&["ov", command])),
                "{command} should require ovcli.conf before Clap validation"
            );
        }
    }

    #[test]
    fn pre_parse_config_gate_covers_known_group_server_commands() {
        let cases: &[&[&str]] = &[
            &["ov", "config", "show"],
            &["ov", "config", "validate"],
            &["ov", "task", "status"],
            &["ov", "task", "cancel"],
            &["ov", "task", "list"],
            &["ov", "task", "watch"],
            &["ov", "task", "watch", "ls"],
            &["ov", "task", "watch", "show"],
            &["ov", "task", "watch", "rm"],
            &["ov", "task", "watch", "pause"],
            &["ov", "task", "watch", "resume"],
            &["ov", "task", "watch", "update"],
            &["ov", "task", "watch", "trigger"],
            &["ov", "admin", "create-account"],
            &["ov", "admin", "list-accounts"],
            &["ov", "admin", "delete-account"],
            &["ov", "admin", "register-user"],
            &["ov", "admin", "list-users"],
            &["ov", "admin", "create-group"],
            &["ov", "admin", "list-groups"],
            &["ov", "admin", "list-group-members"],
            &["ov", "admin", "add-group-member"],
            &["ov", "admin", "remove-group-member"],
            &["ov", "admin", "delete-group"],
            &["ov", "admin", "remove-user"],
            &["ov", "admin", "set-role"],
            &["ov", "admin", "regenerate-key"],
            &["ov", "admin", "set-account-settings"],
            &["ov", "system", "wait"],
            &["ov", "system", "status"],
            &["ov", "system", "health"],
            &["ov", "system", "consistency"],
            &["ov", "system", "crypto"],
            &["ov", "system", "crypto", "init-key"],
            &["ov", "session", "new"],
            &["ov", "session", "list"],
            &["ov", "session", "get"],
            &["ov", "session", "get-session-context"],
            &["ov", "session", "get-session-archive"],
            &["ov", "session", "delete"],
            &["ov", "session", "add-message"],
            &["ov", "session", "add-messages"],
            &["ov", "session", "commit"],
            &["ov", "privacy", "categories"],
            &["ov", "privacy", "tree"],
            &["ov", "privacy", "list"],
            &["ov", "privacy", "get"],
            &["ov", "privacy", "reference"],
            &["ov", "privacy", "resolve"],
            &["ov", "privacy", "upsert"],
            &["ov", "privacy", "versions"],
            &["ov", "privacy", "version"],
            &["ov", "privacy", "activate"],
            &["ov", "privacy", "delete"],
            &["ov", "privacy", "scan"],
            &["ov", "observer", "queue"],
            &["ov", "observer", "vikingdb"],
            &["ov", "observer", "models"],
            &["ov", "observer", "retrieval"],
            &["ov", "observer", "filesystem"],
            &["ov", "observer", "system"],
            &["ov", "skills", "add"],
            &["ov", "skills", "list"],
            &["ov", "skills", "ls"],
            &["ov", "skills", "find"],
            &["ov", "skills", "show"],
            &["ov", "skills", "update"],
            &["ov", "skills", "remove"],
            &["ov", "skills", "rm"],
            &["ov", "skills", "delete"],
        ];

        for args in cases {
            assert!(
                pre_parse_requires_cli_config_file(&os_args(args)),
                "{args:?} should require ovcli.conf before Clap validation"
            );
        }

        assert!(
            pre_parse_requires_cli_config_file(&preprocess_privacy_args(os_args(&[
                "ov", "privacy", "skill", "demo",
            ]))),
            "privacy shortcut should require ovcli.conf after preprocessing"
        );
    }

    #[test]
    fn pre_parse_config_gate_respects_aliases_and_valid_help_values() {
        for args in [
            &["ov", "list"][..],
            &["ov", "delete"],
            &["ov", "rename"],
            &["ov", "lang", "en"],
        ] {
            let expected = args[1] != "lang";
            assert_eq!(
                pre_parse_requires_cli_config_file(&os_args(args)),
                expected,
                "{args:?} pre-parse gate mismatch"
            );
        }
    }

    #[test]
    fn pre_parse_config_gate_allows_non_server_and_unknown_commands() {
        for args in [
            &["ov", "con"][..],
            &["ov", "task", "nope"],
            &["ov", "config"],
            &["ov", "config", "switch"],
            &["ov", "config", "switch", "prod"],
            &["ov", "config", "list"],
            &["ov", "config", "delete", "prod"],
            &["ov", "config", "add", "ov-service", "--api-key-stdin"],
            &["ov", "config", "edit", "prod", "--activate"],
            &["ov", "config", "setup-cli"],
            &["ov", "skills", "validate", "./skills/foo"],
            &["ov", "skills", "validate", "./skills/foo", "--strict"],
            &["ov", "version"],
            &["ov", "language", "en"],
            &["ov", "lang", "en"],
        ] {
            assert!(
                !pre_parse_requires_cli_config_file(&os_args(args)),
                "{args:?} should not be gated before Clap parsing"
            );
        }
    }

    #[test]
    fn cli_tree_help_hides_upload_and_admin_only_flags() {
        let err = Cli::command()
            .try_get_matches_from(["ov", "tree", "--help"])
            .expect_err("help should exit through clap error");
        let help = err.to_string();

        assert!(!help.contains("--progress"));
        assert!(!help.contains("--no-progress"));
        assert!(!help.contains("--verbose"));
        assert!(!help.contains("--sudo"));
    }

    #[test]
    fn cli_add_resource_help_shows_upload_flags() {
        let err = Cli::command()
            .try_get_matches_from(["ov", "add-resource", "--help"])
            .expect_err("help should exit through clap error");
        let help = err.to_string();

        assert!(help.contains("--progress"));
        assert!(help.contains("--no-progress"));
        assert!(help.contains("--verbose"));
        assert!(!help.contains("--parse-mode"));
        assert!(help.contains("--args"));
    }

    #[test]
    fn cli_add_resource_rejects_top_level_parse_mode() {
        assert!(
            Cli::try_parse_from([
                "ov",
                "add-resource",
                "./README.md",
                "--parse-mode",
                "no_split",
            ])
            .is_err()
        );
    }

    #[test]
    fn cli_add_resource_help_shows_tag_flags() {
        let err = Cli::command()
            .try_get_matches_from(["ov", "add-resource", "--help"])
            .expect_err("help should exit through clap error");
        let help = err.to_string();

        assert!(help.contains("--tag"));
        assert!(help.contains("--tag-mode"));
    }

    #[test]
    fn cli_add_skill_help_shows_upload_flags() {
        let err = Cli::command()
            .try_get_matches_from(["ov", "add-skill", "--help"])
            .expect_err("help should exit through clap error");
        let help = err.to_string();

        assert!(help.contains("--progress"));
        assert!(help.contains("--no-progress"));
        assert!(help.contains("--verbose"));
    }

    #[test]
    fn cli_tree_rejects_upload_flags_after_subcommand() {
        assert!(Cli::try_parse_from(["ov", "tree", "viking://", "--progress"]).is_err());
        assert!(Cli::try_parse_from(["ov", "tree", "viking://", "--no-progress"]).is_err());
        assert!(Cli::try_parse_from(["ov", "tree", "viking://", "--verbose"]).is_err());
    }

    #[test]
    fn cli_parses_sudo_as_hidden_global_flag_after_subcommand() {
        let cli = Cli::try_parse_from(["ov", "tree", "viking://", "--sudo"])
            .expect("sudo should parse anywhere so runtime can show a precise command error");

        assert!(cli.sudo);
    }

    #[test]
    fn cli_parses_upload_flags_on_upload_commands() {
        let add_resource = Cli::try_parse_from([
            "ov",
            "add-resource",
            "./README.md",
            "--progress",
            "--verbose",
        ])
        .expect("add-resource upload flags should parse");
        match add_resource.command {
            Commands::AddResource { upload_options, .. } => {
                assert!(upload_options.progress);
                assert!(upload_options.verbose);
            }
            _ => panic!("expected add-resource command"),
        }

        let add_skill = Cli::try_parse_from(["ov", "add-skill", "./skill", "--no-progress"])
            .expect("add-skill upload flags should parse");
        match add_skill.command {
            Commands::AddSkill(args) => {
                assert!(args.upload_options.no_progress);
            }
            _ => panic!("expected add-skill command"),
        }

        assert!(Cli::try_parse_from(["ov", "skills", "add", "./skill", "--progress"]).is_ok());
        assert!(Cli::try_parse_from(["ov", "skills", "update", "--progress"]).is_err());
    }

    #[test]
    fn cli_add_resource_add_type_requires_exact_to() {
        assert!(
            Cli::try_parse_from(["ov", "add-resource", "space:home", "--add-type", "feishu"])
                .is_err()
        );
        assert!(
            Cli::try_parse_from([
                "ov",
                "add-resource",
                "space:home",
                "--add-type",
                "feishu",
                "--to",
                "viking://resources/feishu",
                "--parent",
                "viking://resources/imports",
            ])
            .is_err()
        );
        assert!(
            Cli::try_parse_from([
                "ov",
                "add-resource",
                "space:home",
                "--add-type",
                "feishu",
                "--to",
                "viking://resources/feishu",
                "--parent-auto-create",
                "viking://resources/imports",
            ])
            .is_err()
        );

        let cli = Cli::try_parse_from([
            "ov",
            "add-resource",
            "space:home",
            "--add-type",
            "feishu",
            "--to",
            "viking://resources/feishu",
        ])
        .expect("declared add type with an exact target should parse");

        match cli.command {
            Commands::AddResource { add_type, to, .. } => {
                assert_eq!(add_type.as_deref(), Some("feishu"));
                assert_eq!(to.as_deref(), Some("viking://resources/feishu"));
            }
            _ => panic!("expected add-resource command"),
        }
    }

    #[test]
    fn cli_parses_add_resource_tags() {
        let cli = Cli::try_parse_from([
            "ov",
            "add-resource",
            "./README.md",
            "--tags",
            "team=search,env=test",
            "--tag-mode",
            "append",
        ])
        .expect("add-resource tag flags should parse");

        match cli.command {
            Commands::AddResource { tags, tag_mode, .. } => {
                assert_eq!(tags, vec!["team=search", "env=test"]);
                assert_eq!(tag_mode, "append");
            }
            _ => panic!("expected add-resource command"),
        }
    }

    #[test]
    fn cli_parses_clear_tag_mode_without_tags() {
        let add = Cli::try_parse_from([
            "ov",
            "add-resource",
            "./README.md",
            "--tag-mode",
            "clear",
        ])
        .expect("add-resource clear mode should parse");
        match add.command {
            Commands::AddResource { tags, tag_mode, .. } => {
                assert!(tags.is_empty());
                assert_eq!(tag_mode, "clear");
            }
            _ => panic!("expected add-resource command"),
        }

        let write = Cli::try_parse_from([
            "ov",
            "write",
            "viking://resources/demo.md",
            "--content",
            "content",
            "--tag-mode",
            "clear",
            "--edit-source",
            "compile",
        ])
        .expect("write clear mode with Compile source should parse");
        assert!(matches!(
            write.command,
            Commands::Write { tag_mode, tags, edit_source, .. }
                if tag_mode == "clear" && tags.is_empty() && edit_source == "compile"
        ));

        let reindex = Cli::try_parse_from([
            "ov",
            "reindex",
            "viking://resources/demo",
            "--tag-mode",
            "clear",
        ])
        .expect("reindex clear mode should parse");
        assert!(matches!(
            reindex.command,
            Commands::Reindex { tag_mode, tags, .. } if tag_mode == "clear" && tags.is_empty()
        ));
    }

    #[test]
    fn cli_parses_skills_command_group() {
        let list = Cli::try_parse_from(["ov", "skills", "list", "--limit", "25"])
            .expect("skills list should parse");
        match list.command {
            Commands::Skills {
                action: SkillCommands::List { node_limit, .. },
            } => assert_eq!(node_limit, 25),
            _ => panic!("expected skills list"),
        }

        let find = Cli::try_parse_from([
            "ov",
            "skills",
            "find",
            "review code",
            "--threshold",
            "0.4",
            "--level",
            "0,1",
        ])
        .expect("skills find should parse");
        match find.command {
            Commands::Skills {
                action:
                    SkillCommands::Find {
                        query,
                        threshold,
                        level,
                        ..
                    },
            } => {
                assert_eq!(query, "review code");
                assert_eq!(threshold, Some(0.4));
                assert_eq!(level, Some(vec![0, 1]));
            }
            _ => panic!("expected skills find"),
        }

        let update =
            Cli::try_parse_from(["ov", "skills", "update", "code-review", "--wait", "--yes"])
                .expect("skills update should parse");
        match update.command {
            Commands::Skills {
                action:
                    SkillCommands::Update {
                        skills, wait, yes, ..
                    },
            } => {
                assert_eq!(skills, vec!["code-review"]);
                assert!(wait);
                assert!(yes);
            }
            _ => panic!("expected skills update"),
        }

        for mut argv in [vec!["ov", "add-skill"], vec!["ov", "skills", "add"]] {
            argv.extend([
                "https://github.com/acme/skills.git",
                "--skill",
                "foo",
                "bar",
                "--list",
                "--yes",
                "--wait",
                "--parent-auto-create",
                "viking://agent/skills",
                "--no-progress",
            ]);
            let add_selected = Cli::try_parse_from(argv)
                .expect("both skill add commands should accept the same options");
            let args = match add_selected.command {
                Commands::AddSkill(args)
                | Commands::Skills {
                    action: SkillCommands::Add(args),
                } => args,
                _ => panic!("expected skill add command"),
            };
            assert_eq!(args.source, "https://github.com/acme/skills.git");
            assert_eq!(args.skills, vec!["foo", "bar"]);
            assert!(args.list);
            assert!(args.yes);
            assert!(args.wait);
            assert_eq!(args.parent.as_deref(), Some("viking://agent/skills"));
            assert!(args.upload_options.no_progress);
        }

        let show = Cli::try_parse_from([
            "ov",
            "skills",
            "show",
            "code-review",
            "--level",
            "2",
            "--files",
            "--source",
            "--format",
            "json",
        ])
        .expect("skills show RFC flags should parse");
        match show.command {
            Commands::Skills {
                action:
                    SkillCommands::Show {
                        level,
                        files,
                        source,
                        format,
                        ..
                    },
            } => {
                assert_eq!(level, Some(2));
                assert!(files);
                assert!(source);
                assert_eq!(format.as_deref(), Some("json"));
            }
            _ => panic!("expected skills show"),
        }

        let show_global_output =
            Cli::try_parse_from(["ov", "skills", "show", "code-review", "-o", "json"])
                .expect("skills show should accept global -o after the subcommand");
        assert_eq!(show_global_output.output, Some(OutputFormat::Json));

        let remove = Cli::try_parse_from(["ov", "skills", "remove", "foo", "bar", "--yes"])
            .expect("skills remove --yes should parse");
        match remove.command {
            Commands::Skills {
                action:
                    SkillCommands::Remove {
                        skills, yes, all, ..
                    },
            } => {
                assert_eq!(skills, vec!["foo", "bar"]);
                assert!(yes);
                assert!(!all);
            }
            _ => panic!("expected skills remove"),
        }

        let validate =
            Cli::try_parse_from(["ov", "skills", "validate", "./skills/foo", "--strict"])
                .expect("skills validate --strict should parse");
        match validate.command {
            Commands::Skills {
                action: SkillCommands::Validate { path, strict },
            } => {
                assert_eq!(path, "./skills/foo");
                assert!(strict);
            }
            _ => panic!("expected skills validate"),
        }
    }

    #[test]
    fn cli_keeps_legacy_pre_command_upload_flags() {
        let cli = Cli::try_parse_from([
            "ov",
            "--progress",
            "--verbose",
            "add-resource",
            "./README.md",
        ])
        .expect("legacy pre-command upload flags should still parse");

        assert!(cli.progress);
        assert!(cli.verbose);
    }

    #[test]
    fn legacy_pre_command_upload_flags_only_allow_upload_commands() {
        let upload_options = UploadCliOptions {
            progress: true,
            no_progress: false,
            verbose: false,
        };

        let tree = Cli::try_parse_from(["ov", "--progress", "tree", "viking://"])
            .expect("hidden legacy flag still parses before runtime validation");
        assert_eq!(
            legacy_upload_option_error(upload_options, &tree.command),
            Some(
                "--progress, --no-progress, and --verbose are only supported for add-resource, add-skill, and skills add."
            )
        );

        let add_resource = Cli::try_parse_from(["ov", "--progress", "add-resource", "./README.md"])
            .expect("legacy pre-command upload flags should parse for add-resource");
        assert!(legacy_upload_option_error(upload_options, &add_resource.command).is_none());

        let skills_add = Cli::try_parse_from(["ov", "--progress", "skills", "add", "./skill"])
            .expect("hidden legacy flag still parses before runtime validation");
        assert!(legacy_upload_option_error(upload_options, &skills_add.command).is_none());
    }

    #[test]
    fn cli_parses_sudo_before_admin_command() {
        let cli = Cli::try_parse_from(["ov", "--sudo", "admin", "list-accounts"])
            .expect("pre-command sudo should parse");

        assert!(cli.sudo);
    }

    #[test]
    fn cli_parses_sudo_after_admin_command() {
        let cli = Cli::try_parse_from(["ov", "admin", "list-accounts", "--sudo"])
            .expect("post-command sudo should parse");

        assert!(cli.sudo);
    }

    #[test]
    fn sudo_supports_task_status_and_list_only() {
        let status = Cli::try_parse_from(["ov", "--sudo", "task", "status", "task-123"])
            .expect("sudo task status should parse");
        assert!(status.sudo);
        assert!(status.command.supports_sudo());

        let list = Cli::try_parse_from([
            "ov",
            "--sudo",
            "task",
            "list",
            "--task-type",
            "admin_reindex",
        ])
        .expect("sudo task list should parse");
        assert!(list.sudo);
        assert!(list.command.supports_sudo());

        let watch = Cli::try_parse_from(["ov", "--sudo", "task", "watch", "ls"])
            .expect("sudo task watch should still parse before runtime validation");
        assert!(watch.sudo);
        assert!(!watch.command.supports_sudo());
    }

    #[test]
    fn cli_config_without_subcommand_parses_as_setup_entrypoint() {
        Cli::try_parse_from(["ov", "config"]).expect("bare config command should parse");
    }

    #[test]
    fn cli_config_single_purpose_subcommands_still_parse() {
        for subcommand in ["show", "validate", "switch"] {
            Cli::try_parse_from(["ov", "config", subcommand])
                .unwrap_or_else(|_| panic!("config {subcommand} should parse"));
        }
    }

    #[test]
    fn cli_config_rejects_removed_setup_cli_subcommand() {
        assert!(Cli::try_parse_from(["ov", "config", "setup-cli"]).is_err());
    }

    #[test]
    fn cli_language_command_and_alias_parse() {
        let cli = Cli::try_parse_from(["ov", "language", "zh-CN"])
            .expect("language command should parse");
        match cli.command {
            Commands::Language { language } => assert_eq!(language.as_deref(), Some("zh-CN")),
            _ => panic!("expected language command"),
        }

        let cli = Cli::try_parse_from(["ov", "lang"]).expect("language alias should parse");
        match cli.command {
            Commands::Language { language } => assert!(language.is_none()),
            _ => panic!("expected language command"),
        }
    }

    #[test]
    fn all_node_limit_options_accept_zero_and_reject_negative_values() {
        let command_prefixes = [
            vec!["ov", "ls", "--node-limit"],
            vec!["ov", "tree", "viking://resources", "--node-limit"],
            vec!["ov", "find", "query", "--node-limit"],
            vec!["ov", "search", "query", "--node-limit"],
            vec!["ov", "grep", "query", "--node-limit"],
            vec!["ov", "glob", "**/*", "--node-limit"],
            vec!["ov", "skills", "list", "--node-limit"],
            vec!["ov", "skills", "find", "query", "--node-limit"],
        ];

        for prefix in command_prefixes {
            let mut negative_args = prefix.clone();
            negative_args.push("-1");
            assert!(
                Cli::try_parse_from(&negative_args).is_err(),
                "{negative_args:?} should reject a negative node limit"
            );

            let mut zero_args = prefix.clone();
            zero_args.push("0");
            assert!(
                Cli::try_parse_from(&zero_args).is_ok(),
                "{zero_args:?} should preserve the established zero-limit semantics"
            );

            let mut args = prefix;
            args.push("1");
            assert!(
                Cli::try_parse_from(&args).is_ok(),
                "{args:?} should accept a positive node limit"
            );
        }

        for prefix in [
            vec!["ov", "ls", "--limit"],
            vec!["ov", "tree", "viking://resources", "--limit"],
        ] {
            let mut zero_args = prefix.clone();
            zero_args.push("0");
            assert!(Cli::try_parse_from(&zero_args).is_err());

            let mut positive_args = prefix;
            positive_args.push("1");
            assert!(Cli::try_parse_from(&positive_args).is_ok());
        }

        for prefix in [
            vec!["ov", "ls", "--offset"],
            vec!["ov", "tree", "viking://resources", "--offset"],
        ] {
            let mut negative_args = prefix.clone();
            negative_args.push("-1");
            assert!(Cli::try_parse_from(&negative_args).is_err());

            let mut zero_args = prefix;
            zero_args.push("0");
            assert!(Cli::try_parse_from(&zero_args).is_ok());
        }
    }

    #[test]
    fn config_commands_can_load_invalid_runtime_values_for_repair() {
        let cli = Cli::try_parse_from(["ov", "config", "show"]).expect("config show should parse");
        assert!(cli.command.allows_invalid_runtime_config());

        let status = Cli::try_parse_from(["ov", "status"]).expect("status should parse");
        assert!(!status.command.allows_invalid_runtime_config());
    }

    #[test]
    fn configured_output_is_used_unless_cli_overrides_it() {
        let config = Config {
            output: "json".to_string(),
            ..Config::default()
        };

        assert_eq!(resolve_output_format(None, &config), OutputFormat::Json);
        assert_eq!(
            resolve_output_format(Some(OutputFormat::Table), &config),
            OutputFormat::Table
        );
        let cli = Cli::try_parse_from(["ov", "status"]).unwrap();
        assert_eq!(cli.output, None);

        let invalid_config = Config {
            output: "yaml".to_string(),
            ..Config::default()
        };
        assert_eq!(
            resolve_output_format(None, &invalid_config),
            OutputFormat::Table,
            "repair commands need a safe fallback for invalid persisted output"
        );
    }

    #[test]
    fn only_explicit_clap_help_bypasses_language_setup() {
        for args in [
            ["ov", "--help"].as_slice(),
            ["ov", "-h"].as_slice(),
            ["ov", "status", "--help"].as_slice(),
            ["ov", "system", "wait", "-h"].as_slice(),
        ] {
            assert!(
                render_pre_language_help_request(&os_args(args)).is_some(),
                "{args:?} should render before language setup"
            );
        }

        for args in [
            ["ov", "status"].as_slice(),
            ["ov", "task"].as_slice(),
            ["ov", "-help"].as_slice(),
            ["ov", "--account", "--help", "status"].as_slice(),
        ] {
            assert!(
                render_pre_language_help_request(&os_args(args)).is_none(),
                "{args:?} should keep the language gate"
            );
        }
    }

    #[test]
    fn language_gate_detects_language_command_after_global_flags() {
        assert!(is_language_command_request(&os_args(&["ov", "language"])));
        assert!(is_language_command_request(&os_args(&[
            "ov", "lang", "zh-CN"
        ])));
        assert!(is_language_command_request(&os_args(&[
            "ov", "--output", "json", "language", "en",
        ])));
        assert!(is_language_command_request(&os_args(&[
            "ov",
            "--output=json",
            "--compact",
            "false",
            "lang",
        ])));
        assert!(is_language_command_request(&os_args(&[
            "ov",
            "--compact",
            "lang",
        ])));
        assert!(!is_language_command_request(&os_args(&["ov", "status"])));
        assert!(!is_language_command_request(&os_args(&["ov", "--help"])));
    }

    #[test]
    fn language_gate_action_continues_prompts_or_exits() {
        assert_eq!(
            language_gate_action(&os_args(&["ov", "status"]), true, false),
            LanguageGateAction::Continue
        );
        assert_eq!(
            language_gate_action(&os_args(&["ov", "language"]), false, false),
            LanguageGateAction::Continue
        );
        assert_eq!(
            language_gate_action(&os_args(&["ov", "status"]), false, true),
            LanguageGateAction::Prompt
        );
        assert_eq!(
            language_gate_action(&os_args(&["ov", "status"]), false, false),
            LanguageGateAction::ExitNonInteractive
        );
    }

    #[test]
    fn language_gate_allows_config_agent_commands_without_saved_language() {
        for args in [
            &["ov", "config", "add", "ov-service", "--api-key-stdin"][..],
            &["ov", "config", "add", "custom"],
            &["ov", "config", "edit", "prod", "--activate"],
            &["ov", "config", "delete", "prod"],
            &["ov", "config", "list"],
            &["ov", "config", "switch", "prod"],
        ] {
            assert_eq!(
                language_gate_action(&os_args(args), false, false),
                LanguageGateAction::Continue,
                "{args:?} should bypass first-run language selection"
            );
        }

        assert_eq!(
            language_gate_action(&os_args(&["ov", "config"]), false, false),
            LanguageGateAction::ExitNonInteractive
        );
    }

    #[test]
    fn language_gate_message_points_to_explicit_language_commands() {
        let message = language_required_message();

        assert!(message.contains("ov language en"));
        assert!(message.contains("ov language zh-CN"));
    }

    #[test]
    fn language_command_without_value_requires_interactive_picker() {
        assert!(language_command_can_run_picker(true, false));
        assert!(language_command_can_run_picker(false, true));
        assert!(!language_command_can_run_picker(false, false));
    }

    #[test]
    fn first_command_token_skips_global_flags() {
        assert_eq!(
            first_command_token(&os_args(&[
                "ov",
                "--output",
                "json",
                "--account=acme",
                "--actor-peer-id",
                "peer-a",
                "--sudo",
                "admin",
            ]))
            .as_deref(),
            Some("admin")
        );
        assert_eq!(
            first_command_token(&os_args(&["ov", "--help"])).as_deref(),
            None
        );
    }

    #[test]
    fn find_command_index_skips_root_value_options() {
        assert_eq!(
            find_command_index(&os_args(&[
                "ov",
                "--output",
                "json",
                "--account=acme",
                "--actor-peer-id",
                "peer-a",
                "privacy",
                "sample-policy",
            ])),
            Some(6)
        );
        assert_eq!(
            find_command_index(&os_args(&["ov", "--compact", "privacy", "sample-policy"])),
            Some(2)
        );
        assert_eq!(
            find_command_index(&os_args(&["ov", "-c", "false", "privacy", "sample-policy"])),
            Some(3)
        );
    }

    #[test]
    fn cli_status_parses_verbose_flag() {
        let cli =
            Cli::try_parse_from(["ov", "status", "--verbose"]).expect("status verbose parses");

        match cli.command {
            Commands::Status { verbose } => assert!(verbose),
            _ => panic!("expected status command"),
        }
    }

    #[test]
    fn plain_help_is_rejected_for_top_level_group_and_structured_leaf_commands() {
        for (args, expected_help) in [
            (vec!["ov", "help"], "ov --help"),
            (vec!["ov", "config", "help"], "ov config --help"),
            (vec!["ov", "task", "help"], "ov task --help"),
            (vec!["ov", "admin", "help"], "ov admin --help"),
            (vec!["ov", "ls", "help"], "ov ls --help"),
            (vec!["ov", "tree", "help"], "ov tree --help"),
            (vec!["ov", "read", "help"], "ov read --help"),
            (
                vec!["ov", "task", "status", "help"],
                "ov task status --help",
            ),
            (
                vec!["ov", "system", "consistency", "help"],
                "ov system consistency --help",
            ),
        ] {
            let misuse = plain_help_misuse(&os_args(&args))
                .unwrap_or_else(|| panic!("{args:?} should be plain-help misuse"));
            assert_eq!(misuse.help_command, expected_help);
        }
    }

    #[test]
    fn plain_help_is_allowed_as_free_form_user_input() {
        for args in [
            vec!["ov", "find", "help"],
            vec!["ov", "search", "help"],
            vec!["ov", "grep", "help"],
            vec!["ov", "glob", "help"],
            vec!["ov", "add-memory", "help"],
            vec!["ov", "add-resource", "help"],
            vec!["ov", "add-skill", "help"],
        ] {
            assert!(
                plain_help_misuse(&os_args(&args)).is_none(),
                "{args:?} should remain normal user input"
            );
        }
    }

    #[test]
    fn plain_help_ignores_option_values() {
        assert!(
            plain_help_misuse(&os_args(&[
                "ov",
                "read",
                "--account",
                "help",
                "viking://resource",
            ]))
            .is_none()
        );
        assert!(plain_help_misuse(&os_args(&["ov", "grep", "--uri", "help", "TODO",])).is_none());

        for args in [
            &["ov", "mkdir", "--description", "help", "viking://notes"][..],
            &[
                "ov",
                "write",
                "viking://notes/todo.md",
                "--from-file",
                "help",
            ],
            &[
                "ov",
                "session",
                "add-message",
                "abc",
                "--peer-id",
                "help",
                "--role",
                "user",
                "--content",
                "hi",
            ],
            &[
                "ov",
                "privacy",
                "upsert",
                "cat",
                "target",
                "--values-json",
                "help",
            ],
            &["ov", "admin", "create-account", "acct", "--admin", "help"],
            &["ov", "config", "add", "custom", "--url", "help"],
            &["ov", "task", "list", "--status", "help"],
            &[
                "ov",
                "system",
                "crypto",
                "init-key",
                "--output-file",
                "help",
            ],
        ] {
            assert!(
                plain_help_misuse(&os_args(args)).is_none(),
                "{args:?} should treat help as an option value"
            );
        }
    }

    #[test]
    fn cli_context_overrides_identity_from_cli_flags() {
        let config = Config {
            url: DEFAULT_CUSTOM_URL.to_string(),
            api_key: Some("test-key".to_string()),
            root_api_key: None,
            account: Some("from-config-account".to_string()),
            user: Some("from-config-user".to_string()),
            actor_peer_id: Some("from-config-peer".to_string()),
            agent_id: None,
            timeout: 60.0,
            output: "table".to_string(),
            echo_command: true,
            show_progress: false,
            verbose: false,
            upload: Default::default(),
            extra_headers: None,
            profile: false,
            gateway_token: None,
            auth_mode: None,
            ldap_username: None,
            ldap_password: None,
            oidc_token: None,
        };

        let ctx = CliContext::from_config(
            config,
            OutputFormat::Json,
            true,
            Some("from-cli-account".to_string()),
            Some("from-cli-user".to_string()),
            Some("from-cli-peer".to_string()),
            false,
            None,
            None,
            None,
        );

        assert_eq!(ctx.config.account.as_deref(), Some("from-cli-account"));
        assert_eq!(ctx.config.user.as_deref(), Some("from-cli-user"));
        assert_eq!(ctx.config.actor_peer_id.as_deref(), Some("from-cli-peer"));
        assert!(ctx.config.agent_id.is_none());
    }

    #[test]
    fn cli_context_maps_agent_id_to_actor_peer_scope() {
        let config = Config {
            url: DEFAULT_CUSTOM_URL.to_string(),
            api_key: Some("test-key".to_string()),
            root_api_key: None,
            account: None,
            user: None,
            actor_peer_id: None,
            agent_id: Some("legacy-agent".to_string()),
            timeout: 60.0,
            output: "table".to_string(),
            echo_command: true,
            show_progress: false,
            verbose: false,
            upload: Default::default(),
            extra_headers: None,
            profile: false,
            gateway_token: None,
            auth_mode: None,
            ldap_username: None,
            ldap_password: None,
            oidc_token: None,
        };

        let ctx = CliContext::from_config(
            config,
            OutputFormat::Json,
            true,
            None,
            None,
            None,
            false,
            None,
            None,
            None,
        );
        let client = ctx.get_client();

        assert_eq!(client.actor_peer_id(), Some("legacy-agent"));
    }

    #[test]
    fn cli_context_uses_root_api_key_with_sudo() {
        let config = Config {
            url: DEFAULT_CUSTOM_URL.to_string(),
            api_key: Some("user-key".to_string()),
            root_api_key: Some("root-key".to_string()),
            account: None,
            user: None,
            actor_peer_id: Some("peer-a".to_string()),
            agent_id: None,
            timeout: 60.0,
            output: "table".to_string(),
            echo_command: true,
            show_progress: false,
            verbose: false,
            profile: false,
            upload: Default::default(),
            extra_headers: None,
            gateway_token: None,
            auth_mode: None,
            ldap_username: None,
            ldap_password: None,
            oidc_token: None,
        };

        // Without sudo: use api_key
        let ctx = CliContext::from_config(
            config.clone(),
            OutputFormat::Json,
            true,
            None,
            None,
            None,
            false,
            None,
            None,
            None,
        );
        let client = ctx.get_client();
        assert_eq!(client.api_key(), Some("user-key"));
        assert_eq!(client.actor_peer_id(), Some("peer-a"));

        // With sudo: use root_api_key
        let ctx = CliContext::from_config(
            config,
            OutputFormat::Json,
            true,
            None,
            None,
            None,
            true,
            None,
            None,
            None,
        );
        let client = ctx.get_client();
        assert_eq!(client.api_key(), Some("root-key"));
    }

    #[test]
    fn observer_alias_and_snapshot_restore_examples_parse() {
        let observer = Cli::try_parse_from(["ov", "observer", "fs"]).unwrap();
        assert!(matches!(
            observer.command,
            Commands::Observer {
                action: ObserverCommands::Filesystem
            }
        ));

        let snapshot = Cli::try_parse_from([
            "ov",
            "snapshot",
            "restore",
            "abc123",
            "viking://projects/acme",
        ])
        .unwrap();
        assert!(matches!(
            snapshot.command,
            Commands::Snapshot {
                cmd: SnapshotCmd::Restore {
                    source_commit,
                    project_dir,
                    ..
                }
            } if source_commit == "abc123" && project_dir.as_deref() == Some("viking://projects/acme")
        ));
    }

    #[test]
    fn cli_write_rejects_removed_semantic_flags() {
        let result = Cli::try_parse_from([
            "ov",
            "write",
            "viking://resources/demo.md",
            "--content",
            "updated",
            "--no-semantics",
            "--no-vectorize",
        ]);

        assert!(result.is_err(), "removed write flags should not parse");
    }

    #[test]
    fn cli_import_rejects_removed_vectorize_flag() {
        let result = Cli::try_parse_from([
            "ov",
            "import",
            "./exports/demo.ovpack",
            "viking://resources/imported/",
            "--no-vectorize",
        ]);

        assert!(
            result.is_err(),
            "removed import vectorize flag should not parse"
        );
    }

    #[test]
    fn cli_import_rejects_removed_force_flag() {
        let result = Cli::try_parse_from([
            "ov",
            "import",
            "./exports/demo.ovpack",
            "viking://resources/imported/",
            "--force",
        ]);

        assert!(
            result.is_err(),
            "removed import force flag should not parse"
        );
    }

    #[test]
    fn cli_manifest_mode_takes_run_options_via_args() {
        let result = Cli::try_parse_from([
            "ov",
            "add-resource",
            "--manifest",
            "manifests/code-qa.yaml",
            "--args",
            "catalog:catalog.yaml,dry_run:true,skip_failed:true",
        ]);

        assert!(result.is_ok(), "manifest mode with --args should parse");
    }

    #[test]
    fn cli_manifest_mode_dropped_dedicated_run_flags() {
        for flag in [
            "--catalog=catalog.yaml",
            "--dry-run",
            "--skip-failed",
            "--external-connector",
        ] {
            let result =
                Cli::try_parse_from(["ov", "add-resource", "--manifest", "code-qa.yaml", flag]);
            assert!(
                result.is_err(),
                "removed manifest flag {flag} should not parse"
            );
        }
    }

    #[test]
    fn cli_manifest_mode_rejects_silently_ignored_single_resource_options() {
        for args in [
            ["--reason", "why"],
            ["--instruction", "how"],
            ["--no-directly-upload-media", "--wait"],
        ] {
            let result = Cli::try_parse_from(
                ["ov", "add-resource", "--manifest", "code-qa.yaml"]
                    .into_iter()
                    .chain(args),
            );
            assert!(
                result.is_err(),
                "{} must conflict with --manifest instead of being ignored",
                args[0]
            );
        }
    }

    #[test]
    fn cli_parses_reindex_command() {
        let result = Cli::try_parse_from([
            "ov",
            "reindex",
            "viking://resources/demo",
            "--mode",
            "semantic_and_vectors",
            "--wait=false",
            "--force",
            "--tags",
            "team=search",
            "--tag-mode",
            "append",
            "--recursive=false",
        ]);

        let cli = result.expect("reindex command should parse");
        match cli.command {
            Commands::Reindex {
                force,
                tags,
                tag_mode,
                recursive,
                ..
            } => {
                assert_eq!(tags, vec!["team=search"]);
                assert!(force);
                assert_eq!(tag_mode, "append");
                assert!(!recursive);
            }
            _ => panic!("expected reindex command"),
        }
    }

    #[test]
    fn cli_rejects_unknown_reindex_mode() {
        let result = Cli::try_parse_from([
            "ov",
            "reindex",
            "viking://resources/demo",
            "--mode",
            "semantic",
        ]);

        assert!(result.is_err(), "unknown reindex mode should not parse");
    }

    #[test]
    fn append_time_filter_params_only_emits_after_and_before() {
        let mut params = Vec::new();
        let after = Some("7d".to_string());
        let before = Some("2026-03-12".to_string());

        handlers::append_time_filter_params(&mut params, after.as_deref(), before.as_deref());

        assert_eq!(params, vec!["--after 7d", "--before 2026-03-12"]);
    }

    #[test]
    fn preprocess_field_dynamic_flags_to_static_form() {
        for dynamic_flag in ["--field-api_key", "--key-api_key"] {
            let args = vec![
                OsString::from("ov"),
                OsString::from("privacy"),
                OsString::from("upsert"),
                OsString::from("skill"),
                OsString::from("demo"),
                OsString::from(dynamic_flag),
                OsString::from("secret-v1"),
            ];

            let converted = preprocess_privacy_args(args);
            let converted_strs: Vec<String> = converted
                .into_iter()
                .map(|s| s.to_string_lossy().to_string())
                .collect();

            assert_eq!(
                converted_strs,
                vec![
                    "ov",
                    "privacy",
                    "upsert",
                    "skill",
                    "demo",
                    "--field",
                    "api_key=secret-v1",
                ]
            );
        }
    }

    fn on_cli_parser_stack(test: impl FnOnce() + Send + 'static) {
        std::thread::Builder::new()
            .stack_size(16 * 1024 * 1024)
            .spawn(test)
            .expect("spawn CLI parser test")
            .join()
            .expect("CLI parser test thread");
    }

    #[test]
    fn cli_parses_privacy_tree_options_without_rewriting_to_get() {
        on_cli_parser_stack(|| {
            let args = [
                "ov",
                "privacy",
                "tree",
                "--category",
                "credential",
                "--references",
                "--output",
                "json",
            ]
            .into_iter()
            .map(OsString::from)
            .collect();
            let cli = Cli::parse_from(preprocess_privacy_args(args));
            let Commands::Privacy { action } = cli.command else {
                panic!("expected privacy command")
            };
            let PrivacyCommands::Tree {
                category,
                references,
            } = *action
            else {
                panic!("expected tree command")
            };
            assert_eq!(category.as_deref(), Some("credential"));
            assert!(references);
        });
    }

    #[test]
    fn cli_parses_privacy_upsert_with_field_dynamic_flag() {
        on_cli_parser_stack(|| {
            let cli = Cli::parse_from(preprocess_privacy_args(vec![
                OsString::from("ov"),
                OsString::from("privacy"),
                OsString::from("upsert"),
                OsString::from("skill"),
                OsString::from("demo"),
                OsString::from("--field-api_key"),
                OsString::from("secret-v2"),
            ]));

            match cli.command {
                Commands::Privacy { action } => match *action {
                    PrivacyCommands::Upsert {
                        category,
                        target_key,
                        field,
                        ..
                    } => {
                        assert_eq!(category, "skill");
                        assert_eq!(target_key, "demo");
                        assert_eq!(field, vec!["api_key=secret-v2"]);
                    }
                    _ => panic!("expected privacy upsert"),
                },
                _ => panic!("expected privacy command"),
            }

            for flag in ["--field", "--key"] {
                let cli = Cli::parse_from(preprocess_privacy_args(vec![
                    OsString::from("ov"),
                    OsString::from("privacy"),
                    OsString::from("upsert"),
                    OsString::from("skill"),
                    OsString::from("demo"),
                    OsString::from(flag),
                    OsString::from("api_key=secret-v3"),
                ]));
                match cli.command {
                    Commands::Privacy { action } => match *action {
                        PrivacyCommands::Upsert { field, .. } => {
                            assert_eq!(field, vec!["api_key=secret-v3"]);
                        }
                        _ => panic!("expected privacy upsert"),
                    },
                    _ => panic!("expected privacy command"),
                }
            }
        });
    }

    #[test]
    fn cli_parses_privacy_reference_resolve_and_delete() {
        on_cli_parser_stack(|| {
            for (subcommand, expected_field) in [("reference", "api_key"), ("resolve", "token")] {
                let cli = Cli::parse_from(preprocess_privacy_args(vec![
                    OsString::from("ov"),
                    OsString::from("privacy"),
                    OsString::from(subcommand),
                    OsString::from("credential"),
                    OsString::from("github-prod"),
                    OsString::from(expected_field),
                ]));

                match cli.command {
                    Commands::Privacy { action } => match *action {
                        PrivacyCommands::Reference {
                            category,
                            target_key,
                            field,
                        } => {
                            assert_eq!(subcommand, "reference");
                            assert_eq!(category, "credential");
                            assert_eq!(target_key, "github-prod");
                            assert_eq!(field.as_deref(), Some(expected_field));
                        }
                        PrivacyCommands::Resolve {
                            selector_or_category,
                            target_key,
                            field,
                        } => {
                            assert_eq!(subcommand, "resolve");
                            assert_eq!(selector_or_category, "credential");
                            assert_eq!(target_key.as_deref(), Some("github-prod"));
                            assert_eq!(field.as_deref(), Some(expected_field));
                        }
                        _ => panic!("expected privacy field command"),
                    },
                    _ => panic!("expected privacy command"),
                }
            }

            for subcommand in ["reference", "resolve"] {
                let cli = Cli::parse_from(preprocess_privacy_args(vec![
                    OsString::from("ov"),
                    OsString::from("privacy"),
                    OsString::from(subcommand),
                    OsString::from("credential"),
                    OsString::from("github-prod"),
                ]));

                match cli.command {
                    Commands::Privacy { action } => match *action {
                        PrivacyCommands::Reference { field, .. } => {
                            assert_eq!(subcommand, "reference");
                            assert!(field.is_none());
                        }
                        PrivacyCommands::Resolve {
                            target_key, field, ..
                        } => {
                            assert_eq!(subcommand, "resolve");
                            assert_eq!(target_key.as_deref(), Some("github-prod"));
                            assert!(field.is_none());
                        }
                        _ => panic!("expected privacy field command"),
                    },
                    _ => panic!("expected privacy command"),
                }
            }

            let scan = Cli::parse_from(preprocess_privacy_args(vec![
                OsString::from("ov"),
                OsString::from("privacy"),
                OsString::from("scan"),
                OsString::from("--uri"),
                OsString::from("viking://~/resources/project-a"),
                OsString::from("--fix"),
            ]));
            match scan.command {
                Commands::Privacy { action } => match *action {
                    PrivacyCommands::Scan {
                        uri,
                        fix,
                        node_limit,
                    } => {
                        assert_eq!(uri, "viking://~/resources/project-a");
                        assert!(fix);
                        assert_eq!(node_limit, 1000);
                    }
                    _ => panic!("expected privacy scan"),
                },
                _ => panic!("expected privacy command"),
            }

            for invalid_args in [
                vec!["ov", "privacy", "scan"],
                vec![
                    "ov",
                    "privacy",
                    "scan",
                    "--uri",
                    "viking://~/resources/project-a",
                    "--node-limit",
                    "1001",
                ],
            ] {
                assert!(Cli::try_parse_from(invalid_args).is_err());
            }

            let reference =
                "{{ov_privacy:alice:viking://~/privacy/credential/github-prod#/values/api_key}}";
            let resolved = Cli::parse_from(preprocess_privacy_args(vec![
                OsString::from("ov"),
                OsString::from("privacy"),
                OsString::from("resolve"),
                OsString::from(reference),
            ]));
            match resolved.command {
                Commands::Privacy { action } => match *action {
                    PrivacyCommands::Resolve {
                        selector_or_category,
                        target_key,
                        field,
                    } => {
                        assert_eq!(selector_or_category, reference);
                        assert!(target_key.is_none() && field.is_none());
                    }
                    _ => panic!("expected privacy resolve"),
                },
                _ => panic!("expected privacy command"),
            }

            let cli = Cli::parse_from(preprocess_privacy_args(vec![
                OsString::from("ov"),
                OsString::from("privacy"),
                OsString::from("delete"),
                OsString::from("credential"),
                OsString::from("github-prod"),
                OsString::from("--yes"),
            ]));
            match cli.command {
                Commands::Privacy { action } => match *action {
                    PrivacyCommands::Delete {
                        selector_or_category,
                        target_key,
                        field,
                        yes,
                    } => {
                        assert_eq!(selector_or_category, "credential");
                        assert_eq!(target_key.as_deref(), Some("github-prod"));
                        assert!(field.is_none());
                        assert!(yes);
                    }
                    _ => panic!("expected privacy delete"),
                },
                _ => panic!("expected privacy command"),
            }

            let field_delete = Cli::parse_from(preprocess_privacy_args(vec![
                OsString::from("ov"),
                OsString::from("privacy"),
                OsString::from("delete"),
                OsString::from("credential"),
                OsString::from("github-prod"),
                OsString::from("api_key"),
                OsString::from("--yes"),
            ]));
            match field_delete.command {
                Commands::Privacy { action } => match *action {
                    PrivacyCommands::Delete {
                        selector_or_category,
                        target_key,
                        field,
                        yes,
                    } => {
                        assert_eq!(selector_or_category, "credential");
                        assert_eq!(target_key.as_deref(), Some("github-prod"));
                        assert_eq!(field.as_deref(), Some("api_key"));
                        assert!(yes);
                    }
                    _ => panic!("expected privacy field delete"),
                },
                _ => panic!("expected privacy command"),
            }
        });
    }

    #[test]
    fn cli_parses_privacy_shortcut_as_get() {
        on_cli_parser_stack(|| {
            let cli = Cli::parse_from(preprocess_privacy_args(vec![
                OsString::from("ov"),
                OsString::from("privacy"),
                OsString::from("skill"),
                OsString::from("demo"),
            ]));

            match cli.command {
                Commands::Privacy { action } => match *action {
                    PrivacyCommands::Get {
                        category,
                        target_key,
                    } => {
                        assert_eq!(category, "skill");
                        assert_eq!(target_key, "demo");
                    }
                    _ => panic!("expected privacy get"),
                },
                _ => panic!("expected privacy command"),
            }
        });
    }

    #[test]
    fn cli_parses_privacy_shortcut_after_compact_without_value() {
        on_cli_parser_stack(|| {
            let cli = Cli::try_parse_from(preprocess_cli_args(vec![
                OsString::from("ov"),
                OsString::from("--compact"),
                OsString::from("privacy"),
                OsString::from("skill"),
                OsString::from("demo"),
            ]))
            .expect("--compact without a value should not consume the privacy command");

            assert!(cli.compact);
            match cli.command {
                Commands::Privacy { action } => match *action {
                    PrivacyCommands::Get {
                        category,
                        target_key,
                    } => {
                        assert_eq!(category, "skill");
                        assert_eq!(target_key, "demo");
                    }
                    _ => panic!("expected privacy get"),
                },
                _ => panic!("expected privacy command"),
            }

            let explicit_false = Cli::try_parse_from(preprocess_cli_args(vec![
                OsString::from("ov"),
                OsString::from("-c"),
                OsString::from("false"),
                OsString::from("privacy"),
                OsString::from("skill"),
                OsString::from("demo"),
            ]))
            .expect("-c false should keep its explicit bool value");
            assert!(!explicit_false.compact);
        });
    }
}