sysknife-cli 0.28.0

Approval-gated AI system administration CLI and MCP server
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
//! CLI argument parser for the `sysknife` binary.
//!
//! Structure:
//! - [`Cli`] — top-level struct carrying all global flags
//! - [`Command`] — named subcommands; [`Command::Intent`] catches free-form words
//! - [`HistoryArgs`] — arguments specific to `sysknife history`
//! - [`MaxRiskArg`] — `--max-risk` value-enum bridging to `approval::MaxRisk`
//!
//! Free-form intents work because `Command::Intent` uses `external_subcommand`:
//! any first argument that does not match a named subcommand is captured there.
//! `sysknife "check disk usage"` and `sysknife check disk usage` both produce an
//! `Intent` variant; the words are joined with spaces to form the intent string.

use std::ffi::OsString;

use clap::{Args, Parser, Subcommand, ValueEnum};

use crate::approval::MaxRisk;

/// Linux System Management CLI.
///
/// With no arguments, starts an interactive REPL.
/// Pass a natural-language intent to plan and execute in one shot.
#[derive(Parser, Debug)]
#[command(name = "sysknife", version, about = "Linux System Management CLI")]
pub struct Cli {
    /// Auto-approve steps up to the effective risk ceiling.
    ///
    /// Alone, approves LOW only. With `--max-risk medium`, approves up to
    /// MEDIUM. HIGH steps always require explicit human confirmation —
    /// `--yes` cannot auto-approve them regardless of `--max-risk`.
    #[arg(long, global = true)]
    pub yes: bool,

    /// Maximum risk level to allow; abort if the plan exceeds this ceiling.
    #[arg(long, value_name = "LEVEL", global = true)]
    pub max_risk: Option<MaxRiskArg>,

    /// Fail immediately if any step would require interactive approval.
    #[arg(long, global = true)]
    pub non_interactive: bool,

    /// Display the plan without executing anything.
    #[arg(long, global = true)]
    pub dry_run: bool,

    /// Emit NDJSON instead of human-readable output.
    #[arg(long, global = true)]
    pub json: bool,

    /// Stop waiting in the CLI after this many seconds; daemon work may continue.
    #[arg(long, value_name = "SECS", global = true)]
    pub timeout: Option<u64>,

    /// Append all output to FILE in addition to stdout.
    #[arg(long, value_name = "FILE", global = true)]
    pub log_to: Option<std::path::PathBuf>,

    /// Confirm each step individually instead of the whole plan at once.
    #[arg(long, global = true)]
    pub step_by_step: bool,

    /// Execute HIGH-risk steps with no human confirmation.
    ///
    /// Requires `SYSKNIFE_I_ACCEPT_UNATTENDED_ROOT=1` in the environment as
    /// well; the flag on its own refuses to run. It raises the ceiling that
    /// `--yes` is clamped to and implies nothing else, so an unattended run
    /// passes `--yes --max-risk high` explicitly. Without `--yes` nothing is
    /// auto-approved and the run stops at the first prompt.
    ///
    /// This lifts the approval gate and nothing else. Typed actions,
    /// parameter validation, the polkit allowlist, the CLI/daemon risk-skew
    /// abort and the signed audit chain all still apply, and every step run
    /// this way is recorded as unattended inside the signed audit row.
    #[arg(long, global = true)]
    pub dangerously_skip_approval: bool,

    #[command(subcommand)]
    pub command: Option<Command>,
}

/// Named subcommands for `sysknife`.
///
/// Any first argument that does not match a named subcommand is collected
/// by `Command::Intent` via clap's `external_subcommand` mechanism.
#[derive(Subcommand, Debug)]
pub enum Command {
    /// Check daemon connectivity and print configuration.
    Doctor,

    /// Query past SysKnife execution history.
    History(HistoryArgs),

    /// Approve one daemon-persisted preview and print its one-time receipt.
    Approve {
        /// Transaction ID returned by `sysknife_plan`.
        transaction_id: String,

        /// Print the complete proposed change, with no line or length caps.
        ///
        /// The default view is capped so a long change cannot scroll the action
        /// name and risk level off the screen before you answer. When the cap
        /// hides anything, approval is refused and points you here rather than
        /// accepting consent to text you were not shown. With this flag the
        /// change is printed in full and the decision context is printed
        /// *after* it, so the cap has nothing left to protect.
        #[arg(long)]
        full: bool,
    },

    /// Print shell completion script to stdout.
    Completions {
        /// Target shell.
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },

    /// Start an MCP server over stdio.
    ///
    /// Exposes the five planning/audit tools plus catalogue-backed direct
    /// read-only queries for the detected distro. Mutating actions, including
    /// the Low-risk `AptUpdate`, stay behind plan/approve/execute. The stdio
    /// contract test pins this boundary.
    ///
    /// Add to `claude_desktop_config.json`:
    ///   { "mcpServers": { "sysknife": { "command": "sysknife", "args": ["mcp-server"] } } }
    #[command(name = "mcp-server")]
    McpServer,

    /// Audit log integrity tools.
    Audit {
        #[command(subcommand)]
        command: AuditCommand,
    },

    /// Execute a natural-language intent.
    ///
    /// Words not matching any named subcommand are captured here.
    /// `sysknife "check disk usage"` and `sysknife check disk usage` both work.
    #[command(external_subcommand)]
    Intent(Vec<OsString>),
}

impl Command {
    /// If this command is `Intent`, join the captured words into a single
    /// intent string. Returns `None` for any other variant.
    pub fn intent_string(&self) -> Option<String> {
        match self {
            Command::Intent(words) => Some(
                words
                    .iter()
                    .map(|w| w.to_string_lossy())
                    .collect::<Vec<_>>()
                    .join(" "),
            ),
            _ => None,
        }
    }
}

/// `sysknife audit <subcommand>` subcommands.
#[derive(Subcommand, Debug, Clone)]
pub enum AuditCommand {
    /// Export the stored signed audit-chain rows as JSON.
    Export(AuditExportArgs),

    /// Verify the tamper-evident Ed25519-signed hash chain over the audit log.
    ///
    /// Exits 0 if the chain is intact, 1 if any row is broken, and 2 if the
    /// chain cannot be verified (missing key file, retired key not on disk,
    /// unreadable database, empty unanchored log, etc.). The 1/2 split matters:
    /// a CI pipeline expecting 0 or 1 must not silently pass on a missing key file.
    Verify(AuditVerifyArgs),

    /// Anchor the current chain tip as a signed checkpoint into an external
    /// append-only database, then verify all anchored checkpoints against the
    /// local chain (detects tail-truncation and rewrite).
    Checkpoint(AuditCheckpointArgs),
}

/// Arguments for `sysknife audit export`.
#[derive(Args, Debug, Clone)]
pub struct AuditExportArgs {
    /// Export rows recorded at or after this RFC 3339 datetime.
    #[arg(long, value_name = "DATETIME")]
    pub since: Option<String>,

    /// Maximum number of rows to export. By default every matching row is emitted.
    #[arg(long, value_name = "N")]
    pub limit: Option<u32>,
}

/// Arguments for `sysknife audit verify`.
#[derive(Args, Debug, Clone)]
pub struct AuditVerifyArgs {
    /// Emit a machine-readable JSON report instead of human-friendly text.
    #[arg(long)]
    pub json: bool,

    /// Verify using only the exported public key file (`<audit-key>.pub`),
    /// without the private key. This is the third-party / auditor path: it
    /// proves the chain is intact and unforged without trusting the verifier
    /// with the ability to sign. Without this flag, verification loads the
    /// private key. Supported for both SQLite and PostgreSQL backends.
    #[arg(long, value_name = "FILE")]
    pub pubkey: Option<std::path::PathBuf>,
}

/// Arguments for `sysknife audit checkpoint`.
#[derive(Args, Debug, Clone)]
pub struct AuditCheckpointArgs {
    /// Postgres URL of the external append-only checkpoint database, e.g.
    /// `postgres://user@host/dbname`. Prefer the `SYSKNIFE_CHECKPOINT_DB`
    /// environment variable over this flag so credentials are not exposed on
    /// the command line (visible via `ps` and shell history). Anchoring the
    /// tip off-box is what makes truncation/rewrite of the local chain
    /// detectable.
    #[arg(long, value_name = "URL")]
    pub db: Option<String>,
}

/// Arguments for `sysknife history`.
#[derive(Args, Debug, Clone)]
pub struct HistoryArgs {
    /// Filter by job status (succeeded, failed, canceled, …).
    #[arg(long, value_name = "STATUS")]
    pub status: Option<String>,

    /// Filter by action name.
    #[arg(long, value_name = "ACTION")]
    pub action: Option<String>,

    /// Show only entries after this ISO-8601 date or UTC-qualified datetime.
    #[arg(long, value_name = "DATETIME")]
    pub since: Option<String>,

    /// Maximum number of entries to return.
    #[arg(long, default_value = "20", value_name = "N")]
    pub limit: u32,
}

/// Clap value-enum for `--max-risk`.
///
/// Converts to [`MaxRisk`] via [`From`] so the rest of the codebase
/// uses the domain type directly.
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub enum MaxRiskArg {
    Low,
    Medium,
    High,
}

impl From<MaxRiskArg> for MaxRisk {
    fn from(arg: MaxRiskArg) -> MaxRisk {
        match arg {
            MaxRiskArg::Low => MaxRisk::Low,
            MaxRiskArg::Medium => MaxRisk::Medium,
            MaxRiskArg::High => MaxRisk::High,
        }
    }
}

// ---------------------------------------------------------------------------
// UnattendedConsent
// ---------------------------------------------------------------------------

/// The environment variable that must accompany `--dangerously-skip-approval`.
pub const UNATTENDED_CONSENT_VAR: &str = "SYSKNIFE_I_ACCEPT_UNATTENDED_ROOT";

/// The value that variable must hold. Anything else is treated as unset, so a
/// stray `=0` or `=false` left in a profile cannot arm the override.
pub const UNATTENDED_CONSENT_VALUE: &str = "1";

/// Proof that both halves of the two-key rule were supplied.
///
/// The type exists so `skip_approval` cannot be set from a bare boolean at a
/// call site. `ApprovalPolicy::new_unattended` takes the boolean, but the only
/// `true` in the binary comes from [`UnattendedConsent::resolve`].
#[derive(Debug, PartialEq, Eq)]
pub enum UnattendedConsent {
    /// Neither half supplied. Normal operation.
    NotRequested,
    /// Both halves supplied. The approval gate is lifted for this run.
    Granted,
    /// The flag without the variable.
    FlagWithoutEnv,
    /// The variable without the flag. Not an error, but worth saying: an
    /// environment left armed is exactly what the two-key rule guards against.
    EnvWithoutFlag,
}

impl UnattendedConsent {
    /// Resolve the two keys. `env_value` is the raw `SYSKNIFE_I_ACCEPT_UNATTENDED_ROOT`
    /// reading, passed in rather than read here so this stays a pure function.
    pub fn resolve(flag: bool, env_value: Option<&str>) -> Self {
        let env_ok = env_value == Some(UNATTENDED_CONSENT_VALUE);
        match (flag, env_ok) {
            (true, true) => Self::Granted,
            (true, false) => Self::FlagWithoutEnv,
            (false, true) => Self::EnvWithoutFlag,
            (false, false) => Self::NotRequested,
        }
    }

    /// Read the environment and resolve.
    pub fn from_env(flag: bool) -> Self {
        let raw = std::env::var(UNATTENDED_CONSENT_VAR).ok();
        Self::resolve(flag, raw.as_deref())
    }

    /// Whether the approval gate is lifted. The only place that answers `true`.
    pub fn is_granted(&self) -> bool {
        matches!(self, Self::Granted)
    }

    /// The message to print when the run cannot proceed, or `None` when it can.
    pub fn refusal(&self) -> Option<String> {
        match self {
            Self::FlagWithoutEnv => Some(format!(
                "--dangerously-skip-approval was passed but {UNATTENDED_CONSENT_VAR} is not set to \
                 {UNATTENDED_CONSENT_VALUE}.\n\nThis flag lets an LLM's plan execute HIGH-risk \
                 actions as root with nobody watching. It needs two keys on purpose, so that \
                 neither a flag left in a script nor a variable left in a profile is enough on its \
                 own.\n\nIf you meant it:  {UNATTENDED_CONSENT_VAR}={UNATTENDED_CONSENT_VALUE} \
                 sysknife --dangerously-skip-approval ..."
            )),
            _ => None,
        }
    }
}

#[cfg(test)]
mod unattended_consent_tests {
    use super::*;

    #[test]
    fn both_keys_grant() {
        assert_eq!(
            UnattendedConsent::resolve(true, Some("1")),
            UnattendedConsent::Granted
        );
        assert!(UnattendedConsent::resolve(true, Some("1")).is_granted());
    }

    #[test]
    fn the_flag_alone_refuses_and_says_why() {
        let c = UnattendedConsent::resolve(true, None);
        assert_eq!(c, UnattendedConsent::FlagWithoutEnv);
        assert!(!c.is_granted());
        let msg = c.refusal().expect("a refusal must carry a message");
        assert!(
            msg.contains(UNATTENDED_CONSENT_VAR),
            "names the variable: {msg}"
        );
        assert!(msg.contains("as root"), "says what is at stake: {msg}");
    }

    #[test]
    fn the_variable_alone_does_not_arm_anything() {
        let c = UnattendedConsent::resolve(false, Some("1"));
        assert_eq!(c, UnattendedConsent::EnvWithoutFlag);
        assert!(
            !c.is_granted(),
            "an armed profile must not skip approval on its own"
        );
        assert!(c.refusal().is_none(), "it is not an error, only inert");
    }

    #[test]
    fn neither_key_is_ordinary_operation() {
        let c = UnattendedConsent::resolve(false, None);
        assert_eq!(c, UnattendedConsent::NotRequested);
        assert!(!c.is_granted());
        assert!(c.refusal().is_none());
    }

    // A profile carrying `=0`, `=false`, `=yes` or an empty value is the shape
    // that would otherwise arm this by accident. Only the exact string counts.
    #[test]
    fn only_the_exact_value_counts() {
        for v in ["0", "false", "true", "yes", "", " 1", "1 ", "01", "TRUE"] {
            assert_eq!(
                UnattendedConsent::resolve(true, Some(v)),
                UnattendedConsent::FlagWithoutEnv,
                "{v:?} must not satisfy the environment half"
            );
        }
    }

    #[test]
    fn the_flag_parses_and_defaults_off() {
        let cli = Cli::parse_from(["sysknife", "check disk"]);
        assert!(!cli.dangerously_skip_approval);
        let cli = Cli::parse_from(["sysknife", "--dangerously-skip-approval", "check disk"]);
        assert!(cli.dangerously_skip_approval);
    }

    // There is deliberately no short form and no abbreviation. Typing it has to
    // be a decision, which is the whole safeguard.
    #[test]
    fn the_flag_has_no_short_form() {
        assert!(Cli::try_parse_from(["sysknife", "-d", "check disk"]).is_err());
        assert!(Cli::try_parse_from(["sysknife", "--skip-approval", "check disk"]).is_err());
        assert!(Cli::try_parse_from(["sysknife", "--dangerously-skip", "check disk"]).is_err());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;

    #[test]
    fn no_args_parses_with_no_command_and_no_flags() {
        let cli = Cli::try_parse_from(["sysknife"]).unwrap();
        assert!(cli.command.is_none());
        assert!(!cli.yes);
        assert!(!cli.dry_run);
        assert!(!cli.non_interactive);
        assert!(!cli.json);
        assert!(!cli.step_by_step);
        assert!(cli.timeout.is_none());
        assert!(cli.max_risk.is_none());
        assert!(cli.log_to.is_none());
    }

    #[test]
    fn multi_word_intent_captured_as_intent_variant() {
        let cli = Cli::try_parse_from(["sysknife", "check", "disk", "usage"]).unwrap();
        let intent = cli.command.as_ref().unwrap().intent_string().unwrap();
        assert_eq!(intent, "check disk usage");
    }

    #[test]
    fn quoted_single_arg_intent_captured_verbatim() {
        let cli = Cli::try_parse_from(["sysknife", "check disk usage"]).unwrap();
        let intent = cli.command.as_ref().unwrap().intent_string().unwrap();
        assert_eq!(intent, "check disk usage");
    }

    #[test]
    fn yes_flag_parsed() {
        let cli = Cli::try_parse_from(["sysknife", "--yes", "intent"]).unwrap();
        assert!(cli.yes);
    }

    #[test]
    fn max_risk_low_medium_high_parsed() {
        for (input, expected) in [
            ("low", MaxRiskArg::Low),
            ("medium", MaxRiskArg::Medium),
            ("high", MaxRiskArg::High),
        ] {
            let cli = Cli::try_parse_from(["sysknife", "--max-risk", input]).unwrap();
            assert_eq!(cli.max_risk.unwrap(), expected);
        }
    }

    #[test]
    fn max_risk_arg_converts_to_max_risk() {
        assert_eq!(MaxRisk::from(MaxRiskArg::Low), MaxRisk::Low);
        assert_eq!(MaxRisk::from(MaxRiskArg::Medium), MaxRisk::Medium);
        assert_eq!(MaxRisk::from(MaxRiskArg::High), MaxRisk::High);
    }

    #[test]
    fn dry_run_and_non_interactive_parsed() {
        let cli =
            Cli::try_parse_from(["sysknife", "--dry-run", "--non-interactive", "intent"]).unwrap();
        assert!(cli.dry_run);
        assert!(cli.non_interactive);
    }

    #[test]
    fn json_and_timeout_and_step_by_step_parsed() {
        let cli = Cli::try_parse_from([
            "sysknife",
            "--json",
            "--timeout",
            "30",
            "--step-by-step",
            "intent",
        ])
        .unwrap();
        assert!(cli.json);
        assert_eq!(cli.timeout, Some(30));
        assert!(cli.step_by_step);
    }

    #[test]
    fn log_to_path_parsed() {
        let cli =
            Cli::try_parse_from(["sysknife", "--log-to", "/tmp/sysknife.log", "intent"]).unwrap();
        assert_eq!(
            cli.log_to.as_deref(),
            Some(std::path::Path::new("/tmp/sysknife.log"))
        );
    }

    /// The refusal `sysknife approve` returns on a truncated view tells the
    /// operator to re-run with `--full`. A message naming a flag the parser does
    /// not accept sends them in a circle, which is the same defect as
    /// `a_missing_terminal_is_not_reported_as_a_flag_the_user_never_passed` in
    /// error.rs, one layer further out.
    #[test]
    fn approve_accepts_the_full_flag_the_truncation_refusal_names() {
        let refusal = crate::error::CliError::ApprovalViewIncomplete {
            transaction_id: "tx-abc123".to_string(),
            withheld: 7,
            shortened_note: String::new(),
        }
        .to_string();
        assert!(
            refusal.contains("--full"),
            "the refusal must name the escape hatch: {refusal}"
        );

        let cli = Cli::try_parse_from(["sysknife", "approve", "tx-abc123", "--full"])
            .expect("--full must parse, because the refusal above tells operators to use it");
        match cli.command {
            Some(Command::Approve {
                ref transaction_id,
                full,
            }) => {
                assert_eq!(transaction_id, "tx-abc123");
                assert!(full);
            }
            other => panic!("expected Approve, got {other:?}"),
        }
    }

    #[test]
    fn approve_defaults_to_the_bounded_view() {
        let cli = Cli::try_parse_from(["sysknife", "approve", "tx-abc123"]).unwrap();
        match cli.command {
            Some(Command::Approve { full, .. }) => assert!(
                !full,
                "the bounded view is the default; --full is the deliberate escape"
            ),
            other => panic!("expected Approve, got {other:?}"),
        }
    }

    #[test]
    fn doctor_subcommand_parsed() {
        let cli = Cli::try_parse_from(["sysknife", "doctor"]).unwrap();
        assert!(matches!(cli.command, Some(Command::Doctor)));
    }

    #[test]
    fn history_subcommand_default_limit() {
        let cli = Cli::try_parse_from(["sysknife", "history"]).unwrap();
        match cli.command {
            Some(Command::History(args)) => {
                assert_eq!(args.limit, 20);
                assert!(args.status.is_none());
                assert!(args.action.is_none());
                assert!(args.since.is_none());
            }
            other => panic!("expected Command::History, got {other:?}"),
        }
    }

    #[test]
    fn history_subcommand_with_all_flags() {
        let cli = Cli::try_parse_from([
            "sysknife",
            "history",
            "--limit",
            "5",
            "--status",
            "succeeded",
            "--action",
            "InstallPackages",
            "--since",
            "2026-01-01T00:00:00Z",
        ])
        .unwrap();
        match cli.command {
            Some(Command::History(args)) => {
                assert_eq!(args.limit, 5);
                assert_eq!(args.status.as_deref(), Some("succeeded"));
                assert_eq!(args.action.as_deref(), Some("InstallPackages"));
                assert_eq!(args.since.as_deref(), Some("2026-01-01T00:00:00Z"));
            }
            other => panic!("expected Command::History, got {other:?}"),
        }
    }

    #[test]
    fn audit_export_subcommand_with_filters() {
        let cli = Cli::try_parse_from([
            "sysknife",
            "audit",
            "export",
            "--since",
            "2026-01-01T00:00:00Z",
            "--limit",
            "5",
        ])
        .unwrap();
        match cli.command {
            Some(Command::Audit {
                command: AuditCommand::Export(args),
            }) => {
                assert_eq!(args.since.as_deref(), Some("2026-01-01T00:00:00Z"));
                assert_eq!(args.limit, Some(5));
            }
            other => panic!("expected audit export, got {other:?}"),
        }
    }

    #[test]
    fn global_flags_work_before_subcommand() {
        let cli = Cli::try_parse_from(["sysknife", "--yes", "--dry-run", "doctor"]).unwrap();
        assert!(cli.yes);
        assert!(cli.dry_run);
        assert!(matches!(cli.command, Some(Command::Doctor)));
    }

    #[test]
    fn intent_string_returns_none_for_non_intent_commands() {
        let cli = Cli::try_parse_from(["sysknife", "doctor"]).unwrap();
        assert!(cli.command.unwrap().intent_string().is_none());
    }

    #[test]
    fn completions_subcommand_parsed() {
        let cli = Cli::try_parse_from(["sysknife", "completions", "bash"]).unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Completions {
                shell: clap_complete::Shell::Bash
            })
        ));
    }

    #[test]
    fn completions_unknown_shell_fails() {
        assert!(Cli::try_parse_from(["sysknife", "completions", "zsh-invalid"]).is_err());
    }

    #[test]
    fn history_with_partial_flags() {
        let cli =
            Cli::try_parse_from(["sysknife", "history", "--status", "failed", "--limit", "10"])
                .unwrap();
        match cli.command {
            Some(Command::History(args)) => {
                assert_eq!(args.status.as_deref(), Some("failed"));
                assert_eq!(args.limit, 10);
                assert!(args.action.is_none());
                assert!(args.since.is_none());
            }
            other => panic!("expected Command::History, got {other:?}"),
        }
    }
}