ssh-cli 0.5.4

Native Rust CLI that gives LLMs (Claude Code, Cursor, Windsurf) the ability to operate remote servers via SSH over stdin/stdout
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
// SPDX-License-Identifier: MIT OR Apache-2.0
// G-SECDEV-05: pure module — no `unsafe` permitted (crate root allows only OS FFI / test env).
#![forbid(unsafe_code)]
//! CLI argument definitions via `clap` derive and dispatcher.
//!
//! 1. CRUD de VPS — `vps add|list|remove|edit|show|path|doctor|export|import`
//! 2. `connect` — writes sibling `active` file (not a TOML field)
//! 3. One-shot execution — `exec|sudo-exec|su-exec|scp|sftp|tunnel|health-check`
//! 4. `secrets` — primary-key status/init/reencrypt (cifragem at-rest default)
//! 5. Completions / `commands` (agent command-tree discovery)
//!
//! ZERO `.env` at runtime. ZERO telemetry. One-shot cycle: start → dispatch → exit.

mod commands;
mod path_parse;
mod schema_cmd;
mod scp_args;
mod sftp_args;
mod vps_action;

pub use commands::{
    Command, LocaleAction, SecretsAction, TlsAcmeAccountAction, TlsAcmeAction, TlsAction,
    TlsMtlsAction,
};
pub(crate) use path_parse::{parse_exec_target, parse_hosts_list, parse_scp_target, ScpPathPlan};
pub use schema_cmd::run_schema;
pub use scp_args::ScpAction;
pub use sftp_args::SftpAction;
pub use vps_action::VpsAction;

use anyhow::Result;
use clap::{ArgAction, Parser, ValueHint};
use clap_complete::Shell;
use std::path::PathBuf;

/// Output format supported by the CLI.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum)]
pub enum OutputFormat {
    /// Human-readable text (default).
    #[default]
    Text,
    /// Structured JSON.
    Json,
}

/// Parses `--max-*-chars` values: decimal `usize`, or `none`/`0` for unlimited.
pub(crate) fn parse_cli_char_limit(s: &str) -> Result<usize, String> {
    let t = s.trim();
    if t.eq_ignore_ascii_case("none") || t == "0" {
        return Ok(0);
    }
    t.parse::<usize>()
        .map_err(|e| format!("invalid char limit '{s}': {e}"))
}

/// Shared SSH authentication overrides (flatten into exec/scp/tunnel/health-check).
///
/// Converted to domain strings at the command boundary (G-08/G-09/G-24).
#[derive(Debug, Clone, Default, clap::Args)]
#[command(next_help_heading = "Authentication")]
pub struct SshAuthArgs {
    /// SSH password override.
    #[arg(long, conflicts_with = "password_stdin")]
    pub password: Option<String>,
    /// Reads the SSH password from stdin.
    #[arg(long, action = ArgAction::SetTrue)]
    pub password_stdin: bool,
    /// Private key path override.
    #[arg(long, value_name = "PATH", value_hint = ValueHint::FilePath)]
    pub key: Option<PathBuf>,
    /// Key passphrase.
    #[arg(long, conflicts_with = "key_passphrase_stdin")]
    pub key_passphrase: Option<String>,
    /// Reads the key passphrase from stdin.
    #[arg(long, action = ArgAction::SetTrue)]
    pub key_passphrase_stdin: bool,
    /// Authenticate via ssh-agent (G-SSH-04). Requires `--agent-socket` on Unix.
    #[arg(long, action = ArgAction::SetTrue)]
    pub use_agent: bool,
    /// Agent socket (Unix) or named pipe (Windows). CLI/XDG only — not env store.
    #[arg(long, value_name = "PATH", value_hint = ValueHint::AnyPath)]
    pub agent_socket: Option<PathBuf>,
}
impl SshAuthArgs {
    /// Domain boundary: `PathBuf` → owned path string for VPS/SSH layers.
    #[must_use]
    pub fn key_path_string(&self) -> Option<String> {
        self.key.as_ref().map(|p| p.to_string_lossy().into_owned())
    }
}

/// Global ssh-cli arguments.
#[derive(Debug, Parser)]
#[command(
    name = crate::constants::APP_NAME,
    version = concat!(env!("CARGO_PKG_VERSION"), " (", env!("SSH_CLI_COMMIT_HASH"), ")"),
    about = "One-shot multi-host XDG Rust CLI for LLMs to operate servers over SSH.",
    long_about = "ssh-cli: lightweight one-shot binary (spawn→run→exit). Multi-host XDG storage without .env. \
Password or key auth. No telemetry.",
    after_help = "Examples:\n  \
ssh-cli vps add --name prod --host h.example --user deploy --key ~/.ssh/id_ed25519\n  \
printf '%s' \"$PASS\" | ssh-cli exec prod 'hostname' --json --password-stdin\n  \
ssh-cli scp upload prod ./a.bin /tmp/a.bin --json\n  \
ssh-cli tunnel prod 8080 127.0.0.1 80 --timeout-ms 60000 --json\n  \
ssh-cli vps export -o /tmp/hosts.toml",
    propagate_version = true,
    arg_required_else_help = true,
    subcommand_required = true,
    next_help_heading = "Global options"
)]
pub struct CliArgs {
    /// Forces the CLI language (BCP47; must negotiate to `en` or `pt-BR`).
    ///
    /// Examples: `en`, `en-US`, `pt-BR`, `pt`. Invalid tags fail clap validation.
    #[arg(
        long,
        global = true,
        value_name = "LOCALE",
        value_parser = crate::locale::parse_lang_cli_arg
    )]
    pub lang: Option<String>,

    /// Increases log verbosity on stderr (`-v` info, `-vv` debug, `-vvv` trace).
    ///
    /// Always scoped to this crate (G2/G14): never a bare global `debug`/`trace`
    /// that would enable `russh::client::encrypted` password dumps.
    #[arg(
        short,
        long,
        global = true,
        action = ArgAction::Count,
        conflicts_with = "quiet"
    )]
    pub verbose: u8,

    /// Suppresses non-JSON output (quiet mode).
    #[arg(
        short,
        long,
        global = true,
        action = ArgAction::SetTrue,
        conflicts_with = "verbose"
    )]
    pub quiet: bool,

    /// Configuration directory override (useful for tests).
    #[arg(
        long,
        global = true,
        value_name = "DIR",
        value_hint = ValueHint::DirPath
    )]
    pub config_dir: Option<PathBuf>,

    /// Disables colored output.
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    pub no_color: bool,

    /// Global output format (text, json). If omitted: JSON when stdout is not a TTY.
    #[arg(long, global = true, value_enum)]
    pub output_format: Option<OutputFormat>,

    /// Force JSON on stdout (agent; alias of `--output-format json`; G-AUD-01).
    ///
    /// Global — appears before or after subcommands. Subcommand fields use
    /// `from_global` so there is a single `--json` long name (clap uniqueness).
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    pub json: bool,

    /// Keep only these dotted paths in each record (CSV; alias `--fields`).
    ///
    /// Agent-native shaping: applied **before** serialization, so the full envelope is
    /// never built. Without it an agent must pipe through `jaq`, by which point the
    /// oversized payload has already been written and the tokens already spent.
    #[arg(
        long,
        global = true,
        alias = "fields",
        value_name = "PATHS",
        value_delimiter = ','
    )]
    pub select: Vec<String>,

    /// Keep records matching `key=value`, `key!=value` or `key~substring` (repeatable, AND).
    ///
    /// A malformed predicate is rejected at parse time rather than silently matching
    /// nothing — a typo must not be indistinguishable from an empty result.
    #[arg(long, global = true, value_name = "EXPR")]
    pub filter: Vec<String>,

    /// Emit at most N records (distinct from per-command query limits).
    #[arg(long, global = true, value_name = "N")]
    pub limit: Option<usize>,

    /// Sort records ascending by dotted path (numbers compare numerically).
    #[arg(long, global = true, value_name = "PATH")]
    pub sort: Option<String>,

    /// Drop later records repeating this dotted path's value.
    #[arg(long, global = true, value_name = "PATH")]
    pub dedupe_by: Option<String>,

    /// Replace the record collection with `{"count": N}`, counted after all filtering.
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    pub count_only: bool,

    /// Shorten strings longer than N **characters** (never bytes; UTF-8 stays valid).
    #[arg(long, global = true, value_name = "CHARS")]
    pub truncate_content: Option<usize>,

    /// Cap envelope size by dropping trailing records (never by slicing the JSON text).
    #[arg(long, global = true, value_name = "BYTES")]
    pub max_output_bytes: Option<usize>,

    /// Refuse to read stdin; fail fast instead of blocking on an absent human.
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    pub no_input: bool,

    /// Print the plan for a destructive operation and exit without executing it.
    ///
    /// Accepted only by commands that implement it (see
    /// [`supports_dry_run`]); anywhere else it is rejected with exit 64 rather
    /// than accepted and ignored. A global flag that silently does nothing on
    /// half the surface is worse than no flag at all — that is exactly how
    /// `--no-input` shipped broken on `vps add`.
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    pub dry_run: bool,

    /// Disables sudo-exec/su-exec for this invocation (alias --disableSudo).
    #[arg(long, global = true, alias = "disableSudo", action = ArgAction::SetTrue)]
    pub disable_sudo: bool,

    /// Replaces a diverging host key in TOFU known_hosts.
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    pub replace_host_key: bool,

    /// Allow plaintext secrets at rest (no auto `secrets.key`). Prefer for tests only.
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    pub allow_plaintext_secrets: bool,

    /// Path to a 64-hex primary-key file (overrides XDG `secrets.key` for this one-shot).
    #[arg(
        long,
        global = true,
        value_name = "PATH",
        value_hint = ValueHint::FilePath
    )]
    pub secrets_key_file: Option<PathBuf>,

    /// Prefer OS keyring for the primary key (CLI flag only; no product env store).
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    pub use_keyring: bool,

    /// Global default timeout in milliseconds for SSH ops (exec/scp/health-check).
    /// Local `--timeout` on a subcommand wins. Tunnel still requires `--timeout-ms`.
    #[arg(long, global = true, value_name = "MS")]
    pub timeout: Option<u64>,

    /// Cap concurrent multi-host SSH sessions / tunnel forwards (1..=MAX_CONCURRENCY).
    ///
    /// Default: auto from CPUs × I/O oversubscribe vs free RAM (see `concurrency`).
    /// Applies to `--all` fan-out and tunnel accepts (no env store; G-UNSAFE-14).
    #[arg(
        long,
        global = true,
        value_name = "N",
        value_parser = clap::value_parser!(u16).range(1..=(crate::constants::MAX_CONCURRENCY as i64))
    )]
    pub max_concurrency: Option<u16>,

    /// Stop admitting new multi-host units after the first failure (G-O1).
    ///
    /// Default: continue all hosts (agent-friendly partial success). In-flight
    /// units still finish; never-started hosts are omitted from batch results
    /// unless callers pad skipped rows.
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    pub fail_fast: bool,

    /// Max concurrent SCP file transfers on **one** SSH session (G-O4).
    ///
    /// Default: 1 (serial multi-file, session reuse). Values >1 open parallel
    /// SCP channels on the same session (bounded). Env: not used; CLI only.
    #[arg(
        long,
        global = true,
        value_name = "N",
        value_parser = clap::value_parser!(u16).range(1..=(crate::constants::MAX_CONCURRENCY as i64))
    )]
    pub scp_file_concurrency: Option<u16>,

    /// Subcommand to run.
    #[command(subcommand)]
    pub command: Command,
}

/// Parses CLI arguments.
#[must_use]
pub fn parse_args() -> CliArgs {
    CliArgs::parse()
}

/// Merges local subcommand timeout with global `--timeout` (local wins).
#[must_use]
pub fn effective_timeout(local: Option<u64>, global: Option<u64>) -> Option<u64> {
    local.or(global)
}

/// Merges local/global timeout and refines to [`crate::domain::TimeoutMs`] (G-TYPE-18).
///
/// # Errors
/// Returns domain error text when the effective value is out of range.
pub fn effective_timeout_ms(
    local: Option<u64>,
    global: Option<u64>,
) -> Result<Option<crate::domain::TimeoutMs>, String> {
    match effective_timeout(local, global) {
        None => Ok(None),
        Some(ms) => crate::domain::TimeoutMs::try_new(ms)
            .map(Some)
            .map_err(|e| e.to_string()),
    }
}

/// Maps CLI `--step` strings into refined remote commands (G-TYPE-19).
///
/// # Errors
/// Returns domain error text when any step is empty or contains NUL.
pub fn parse_remote_steps(steps: Vec<String>) -> Result<Vec<crate::domain::RemoteCommand>, String> {
    steps
        .into_iter()
        .map(|s| crate::domain::RemoteCommand::try_new(s).map_err(|e| e.to_string()))
        .collect()
}

/// Installs stderr tracing before clap parse (delegates to [`crate::telemetry`]).
#[inline]
pub fn bootstrap_logs() {
    crate::telemetry::bootstrap_logs();
}

/// Reloads the tracing filter from CLI flags (delegates to [`crate::telemetry`]).
#[inline]
pub fn initialize_logs(args: &CliArgs) {
    crate::telemetry::initialize_logs(args.verbose);
}

/// Writes shell completions to stdout.
///
/// GAP-SSH-CLI-003 / G-IO-08: broken pipe (EPIPE) does not panic — returns
/// [`crate::errors::SshCliError::Io`] so `main` exits **141**.
///
/// # Errors
/// Stdout write failures (including BrokenPipe).
pub fn generate_completions(shell: Shell) -> Result<()> {
    use clap::CommandFactory;
    use std::io::Write;
    let mut cmd = CliArgs::command();
    let mut buf: Vec<u8> = Vec::new();
    clap_complete::generate(shell, &mut cmd, crate::constants::APP_NAME, &mut buf);
    let mut out = std::io::stdout().lock();
    out.write_all(&buf).and_then(|()| out.flush())?;
    Ok(())
}

/// Builds a JSON command tree from the clap `Command` graph (G-IO-10).
#[must_use]
pub fn command_tree_json() -> serde_json::Value {
    use clap::CommandFactory;
    fn walk(cmd: &clap::Command) -> serde_json::Value {
        let name = cmd.get_name().to_string();
        let about = cmd.get_about().map(|s| s.to_string());
        let mut children = Vec::new();
        for sub in cmd.get_subcommands() {
            if sub.is_hide_set() {
                continue;
            }
            children.push(walk(sub));
        }
        serde_json::json!({
            "name": name,
            "about": about,
            "subcommands": children,
        })
    }
    let root = CliArgs::command();
    serde_json::json!({
        "ok": true,
        "event": "commands",
        "bin": root.get_name(),
        "version": env!("CARGO_PKG_VERSION"),
        "tree": walk(&root),
    })
}

/// Renders a man page for `ssh-cli` (G-12 / clap_mangen).
pub fn render_manpage() -> Result<Vec<u8>, std::io::Error> {
    use clap::CommandFactory;
    use std::io::Write;
    let cmd = CliArgs::command();
    let man = clap_mangen::Man::new(cmd);
    let mut buf = Vec::new();
    man.render(&mut buf)?;
    // Ensure trailing newline for POSIX man consumers.
    if !buf.ends_with(b"\n") {
        buf.write_all(b"\n")?;
    }
    Ok(buf)
}

/// Resolves a secret from `--*-stdin` or an argv value into [`secrecy::SecretString`].
///
/// G-SECDEV-01: wrap credentials at the CLI boundary — never forward bare
/// `String` passwords into exec/scp/tunnel/health overrides.
pub(crate) fn read_stdin_if(
    flag: bool,
    value: Option<String>,
) -> Result<Option<secrecy::SecretString>> {
    if flag {
        // C2: `--no-input` refuses stdin declaratively. Without it, an agent that
        // passed `--password-stdin` with nothing piped in would block forever waiting
        // on a human who is not there — the failure mode is a hung process rather than
        // an error, which is the worst outcome for unattended automation.
        //
        // The refusal lives inside `read_secret_stdin` so every caller inherits it;
        // duplicating it here would leave `vps add`/`vps edit` uncovered again.
        Ok(Some(crate::vps::read_secret_stdin()?))
    } else {
        Ok(value.map(secrecy::SecretString::from))
    }
}

/// Process-wide `--no-input` switch.
static NO_INPUT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Installs the `--no-input` policy for this one-shot process.
pub fn set_no_input(value: bool) {
    NO_INPUT.store(value, std::sync::atomic::Ordering::Relaxed);
}

/// Whether stdin reads must fail instead of blocking.
#[must_use]
pub fn is_no_input() -> bool {
    NO_INPUT.load(std::sync::atomic::Ordering::Relaxed)
}

/// Resolves the tunnel mode from the mutually exclusive mode flags.
///
/// Pure: no registry, no socket, no clock. The positional arguments mean
/// different things per mode — `remote_host` is a destination for a local
/// forward and a *server bind address* under `--reverse` — so getting this wrong
/// points the tunnel somewhere the caller never asked for. Keeping the decision
/// in one testable function is what lets every combination be covered without a
/// server.
///
/// # Errors
/// [`crate::errors::SshCliError::InvalidArgument`] (exit 64) when a mode is given
/// arguments it cannot use, or is missing arguments it requires.
pub fn resolve_tunnel_mode(
    socks5: bool,
    remote_socket: Option<String>,
    reverse: bool,
    remote_host: Option<String>,
    remote_port: Option<u16>,
) -> Result<crate::tunnel::TunnelMode, crate::errors::SshCliError> {
    use crate::errors::SshCliError::InvalidArgument;
    use crate::tunnel::TunnelMode;

    let positional_given = remote_host.is_some() || remote_port.is_some();

    if socks5 {
        if positional_given {
            return Err(InvalidArgument(
                "--socks5 chooses a destination per connection; remove REMOTE_HOST and REMOTE_PORT"
                    .to_string(),
            ));
        }
        return Ok(TunnelMode::Socks5);
    }

    if let Some(socket_path) = remote_socket {
        if positional_given {
            return Err(InvalidArgument(
                "--remote-socket replaces the destination; remove REMOTE_HOST and REMOTE_PORT"
                    .to_string(),
            ));
        }
        return Ok(TunnelMode::StreamLocal { socket_path });
    }

    let (Some(host), Some(port)) = (remote_host, remote_port) else {
        return Err(InvalidArgument(
            "tunnel requires REMOTE_HOST and REMOTE_PORT unless --socks5 or --remote-socket \
             is used"
                .to_string(),
        ));
    };

    if reverse {
        // Port 0 is meaningful here and only here: the server allocates and reports
        // back, exactly like a local ephemeral bind.
        return Ok(TunnelMode::Reverse {
            remote_bind: host,
            remote_port: port,
        });
    }

    if port == 0 {
        return Err(InvalidArgument(
            "REMOTE_PORT 0 is only valid with --reverse, where the server allocates the port"
                .to_string(),
        ));
    }
    Ok(TunnelMode::Local {
        remote_host: host,
        remote_port: port,
    })
}

/// Process-wide `--dry-run` switch.
static DRY_RUN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Installs the `--dry-run` policy for this one-shot process.
pub fn set_dry_run(value: bool) {
    DRY_RUN.store(value, std::sync::atomic::Ordering::Relaxed);
}

/// Whether destructive operations must emit a plan instead of executing.
#[must_use]
pub fn is_dry_run() -> bool {
    DRY_RUN.load(std::sync::atomic::Ordering::Relaxed)
}

/// Whether this command implements `--dry-run`.
///
/// C2 covers the operations that destroy state without a prior read: registry
/// removal and import, remote unlink and rmdir, and the two `secrets` writes
/// that can invalidate every stored credential at once. Transfers and `exec`
/// are deliberately absent — their effect is the remote command itself, which
/// this CLI cannot preview without running it.
#[must_use]
pub fn supports_dry_run(command: &Command) -> bool {
    use crate::cli::{SecretsAction, SftpAction, VpsAction};
    match command {
        Command::Vps { action } => {
            matches!(action, VpsAction::Remove { .. } | VpsAction::Import { .. })
        }
        Command::Sftp { action, .. } => {
            matches!(action, SftpAction::Rm { .. } | SftpAction::Rmdir { .. })
        }
        Command::Secrets { action } => matches!(
            action,
            SecretsAction::Init { .. } | SecretsAction::Reencrypt { .. }
        ),
        _ => false,
    }
}

/// Rejects `--dry-run` on a command that cannot honour it.
///
/// # Errors
/// [`crate::errors::SshCliError::InvalidArgument`] (exit 64) when the flag was
/// passed to an unsupported command.
pub fn guard_dry_run_supported(command: &Command) -> Result<(), crate::errors::SshCliError> {
    if !is_dry_run() || supports_dry_run(command) {
        return Ok(());
    }
    Err(crate::errors::SshCliError::InvalidArgument(
        "--dry-run is not implemented for this command; it is accepted only by \
         `vps remove`, `vps import`, `sftp rm`, `sftp rmdir`, `secrets init` and \
         `secrets reencrypt`"
            .to_string(),
    ))
}

/// Emits the plan for a destructive operation and reports whether to stop.
///
/// Returns `true` when the caller must return without mutating anything. The
/// plan always reaches stdout as JSON, even in text mode: the point of a
/// preview is that a machine can diff it against what it intended, and prose
/// cannot be diffed.
///
/// # Errors
/// stdout write failures (including `BrokenPipe`).
pub fn dry_run_stop(
    operation: &str,
    fields: &[(&str, serde_json::Value)],
) -> Result<bool, crate::errors::SshCliError> {
    if !is_dry_run() {
        return Ok(false);
    }
    let mut map = std::collections::BTreeMap::new();
    map.insert("operation".to_string(), serde_json::json!(operation));
    map.insert("dry_run".to_string(), serde_json::json!(true));
    map.insert("executed".to_string(), serde_json::json!(false));
    for (k, v) in fields {
        map.insert((*k).to_string(), v.clone());
    }
    crate::json_wire::print_json_line(&crate::json_wire::SuccessEnvelope::new("dry-run", map))
        .map_err(crate::errors::SshCliError::Io)?;
    Ok(true)
}

/// Warns only when a secret value is present on argv (not stdin flags).
///
/// G-AUD-08: inspect concrete `Option` fields — never `Debug` string heuristics
/// (`password: None` + any `Some(` elsewhere was a false positive).
pub(crate) fn warn_if_password_argv(args: &CliArgs) {
    let has = match &args.command {
        Command::Exec { auth, .. }
        | Command::HealthCheck { auth, .. }
        | Command::Tunnel { auth, .. } => auth.password.is_some() || auth.key_passphrase.is_some(),
        Command::SudoExec {
            auth,
            sudo_password,
            ..
        } => auth.password.is_some() || auth.key_passphrase.is_some() || sudo_password.is_some(),
        Command::SuExec {
            auth, su_password, ..
        } => auth.password.is_some() || auth.key_passphrase.is_some() || su_password.is_some(),
        Command::Scp { action } => match action {
            ScpAction::Upload { auth, .. } | ScpAction::Download { auth, .. } => {
                auth.password.is_some() || auth.key_passphrase.is_some()
            }
        },
        Command::Sftp { action } => sftp_auth_has_argv_secret(action),
        Command::Vps { action } => vps_action_has_argv_secret(action),
        _ => false,
    };

    if has {
        crate::output::print_warning(
            "a password-like value was passed on the command line (visible in process lists); prefer --*-stdin",
        );
    }
}

fn sftp_auth_has_argv_secret(action: &SftpAction) -> bool {
    let auth = match action {
        SftpAction::Upload { auth, .. }
        | SftpAction::Download { auth, .. }
        | SftpAction::Ls { auth, .. }
        | SftpAction::Mkdir { auth, .. }
        | SftpAction::Rmdir { auth, .. }
        | SftpAction::Rm { auth, .. }
        | SftpAction::Rename { auth, .. }
        | SftpAction::Stat { auth, .. } => auth,
    };
    auth.password.is_some() || auth.key_passphrase.is_some()
}

fn vps_action_has_argv_secret(action: &VpsAction) -> bool {
    match action {
        VpsAction::Add {
            password,
            key_passphrase,
            sudo_password,
            su_password,
            ..
        }
        | VpsAction::Edit {
            password,
            key_passphrase,
            sudo_password,
            su_password,
            ..
        } => {
            password.is_some()
                || key_passphrase.is_some()
                || sudo_password.is_some()
                || su_password.is_some()
        }
        _ => false,
    }
}

/// Resolves output format: `--json` global / explicit enum > non-TTY JSON > Text.
///
/// G-AUD-01/12: no `SSH_CLI_FORCE_TEXT` env store — use `--output-format text`.
#[must_use]
pub fn resolve_format(explicit: Option<OutputFormat>) -> OutputFormat {
    if let Some(f) = explicit {
        return f;
    }
    if !std::io::IsTerminal::is_terminal(&std::io::stdout()) {
        OutputFormat::Json
    } else {
        OutputFormat::Text
    }
}

/// Resolves format from global `--json` + `--output-format` (G-AUD-01).
///
/// `# Errors`
/// `--json` together with `--output-format text`.
pub fn resolve_format_from_cli(
    json: bool,
    explicit: Option<OutputFormat>,
) -> Result<OutputFormat, crate::errors::SshCliError> {
    // G-AUD-01: `--json` always wins (including when tests pass `--output-format text`
    // for human stderr isolation while still requesting JSON success bodies).
    if json {
        return Ok(OutputFormat::Json);
    }
    Ok(resolve_format(explicit))
}

mod dispatch;

pub use dispatch::{dispatch, dispatch_impl};

#[cfg(test)]
mod tests;