systemg 0.57.1

An agent-friendly general process composer.
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
//! Command-line interface for Systemg.
use std::{fmt, str::FromStr};

use clap::{Parser, Subcommand, ValueEnum};
use tracing::level_filters::LevelFilter;

/// Documentation links appended to `--help` output.
const DOCS_HELP: &str = "\
Documentation:
  Docs:      https://sysg.dev
  Config:    https://sysg.dev/how-it-works/configuration
  LLM docs:  https://sysg.dev/llms.txt (index)
             https://sysg.dev/llms-full.txt (full reference)";

/// Wrapper around `LevelFilter` so clap can parse log levels from either
/// string names ("info", "debug", etc.) or numeric shorthands (0-5).
#[derive(Clone, Copy, Debug)]
pub struct LogLevelArg(LevelFilter);

impl LogLevelArg {
    /// Returns the string representation suitable for `RUST_LOG`.
    pub fn as_str(&self) -> &'static str {
        match self.0 {
            LevelFilter::OFF => "off",
            LevelFilter::ERROR => "error",
            LevelFilter::WARN => "warn",
            LevelFilter::INFO => "info",
            LevelFilter::DEBUG => "debug",
            LevelFilter::TRACE => "trace",
        }
    }
}

impl FromStr for LogLevelArg {
    type Err = String;

    /// Handles from str.
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let trimmed = value.trim();
        if trimmed.is_empty() {
            return Err("log level cannot be empty".into());
        }

        if let Ok(number) = trimmed.parse::<u8>() {
            let level = match number {
                0 => LevelFilter::OFF,
                1 => LevelFilter::ERROR,
                2 => LevelFilter::WARN,
                3 => LevelFilter::INFO,
                4 => LevelFilter::DEBUG,
                5 => LevelFilter::TRACE,
                _ => {
                    return Err(format!(
                        "unsupported log level number '{number}' (expected 0-5)"
                    ));
                }
            };

            return Ok(LogLevelArg(level));
        }

        let lowercase = trimmed.to_ascii_lowercase();
        let level = match lowercase.as_str() {
            "off" => Some(LevelFilter::OFF),
            "error" | "err" => Some(LevelFilter::ERROR),
            "warn" | "warning" => Some(LevelFilter::WARN),
            "info" | "information" => Some(LevelFilter::INFO),
            "debug" => Some(LevelFilter::DEBUG),
            "trace" => Some(LevelFilter::TRACE),
            _ => None,
        }
        .ok_or_else(|| format!("invalid log level '{trimmed}'"))?;

        Ok(LogLevelArg(level))
    }
}

/// Type of logs to display.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LogKind {
    /// Standard output logs
    Stdout,
    /// Standard error logs
    Stderr,
}

impl LogKind {
    /// Returns the string representation for file paths and display.
    pub fn as_str(&self) -> &'static str {
        match self {
            LogKind::Stdout => "stdout",
            LogKind::Stderr => "stderr",
        }
    }
}

impl fmt::Display for LogKind {
    /// Handles fmt.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl FromStr for LogKind {
    type Err = String;

    /// Handles from str.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_lowercase().as_str() {
            "stdout" => Ok(LogKind::Stdout),
            "stderr" => Ok(LogKind::Stderr),
            _ => Err(format!(
                "invalid log kind '{}', must be one of: stdout, stderr",
                s
            )),
        }
    }
}

/// Machine-readable output formats supported by status and inspect.
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
pub enum OutputFormat {
    /// Emit JSON output.
    Json,
    /// Emit XML output.
    Xml,
}

/// Command-line interface for Systemg.
#[derive(Parser)]
#[command(name = "systemg", version, author)]
#[command(about = "A lightweight process manager for system services", long_about = None)]
#[command(after_help = DOCS_HELP)]
pub struct Cli {
    /// Override the logging verbosity for this invocation only.
    #[arg(long, value_name = "LEVEL", global = true)]
    pub log_level: Option<LogLevelArg>,

    /// Print live per-service progress to the terminal (e.g. `Starting web...`)
    /// as the supervisor boots, independent of the supervisor log.
    #[arg(short = 'v', long, global = true)]
    pub verbose: bool,

    /// Opt into privileged system mode. Requires running as root.
    #[arg(long = "sys", global = true)]
    pub sys: bool,

    /// Drop privileges after performing privileged setup.
    #[arg(long = "drop-privileges", global = true)]
    pub drop_privileges: bool,

    /// Agent-friendly output: disable color, banners, paging, and log following.
    ///
    /// Equivalent to setting `SYSTEMG_AGENT=1`. Also implied when `SYSTEMG_AGENT`
    /// or `NO_COLOR` is set in the environment. Intended for non-interactive
    /// callers such as scripts, pipes, and coding agents.
    #[arg(long = "plain", global = true)]
    pub plain: bool,

    /// The command to execute.
    #[command(subcommand)]
    pub command: Commands,
}

/// Available commands for systemg.
#[derive(Subcommand)]
pub enum Commands {
    /// Start the process manager with the given configuration.
    Start {
        /// Path to the configuration file (defaults to `systemg.yaml`).
        #[arg(short, long, default_value = "systemg.yaml")]
        config: String,

        /// Whether to daemonize systemg.
        #[arg(long)]
        daemonize: bool,

        /// Optionally start only the named service.
        #[arg(short, long)]
        service: Option<String>,

        /// Project id to target.
        #[arg(short = 'p', long)]
        project: Option<String>,

        /// Name for ad-hoc units or child-start requests.
        #[arg(long)]
        name: Option<String>,

        /// Time-to-live in seconds for child-start requests.
        #[arg(long)]
        ttl: Option<u64>,

        /// Parent process ID for child-start requests.
        #[arg(long)]
        parent_pid: Option<u32>,

        /// Explicitly run in child-start mode (requires --parent-pid).
        #[arg(long)]
        child: bool,

        /// Pipe stderr output from supervised processes to stdout.
        ///
        /// When enabled, stderr from all supervised processes will be redirected to
        /// the stdout of the sysg start command with the format: \[service_name:stderr\] \<line\>
        ///
        /// This is useful for:
        /// • Debugging services during development
        /// • Capturing all error output in CI/CD pipelines
        /// • Monitoring service errors in real-time
        ///
        /// Note: This only affects foreground mode. In daemonized mode, stderr is still
        /// written to log files.
        #[arg(long)]
        stderr: bool,

        /// Ad-hoc command and arguments to supervise without a manifest.
        #[arg(trailing_var_arg = true)]
        command: Vec<String>,
    },

    /// Stop the currently running process manager.
    Stop {
        /// Path to the configuration file (defaults to `systemg.yaml`).
        #[arg(short, long, default_value = "systemg.yaml")]
        config: String,

        /// Name of service to stop (optional).
        #[arg(short, long)]
        service: Option<String>,

        /// Project id to target.
        #[arg(short = 'p', long)]
        project: Option<String>,

        /// Shut down the resident supervisor and all registered projects.
        #[arg(long)]
        supervisor: bool,
    },

    /// Restart the process manager, optionally specifying a new configuration file.
    Restart {
        /// Path to the configuration file (defaults to `systemg.yaml`).
        #[arg(short, long, default_value = "systemg.yaml")]
        config: String,

        /// Optionally restart only the named service.
        #[arg(short, long)]
        service: Option<String>,

        /// Project id to target.
        #[arg(short = 'p', long)]
        project: Option<String>,

        /// Start the supervisor before restarting if it isn't already running.
        #[arg(long)]
        daemonize: bool,
    },

    /// Show the status of currently running services.
    Status {
        /// Optional configuration file used to scope status output.
        #[arg(short, long)]
        config: Option<String>,

        /// Optionally specify a service name to check its status.
        #[arg(short, long)]
        service: Option<String>,

        /// Project id to filter status by.
        #[arg(short = 'p', long)]
        project: Option<String>,

        /// Show all services including orphaned state (services not in current config).
        #[arg(long)]
        all: bool,

        /// Emit machine-readable output in the requested format.
        #[arg(
            long,
            value_enum,
            value_name = "FORMAT",
            num_args = 0..=1,
            default_missing_value = "json"
        )]
        format: Option<OutputFormat>,

        /// Disable ANSI colors in output.
        #[arg(long = "no-color")]
        no_color: bool,

        /// Show full command lines in the status table.
        #[arg(long = "full-cmd")]
        full_cmd: bool,

        /// Force immediate runtime collection instead of the configured snapshot mode.
        #[arg(long)]
        live: bool,

        /// Continuously refresh output at the provided interval (e.g., "5", "1s", "2m").
        #[arg(long, value_name = "DURATION")]
        stream: Option<String>,
    },

    /// Inspect a single service or cron unit in detail.
    Inspect {
        /// Path to the configuration file (defaults to `systemg.yaml`).
        #[arg(short, long, default_value = "systemg.yaml")]
        config: String,

        /// Name of the service to inspect.
        #[arg(short, long)]
        service: String,

        /// Project id containing the inspected service.
        #[arg(short = 'p', long)]
        project: Option<String>,

        /// Emit machine-readable output in the requested format.
        #[arg(
            long,
            value_enum,
            value_name = "FORMAT",
            num_args = 0..=1,
            default_missing_value = "json"
        )]
        format: Option<OutputFormat>,

        /// Disable ANSI colors in output.
        #[arg(long = "no-color")]
        no_color: bool,

        /// Force immediate runtime collection instead of the configured snapshot mode.
        #[arg(long)]
        live: bool,

        /// Continuously refresh output and use a rolling metrics window (e.g., "5", "1s", "2m").
        #[arg(long, value_name = "DURATION")]
        stream: Option<String>,
    },

    /// Tail stored service output logs.
    Logs {
        /// Path to the configuration file (defaults to `systemg.yaml`).
        #[arg(short, long, default_value = "systemg.yaml")]
        config: String,

        /// Purge log files instead of displaying them.
        #[arg(long)]
        purge: bool,

        /// Prune rotated log backups instead of displaying logs.
        #[arg(long)]
        prune: bool,

        /// When pruning, cap total rotated-backup size (e.g. "500MB", "2g").
        #[arg(long, value_name = "SIZE")]
        max_size: Option<String>,

        /// When pruning, remove rotated backups older than this (e.g. "7d", "12h").
        #[arg(long, value_name = "AGE")]
        max_age: Option<String>,

        /// The name of the service whose logs should be displayed (optional).
        #[arg(short, long)]
        service: Option<String>,

        /// Project id to filter logs by.
        #[arg(short = 'p', long)]
        project: Option<String>,

        /// Number of trailing lines to show. Omit to show the FULL captured log;
        /// pass `-l N` to limit to the last N lines.
        #[arg(short, long, default_value_t = usize::MAX)]
        lines: usize,

        /// Kind of logs to show: stdout or stderr. Defaults to stdout+stderr.
        #[arg(short = 'k', long)]
        kind: Option<LogKind>,

        /// Show the supervisor's own log instead of any service's logs.
        #[arg(long)]
        supervisor: bool,

        /// Follow the log stream until interrupted (like `tail -F`).
        ///
        /// Stays attached and prints new lines as they arrive. Press Esc or
        /// Ctrl-C to stop following and return to the shell. When neither
        /// `--follow` nor `--no-follow` is given, systemg follows only when
        /// stdout is an interactive terminal and `SYSTEMG_AGENT` is unset;
        /// otherwise it prints a one-shot snapshot and exits. This keeps
        /// non-interactive callers (agents, pipes, SSH) from wedging.
        #[arg(short = 'f', long, conflicts_with = "no_follow")]
        follow: bool,

        /// Force a one-shot snapshot even on an interactive terminal.
        #[arg(long = "no-follow")]
        no_follow: bool,

        /// Only show lines captured at or after this time.
        ///
        /// Accepts an RFC3339 timestamp (`2026-07-07T14:00:00Z`), a UTC date
        /// (`2026-07-07`), or a relative age in the past (`30m`, `2h`, `7d`).
        #[arg(long, value_name = "TIME")]
        since: Option<String>,

        /// Only show lines captured at or before this time (same formats as --since).
        #[arg(long, value_name = "TIME")]
        until: Option<String>,

        /// Only show lines matching this regular expression.
        #[arg(short = 'g', long, value_name = "PATTERN")]
        grep: Option<String>,

        /// Read the full active-plus-rotated history instead of the last --lines.
        #[arg(short = 'a', long)]
        all: bool,

        /// Print the on-disk log path(s) instead of the logs, then exit.
        ///
        /// With no service, prints the log directory. With `--service`, prints
        /// that service's resolved log file (add `--all` to list its rotated
        /// backups too).
        #[arg(long)]
        path: bool,

        /// Emit machine-readable output. `json` prints one
        /// `{ts, stream, service, line}` object per line.
        #[arg(long, value_enum, value_name = "FORMAT")]
        format: Option<OutputFormat>,

        /// Print only the application's original line, dropping systemg's
        /// capture timestamp and stream prefix.
        #[arg(long)]
        raw: bool,

        /// Strip ANSI color/escape sequences from log lines. Defaults on for
        /// `--format json`, `--raw`, and non-interactive output.
        #[arg(long = "strip-ansi")]
        strip_ansi: bool,

        /// Keep ANSI escape sequences even when they would be stripped by default.
        #[arg(long = "no-strip-ansi", conflicts_with = "strip_ansi")]
        no_strip_ansi: bool,

        /// Continuously refresh output at the provided interval (e.g., "5", "1s", "2m").
        #[arg(long, value_name = "DURATION")]
        stream: Option<String>,
    },

    /// Validate a configuration file and report errors with fixes.
    Validate {
        /// Path to the configuration file (defaults to `systemg.yaml`).
        #[arg(short, long, default_value = "systemg.yaml")]
        config: String,

        /// Emit machine-readable output in the requested format.
        #[arg(
            long,
            value_enum,
            value_name = "FORMAT",
            num_args = 0..=1,
            default_missing_value = "json"
        )]
        format: Option<OutputFormat>,

        /// Disable ANSI colors in output.
        #[arg(long = "no-color")]
        no_color: bool,
    },

    /// Convert a legacy `project:` manifest to the canonical `projects:` form.
    Migrate {
        /// Path to the manifest to convert.
        config: String,

        /// Overwrite the file in place (a `.bak` copy is kept) instead of
        /// printing the converted manifest to stdout.
        #[arg(long)]
        in_place: bool,
    },

    /// Purge systemg state and runtime files.
    ///
    /// With no selector, wipes the entire state root. `-c` scopes to every
    /// project a config declares; `-p` scopes to one project. Refuses to run
    /// while a live supervisor is managing processes unless `--force` is given.
    Purge {
        /// Purge only the projects this config declares (or `__loose__` if it is
        /// project-less). Omit to wipe the whole state root.
        #[arg(short, long)]
        config: Option<String>,

        /// Purge only this project's state.
        #[arg(short = 'p', long)]
        project: Option<String>,

        /// Purge even while a supervisor is managing processes (stops it first).
        #[arg(long)]
        force: bool,
    },

    /// INTERNAL: report live-upgrade protocol metadata for installer preflight.
    #[command(hide = true)]
    UpgradeInfo,

    /// INTERNAL: ask the resident supervisor to execute a staged binary.
    #[command(hide = true)]
    UpgradeSupervisor {
        /// Path to the staged replacement binary.
        #[arg(long)]
        binary: String,
    },

    /// INTERNAL: boot the resident supervisor. Not for direct use — the daemon
    /// re-execs into this after forking so it starts from a clean, single-threaded
    /// process image (no mutexes inherited-locked from the launching CLI's threads).
    #[command(hide = true)]
    Supervise {
        /// Path to the manifest the supervisor boots from.
        #[arg(long)]
        config: String,

        /// Boot only this single service instead of the whole config.
        #[arg(long)]
        service: Option<String>,

        /// Pipe service stderr through the supervisor.
        #[arg(long)]
        pipe_stderr: bool,

        /// Verbose boot reporting.
        #[arg(long)]
        verbose: bool,

        /// Record the primary project as terminal-attached rather than daemonized.
        #[arg(long)]
        foreground: bool,

        /// Private state record inherited from a live supervisor re-exec.
        #[arg(long)]
        handoff: Option<String>,
    },

    /// DEPRECATED: Spawn a dynamic child process from a parent service.
    #[command(hide = true)]
    Spawn {
        /// Name for the spawned child process.
        #[arg(long)]
        name: String,

        /// Time-to-live in seconds (optional).
        #[arg(long)]
        ttl: Option<u64>,

        /// Parent process ID (defaults to caller's parent PID if not specified).
        #[arg(long)]
        parent_pid: Option<u32>,

        /// Override the logging verbosity for the spawned process.
        #[arg(long, value_name = "LEVEL")]
        log_level: Option<LogLevelArg>,

        /// Command and arguments to execute.
        #[arg(trailing_var_arg = true, required = true)]
        command: Vec<String>,
    },
}

impl Commands {
    /// The subcommand's canonical name, used to attach command-appropriate help
    /// and docs to an otherwise-generic failure (so a `status` error points at
    /// status docs, not `sysg logs`).
    pub fn name(&self) -> &'static str {
        match self {
            Commands::Start { .. } => "start",
            Commands::Stop { .. } => "stop",
            Commands::Restart { .. } => "restart",
            Commands::Status { .. } => "status",
            Commands::Inspect { .. } => "inspect",
            Commands::Logs { .. } => "logs",
            Commands::Validate { .. } => "validate",
            Commands::Migrate { .. } => "migrate",
            Commands::Purge { .. } => "purge",
            Commands::UpgradeInfo => "upgrade-info",
            Commands::UpgradeSupervisor { .. } => "upgrade-supervisor",
            Commands::Supervise { .. } => "supervise",
            Commands::Spawn { .. } => "spawn",
        }
    }
}

/// Parses command-line arguments and returns a `Cli` struct.
pub fn parse_args() -> Cli {
    Cli::parse()
}

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

    #[test]
    fn status_accepts_stream() {
        let cli = Cli::try_parse_from(["sysg", "status", "--stream", "5"]).unwrap();
        match cli.command {
            Commands::Status { stream, .. } => assert_eq!(stream.as_deref(), Some("5")),
            _ => panic!("expected status command"),
        }
    }

    #[test]
    fn status_accepts_live() {
        let cli = Cli::try_parse_from(["sysg", "status", "--live"]).unwrap();
        match cli.command {
            Commands::Status { live, .. } => assert!(live),
            _ => panic!("expected status command"),
        }
    }

    #[test]
    fn status_accepts_project_filter() {
        let cli = Cli::try_parse_from(["sysg", "status", "-p", "arbitration"]).unwrap();
        match cli.command {
            Commands::Status { project, .. } => {
                assert_eq!(project.as_deref(), Some("arbitration"));
            }
            _ => panic!("expected status command"),
        }
    }

    #[test]
    fn status_config_is_optional() {
        let cli = Cli::try_parse_from(["sysg", "status"]).unwrap();
        match cli.command {
            Commands::Status { config, .. } => assert!(config.is_none()),
            _ => panic!("expected status command"),
        }
    }

    #[test]
    fn status_accepts_explicit_config_scope() {
        let cli = Cli::try_parse_from(["sysg", "status", "-c", "foo.yaml"]).unwrap();
        match cli.command {
            Commands::Status { config, .. } => {
                assert_eq!(config.as_deref(), Some("foo.yaml"));
            }
            _ => panic!("expected status command"),
        }
    }

    #[test]
    fn stop_accepts_supervisor_shutdown_flag() {
        let cli = Cli::try_parse_from(["sysg", "stop", "--supervisor"]).unwrap();
        match cli.command {
            Commands::Stop { supervisor, .. } => assert!(supervisor),
            _ => panic!("expected stop command"),
        }
    }

    #[test]
    fn stop_accepts_project_filter_with_log_level() {
        let cli = Cli::try_parse_from([
            "sysg",
            "stop",
            "-p",
            "gamecast-dev",
            "--log-level",
            "DEBUG",
        ])
        .unwrap();
        assert_eq!(
            cli.log_level.as_ref().map(LogLevelArg::as_str),
            Some("debug")
        );
        match cli.command {
            Commands::Stop {
                project, service, ..
            } => {
                assert_eq!(project.as_deref(), Some("gamecast-dev"));
                assert!(service.is_none());
            }
            _ => panic!("expected stop command"),
        }
    }

    #[test]
    fn inspect_accepts_stream() {
        let cli = Cli::try_parse_from([
            "sysg",
            "inspect",
            "--service",
            "demo",
            "--stream",
            "2m",
        ])
        .unwrap();
        match cli.command {
            Commands::Inspect { stream, .. } => {
                assert_eq!(stream.as_deref(), Some("2m"))
            }
            _ => panic!("expected inspect command"),
        }
    }

    #[test]
    fn inspect_accepts_live() {
        let cli = Cli::try_parse_from(["sysg", "inspect", "--service", "demo", "--live"])
            .unwrap();
        match cli.command {
            Commands::Inspect { live, .. } => assert!(live),
            _ => panic!("expected inspect command"),
        }
    }

    #[test]
    fn logs_accepts_project_filter() {
        let cli =
            Cli::try_parse_from(["sysg", "logs", "--project", "arbitration"]).unwrap();
        match cli.command {
            Commands::Logs { project, .. } => {
                assert_eq!(project.as_deref(), Some("arbitration"));
            }
            _ => panic!("expected logs command"),
        }
    }

    #[test]
    fn logs_accepts_stream() {
        let cli =
            Cli::try_parse_from(["sysg", "logs", "--service", "demo", "--stream", "1s"])
                .unwrap();
        match cli.command {
            Commands::Logs { stream, .. } => {
                assert_eq!(stream.as_deref(), Some("1s"))
            }
            _ => panic!("expected logs command"),
        }
    }

    #[test]
    fn logs_accepts_purge_for_service() {
        let cli = Cli::try_parse_from(["sysg", "logs", "--service", "demo", "--purge"])
            .unwrap();
        match cli.command {
            Commands::Logs { purge, service, .. } => {
                assert!(purge);
                assert_eq!(service.as_deref(), Some("demo"));
            }
            _ => panic!("expected logs command"),
        }
    }

    #[test]
    fn logs_accepts_follow() {
        let cli =
            Cli::try_parse_from(["sysg", "logs", "--service", "demo", "-f"]).unwrap();
        match cli.command {
            Commands::Logs {
                follow, no_follow, ..
            } => {
                assert!(follow);
                assert!(!no_follow);
            }
            _ => panic!("expected logs command"),
        }
    }

    #[test]
    fn logs_accepts_no_follow() {
        let cli =
            Cli::try_parse_from(["sysg", "logs", "--service", "demo", "--no-follow"])
                .unwrap();
        match cli.command {
            Commands::Logs {
                follow, no_follow, ..
            } => {
                assert!(!follow);
                assert!(no_follow);
            }
            _ => panic!("expected logs command"),
        }
    }

    #[test]
    fn logs_rejects_follow_with_no_follow() {
        assert!(Cli::try_parse_from(["sysg", "logs", "-f", "--no-follow"]).is_err());
    }

    #[test]
    fn global_plain_flag_parses_before_subcommand() {
        let cli = Cli::try_parse_from(["sysg", "--plain", "status"]).unwrap();
        assert!(cli.plain);
    }

    #[test]
    fn global_plain_flag_parses_after_subcommand() {
        let cli = Cli::try_parse_from(["sysg", "logs", "--plain"]).unwrap();
        assert!(cli.plain);
    }

    #[test]
    fn logs_accepts_path_flag() {
        let cli = Cli::try_parse_from(["sysg", "logs", "-s", "api", "--path", "--all"])
            .unwrap();
        match cli.command {
            Commands::Logs { path, all, .. } => {
                assert!(path);
                assert!(all);
            }
            _ => panic!("expected logs command"),
        }
    }

    #[test]
    fn logs_accepts_format_and_render_flags() {
        let cli = Cli::try_parse_from([
            "sysg",
            "logs",
            "-s",
            "api",
            "--format",
            "json",
            "--strip-ansi",
        ])
        .unwrap();
        match cli.command {
            Commands::Logs {
                format,
                strip_ansi,
                raw,
                ..
            } => {
                assert_eq!(format, Some(OutputFormat::Json));
                assert!(strip_ansi);
                assert!(!raw);
            }
            _ => panic!("expected logs command"),
        }
    }

    #[test]
    fn logs_rejects_strip_and_no_strip_together() {
        assert!(
            Cli::try_parse_from(["sysg", "logs", "--strip-ansi", "--no-strip-ansi"])
                .is_err()
        );
    }

    #[test]
    fn logs_accepts_filter_flags() {
        let cli = Cli::try_parse_from([
            "sysg",
            "logs",
            "-s",
            "api",
            "--since",
            "2h",
            "--until",
            "2026-07-07",
            "--grep",
            "ERROR",
            "--all",
        ])
        .unwrap();
        match cli.command {
            Commands::Logs {
                since,
                until,
                grep,
                all,
                ..
            } => {
                assert_eq!(since.as_deref(), Some("2h"));
                assert_eq!(until.as_deref(), Some("2026-07-07"));
                assert_eq!(grep.as_deref(), Some("ERROR"));
                assert!(all);
            }
            _ => panic!("expected logs command"),
        }
    }

    #[test]
    fn logs_accepts_purge_without_service() {
        let cli = Cli::try_parse_from(["sysg", "logs", "--purge"]).unwrap();
        match cli.command {
            Commands::Logs { purge, service, .. } => {
                assert!(purge);
                assert_eq!(service, None);
            }
            _ => panic!("expected logs command"),
        }
    }

    #[test]
    fn validate_accepts_config_and_format() {
        let cli = Cli::try_parse_from([
            "sysg", "validate", "-c", "app.yaml", "--format", "json",
        ])
        .unwrap();
        match cli.command {
            Commands::Validate { config, format, .. } => {
                assert_eq!(config, "app.yaml");
                assert_eq!(format, Some(OutputFormat::Json));
            }
            _ => panic!("expected validate command"),
        }
    }

    #[test]
    fn validate_defaults_config() {
        let cli = Cli::try_parse_from(["sysg", "validate"]).unwrap();
        match cli.command {
            Commands::Validate { config, format, .. } => {
                assert_eq!(config, "systemg.yaml");
                assert_eq!(format, None);
            }
            _ => panic!("expected validate command"),
        }
    }

    #[test]
    fn status_rejects_watch() {
        assert!(Cli::try_parse_from(["sysg", "status", "--watch", "5"]).is_err());
    }

    #[test]
    fn start_accepts_trailing_command() {
        let cli =
            Cli::try_parse_from(["sysg", "start", "--daemonize", "sleep", "5"]).unwrap();
        match cli.command {
            Commands::Start {
                daemonize, command, ..
            } => {
                assert!(daemonize);
                assert_eq!(command, vec!["sleep".to_string(), "5".to_string()]);
            }
            _ => panic!("expected start command"),
        }
    }

    #[test]
    fn start_accepts_child_mode_flags() {
        let cli = Cli::try_parse_from([
            "sysg",
            "start",
            "--child",
            "--parent-pid",
            "4242",
            "--name",
            "worker-1",
            "--ttl",
            "30",
            "python",
            "worker.py",
        ])
        .unwrap();
        match cli.command {
            Commands::Start {
                child,
                parent_pid,
                name,
                ttl,
                command,
                ..
            } => {
                assert!(child);
                assert_eq!(parent_pid, Some(4242));
                assert_eq!(name.as_deref(), Some("worker-1"));
                assert_eq!(ttl, Some(30));
                assert_eq!(command, vec!["python".to_string(), "worker.py".to_string()]);
            }
            _ => panic!("expected start command"),
        }
    }

    #[test]
    fn inspect_rejects_window() {
        assert!(
            Cli::try_parse_from([
                "sysg",
                "inspect",
                "--service",
                "demo",
                "--window",
                "5s",
            ])
            .is_err()
        );
    }
}