greggd 1.0.14

Lightweight Linux, macOS, and Windows metrics daemon that exposes a read-only JSON API for the gregg client.
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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
//! CLI argument parsing and subcommand dispatch for `greggd`.
//!
//! Uses `clap` derive macros for structured argument parsing. Each
//! subcommand has a stable help message and returns a meaningful exit code.

use std::fmt;
use std::io::{Read, Write};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, TcpStream};
use std::path::PathBuf;
use std::process::{Command as ProcessCommand, Stdio};
use std::time::Duration;

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

use crate::config::{Config, ConfigError};
#[cfg(any(target_os = "windows", test))]
use crate::service::ServiceError;
use crate::startup::StartupMethodArg;

/// Lightweight metrics daemon for the gregg monitoring system.
#[derive(Parser)]
#[command(
    name = "greggd",
    version,
    about = "Lightweight Linux, macOS, and Windows metrics daemon",
    long_about = "greggd runs on designated systems and exposes a read-only JSON API \
                  for the gregg terminal client. It samples CPU, memory, swap, and \
                  load metrics on a configurable interval and serves cached immutable \
                  snapshots over HTTP/1."
)]
pub struct Cli {
    /// Path to the configuration file.
    #[arg(
        long,
        short = 'c',
        global = true,
        help = "Path to the TOML configuration file",
        value_name = "PATH"
    )]
    pub config: Option<PathBuf>,

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

/// Available subcommands.
#[derive(Subcommand)]
pub enum Command {
    /// Run the daemon in the foreground.
    Run,
    /// Stop a running greggd instance via the local Unix control socket
    /// (Linux/macOS) or via the Windows Service Control Manager (Windows).
    Stop,
    /// Start the greggd Windows service.
    #[cfg(target_os = "windows")]
    Start,
    /// Restart the daemon through its detected startup manager.
    #[allow(clippy::doc_markdown)]
    Restart,
    /// Manage automatic startup (systemd, launchd, or cron).
    Startup {
        #[command(subcommand)]
        command: StartupCommand,
    },
    /// Ensure greggd is running. Probes the configured local health endpoint and,
    /// if the endpoint is definitely refused, spawns `greggd run` as a detached child.
    /// Intended for cron, Task Scheduler, and other operator-managed
    /// supervisors that have no built-in readiness monitoring.
    Croncheck,
    /// Print the configured bind address without probing or mutating state.
    Configprint,
    /// Show read-only local diagnostic status: version, config path,
    /// configured bind address, local health classification, and detected
    /// startup-manager state. Never starts, stops, restarts, installs, or
    /// mutates configuration; exit 0 only when a valid Gregg health
    /// endpoint answered (ready, warming, or failed).
    Status,
    /// Update the bind address (applies on the next daemon start).
    Host {
        /// The new IPv4 or IPv6 address to bind to.
        address: IpAddr,
    },
    /// Update the TCP port (applies on the next daemon start).
    Port {
        /// The new port number (1-65535).
        port: u16,
    },
    /// Uninstall the greggd daemon binary and its Gregg-owned startup integration.
    ///
    /// Removes only the exact invoked executable; a sibling `gregg` binary
    /// sharing the install directory is never touched, and install
    /// directories are never removed recursively. Startup teardown removes
    /// only canonical Gregg artifacts actually present (systemd unit,
    /// launchd plist, managed cron block, or the `greggd` SCM
    /// registration). Configuration is preserved by default; `--purge`
    /// additionally removes the resolved daemon config file (and the macOS
    /// daemon log). `--dry-run` prints the exact resources that would be
    /// removed without mutating anything. There is no interactive prompt;
    /// invoking `uninstall` is the explicit destructive action.
    Uninstall {
        /// Print the exact resources that would be removed without
        /// stopping, mutating, or deleting anything.
        #[arg(long)]
        dry_run: bool,
        /// Also remove the resolved daemon config/data files
        /// (destructive). Without this flag configuration is preserved.
        #[arg(long)]
        purge: bool,
    },
    /// Print the binary version.
    Version,
    /// Update the daemon binary to the latest stable crates.io version.
    ///
    /// The updater uses crates.io as the version authority and downloads the
    /// exact tagged GitHub Release asset when available. Checksum and
    /// candidate `version` are verified before any replacement. If no
    /// prebuilt asset exists for the current host (HTTP 404), Cargo is used
    /// as a fallback when available. A checksum or version mismatch is a
    /// hard error and does not fall back to Cargo. After a successful
    /// replacement, the daemon is restarted through its detected manager
    /// when it was running (systemd, launchd, SCM, or direct cron); an
    /// intentionally stopped service remains stopped. No `sudo` is invoked
    /// internally; rerun with `sudo greggd update` when the install location
    /// requires it.
    Update,
    /// Internal: Windows SCM service entry point. Not for interactive use.
    #[cfg(target_os = "windows")]
    #[command(hide = true)]
    Service,
}

/// Startup subcommands for automatic startup management.
#[derive(Subcommand, Debug, Clone, PartialEq, Eq)]
pub enum StartupCommand {
    /// Install and enable automatic startup for the detected or specified manager.
    Install {
        /// Startup manager to install. `auto` detects the platform default.
        #[arg(long, value_enum, default_value_t = StartupMethodArg::Auto, value_name = "METHOD")]
        method: StartupMethodArg,
    },
    /// Print instructions for enabling automatic startup without mutating state.
    Instructions {
        /// Startup manager to describe. `auto` detects the platform default.
        #[arg(long, value_enum, default_value_t = StartupMethodArg::Auto, value_name = "METHOD")]
        method: StartupMethodArg,
    },
}

impl ValueEnum for StartupMethodArg {
    fn value_variants<'a>() -> &'a [Self] {
        &[Self::Auto, Self::Systemd, Self::Launchd, Self::Cron]
    }

    fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
        Some(match self {
            Self::Auto => clap::builder::PossibleValue::new("auto"),
            Self::Systemd => clap::builder::PossibleValue::new("systemd"),
            Self::Launchd => clap::builder::PossibleValue::new("launchd"),
            Self::Cron => clap::builder::PossibleValue::new("cron"),
        })
    }
}

/// Exit codes returned by greggd commands.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExitCode {
    Success = 0,
    /// Configuration error (invalid, missing, or unwritable).
    ConfigError = 1,
    /// Service management command failed.
    ServiceError = 2,
    /// The daemon could not start (port conflict, etc.).
    RuntimeError = 3,
    /// Permission denied for the requested operation.
    PermissionDenied = 4,
}

impl From<&ConfigError> for ExitCode {
    fn from(e: &ConfigError) -> Self {
        match e {
            ConfigError::Io { source, .. }
                if source.kind() == std::io::ErrorKind::PermissionDenied =>
            {
                Self::PermissionDenied
            }
            ConfigError::AtomicWrite { source, .. } => match source {
                crate::config::AtomicWriteError::Io(io)
                    if io.kind() == std::io::ErrorKind::PermissionDenied =>
                {
                    Self::PermissionDenied
                }
                _ => Self::ConfigError,
            },
            _ => Self::ConfigError,
        }
    }
}

#[cfg(any(target_os = "windows", test))]
impl From<&ServiceError> for ExitCode {
    fn from(e: &ServiceError) -> Self {
        match e {
            ServiceError::CommandFailed { .. }
            | ServiceError::ExecFailed { .. }
            | ServiceError::NotAvailable { .. }
            | ServiceError::StateQueryFailed { .. }
            | ServiceError::Timeout { .. } => Self::ServiceError,
            ServiceError::AccessDenied => Self::PermissionDenied,
        }
    }
}

impl From<&crate::startup::InstallError> for ExitCode {
    fn from(e: &crate::startup::InstallError) -> Self {
        match e {
            crate::startup::InstallError::Permission { .. } => Self::PermissionDenied,
            crate::startup::InstallError::Io { source, .. }
                if source.kind() == std::io::ErrorKind::PermissionDenied =>
            {
                Self::PermissionDenied
            }
            crate::startup::InstallError::BinaryMissing { .. }
            | crate::startup::InstallError::UnsupportedMethod { .. } => Self::ConfigError,
            _ => Self::ServiceError,
        }
    }
}

impl From<&crate::uninstall::UninstallError> for ExitCode {
    fn from(e: &crate::uninstall::UninstallError) -> Self {
        match e {
            crate::uninstall::UninstallError::Permission { .. } => Self::PermissionDenied,
            crate::uninstall::UninstallError::Service { .. } => Self::ServiceError,
            crate::uninstall::UninstallError::CurrentExe(_)
            | crate::uninstall::UninstallError::Io { .. }
            | crate::uninstall::UninstallError::UncertainStop { .. }
            | crate::uninstall::UninstallError::Cron { .. }
            | crate::uninstall::UninstallError::CargoHandoff { .. }
            | crate::uninstall::UninstallError::CargoFailed(_) => Self::RuntimeError,
        }
    }
}

impl From<&crate::update::UpdateError> for ExitCode {
    fn from(e: &crate::update::UpdateError) -> Self {
        match e {
            crate::update::UpdateError::PermissionDenied { .. } => Self::PermissionDenied,
            _ => Self::RuntimeError,
        }
    }
}

/// Resolve the config path: explicit `--config` or platform default.
pub fn resolve_config_path(explicit: Option<&PathBuf>) -> PathBuf {
    explicit.cloned().unwrap_or_else(Config::default_path)
}

/// Load or create the configuration.
///
/// If the config file exists, load and validate it. If it does not exist
/// and no explicit path was given, use defaults. If an explicit path was
/// given but the file is missing, return an error.
pub fn load_config(path: &std::path::Path, explicit: bool) -> Result<Config, ConfigError> {
    match std::fs::metadata(path) {
        Ok(_) => Config::load(path),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            if explicit {
                Err(ConfigError::Io {
                    path: path.to_path_buf(),
                    source: error,
                })
            } else {
                // No explicit path and file doesn't exist — use defaults.
                Ok(Config::default())
            }
        }
        Err(source) => Err(ConfigError::Io {
            path: path.to_path_buf(),
            source,
        }),
    }
}

/// Error returned when config validation fails during mutation.
///
/// This is separate from `ConfigError` because it carries the violations
/// for structured reporting and requires a distinct exit code.
#[derive(Debug)]
pub struct ConfigValidationError(pub Vec<crate::config::ConfigViolation>);

impl fmt::Display for ConfigValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "configuration validation failed:")?;
        for v in &self.0 {
            write!(f, "\n  - {v}")?;
        }
        Ok(())
    }
}

impl std::error::Error for ConfigValidationError {}

/// Update a single field in the config and atomically persist it.
///
/// This is the shared logic for `host` and `port` subcommands.
pub fn mutate_config(
    path: &std::path::Path,
    explicit: bool,
    mutate: impl FnOnce(&mut Config),
) -> Result<(), Box<dyn std::error::Error>> {
    let mut config = load_config(path, explicit)?;
    mutate(&mut config);

    let violations = config.validate();
    if !violations.is_empty() {
        return Err(Box::new(ConfigValidationError(violations)));
    }

    config.write_atomic(path)?;

    Ok(())
}

/// Return the compile-time version rendered for the daemon binary.
#[must_use]
pub fn version_string() -> String {
    format!("greggd {}", env!("CARGO_PKG_VERSION"))
}

/// Map wildcard bind addresses to local loopback addresses for probing.
#[must_use]
pub fn probe_address(address: IpAddr) -> IpAddr {
    match address {
        IpAddr::V4(value) if value.is_unspecified() => IpAddr::V4(Ipv4Addr::LOCALHOST),
        IpAddr::V6(value) if value.is_unspecified() => IpAddr::V6(Ipv6Addr::LOCALHOST),
        value => value,
    }
}

/// Derive the local probe target from daemon configuration.
#[must_use]
pub fn croncheck_target(config: &Config) -> SocketAddr {
    SocketAddr::new(probe_address(config.host), config.port)
}

/// Return the configured bind address in canonical socket-address form.
#[must_use]
pub fn config_address(config: &Config) -> SocketAddr {
    SocketAddr::new(config.host, config.port)
}

/// Return the bind address for `configprint`, resolving wildcards to
/// the host's primary local IP so the output is a usable address a
/// remote client can dial.
///
/// A specific host is returned unchanged. A `0.0.0.0` wildcard is
/// resolved to the local IPv4 address and an `::` wildcard to the
/// local IPv6 address (with an IPv4 fallback). If the local interface
/// cannot be resolved, the wildcard is preserved verbatim so the
/// output is still a valid socket address.
#[must_use]
pub fn display_address(config: &Config) -> SocketAddr {
    display_address_from(
        config,
        crate::net::local_ipv4_address,
        crate::net::local_ipv6_address,
    )
}

/// Same as [`display_address`] but with explicit local-address probes
/// for testability. The probes are plain `fn() -> Option<IpAddr>`
/// callbacks so callers can inject deterministic addresses without
/// touching the kernel's routing table.
#[must_use]
#[allow(clippy::module_name_repetitions)]
pub fn display_address_from(
    config: &Config,
    local_ipv4: fn() -> Option<IpAddr>,
    local_ipv6: fn() -> Option<IpAddr>,
) -> SocketAddr {
    let host = match config.host {
        IpAddr::V4(value) if value.is_unspecified() => local_ipv4().unwrap_or(config.host),
        IpAddr::V6(value) if value.is_unspecified() => {
            local_ipv6().or_else(local_ipv4).unwrap_or(config.host)
        }
        other => other,
    };
    SocketAddr::new(host, config.port)
}

/// Bounded TCP-connect check used by `croncheck`.
///
/// Returns `true` if a listener accepts the connection within the
/// timeout, `false` otherwise. A refusal, timeout, or unreachable host
/// all mean the daemon is not accepting traffic on this address.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum CroncheckProbe {
    Running,
    Absent,
    Ambiguous,
}

const CRONCHECK_TIMEOUT: Duration = Duration::from_millis(750);
const MAX_CRONCHECK_RESPONSE_BYTES: usize = 256 * 1024;

/// Classify a raw `/v2/healthz` response body into its readiness state.
///
/// Returns `None` unless the response is a well-formed HTTP/1.x reply whose
/// status/JSON pair is a valid Gregg health response: `200` + `ready`, or
/// `503` + `warming`/`failed`. Anything else (wrong status, non-JSON body,
/// schema mismatch, truncated headers) is not a valid Gregg endpoint.
fn classify_health_response(response: &[u8]) -> Option<gregg_protocol::ReadinessState> {
    let header_end = response
        .windows(4)
        .position(|window| window == b"\r\n\r\n")?;
    let headers = &response[..header_end];
    let body = &response[header_end + 4..];
    let status_line = headers.split(|byte| *byte == 10).next()?;
    let mut status_parts = status_line.split(|byte| *byte == 32 || *byte == 13);
    let version = status_parts.next()?;
    let status = status_parts
        .next()
        .and_then(|value| std::str::from_utf8(value).ok())
        .and_then(|value| value.parse::<u16>().ok())?;
    if version != b"HTTP/1.0" && version != b"HTTP/1.1" {
        return None;
    }
    let Ok(health) = serde_json::from_slice::<gregg_protocol::v2::HealthResponseV2>(body) else {
        return None;
    };
    match (status, health.state) {
        (200, gregg_protocol::ReadinessState::Ready) => Some(gregg_protocol::ReadinessState::Ready),
        (503, gregg_protocol::ReadinessState::Warming) => {
            Some(gregg_protocol::ReadinessState::Warming)
        }
        (503, gregg_protocol::ReadinessState::Failed) => {
            Some(gregg_protocol::ReadinessState::Failed)
        }
        _ => None,
    }
}

/// Raw outcome of the bounded local health fetch shared by `croncheck`,
/// restart/update coordination, and `status`.
#[derive(Debug, PartialEq, Eq)]
enum FetchOutcome {
    /// The listener definitely refused the connection: nothing accepts
    /// traffic on this address.
    Refused,
    /// No usable answer: timeout, unreachable host, write/read failure, or
    /// an over-cap response body.
    Failed,
    /// The peer answered within bounds; classification happens separately.
    Responded(Vec<u8>),
}

/// Perform the bounded raw-HTTP `GET /v2/healthz` fetch: finite
/// connection/read deadline, bounded response body, no service-manager
/// invocation, no mutation.
fn fetch_health_bytes(target: SocketAddr) -> FetchOutcome {
    let mut stream = match TcpStream::connect_timeout(&target, CRONCHECK_TIMEOUT) {
        Ok(stream) => stream,
        Err(error) if error.kind() == std::io::ErrorKind::ConnectionRefused => {
            return FetchOutcome::Refused
        }
        Err(_) => return FetchOutcome::Failed,
    };
    let _ = stream.set_read_timeout(Some(CRONCHECK_TIMEOUT));
    let _ = stream.set_write_timeout(Some(CRONCHECK_TIMEOUT));
    if stream
        .write_all(b"GET /v2/healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
        .is_err()
    {
        return FetchOutcome::Failed;
    }
    let mut response = Vec::new();
    let mut chunk = [0_u8; 4096];
    loop {
        match stream.read(&mut chunk) {
            Ok(0) => break,
            Ok(read) => {
                // Check before buffering so at most the cap itself is held.
                if response.len().saturating_add(read) > MAX_CRONCHECK_RESPONSE_BYTES {
                    return FetchOutcome::Failed;
                }
                response.extend_from_slice(&chunk[..read]);
            }
            Err(_) => return FetchOutcome::Failed,
        }
    }
    FetchOutcome::Responded(response)
}

/// Detailed local health classification used by `greggd status`.
///
/// Unlike [`CroncheckProbe`], which answers only "definitely running /
/// definitely absent / ambiguous", this distinguishes a valid Gregg
/// readiness state from an unreachable endpoint and from a peer that
/// answered but is not a valid Gregg health endpoint. It never infers
/// process ownership from port occupancy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HealthProbe {
    /// A valid Gregg endpoint reports `ready`.
    Ready,
    /// A valid Gregg endpoint reports `warming`.
    Warming,
    /// A valid Gregg endpoint reports `failed` (alive but unhealthy).
    Failed,
    /// No listener answered: refused, timed out, or otherwise unreachable.
    Unreachable,
    /// Something answered but it is not a valid Gregg health endpoint.
    NotGregg,
}

/// Run the authoritative bounded health probe and classify the result.
pub(crate) fn probe_health(target: SocketAddr) -> HealthProbe {
    match fetch_health_bytes(target) {
        FetchOutcome::Refused | FetchOutcome::Failed => HealthProbe::Unreachable,
        FetchOutcome::Responded(bytes) => match classify_health_response(&bytes) {
            Some(gregg_protocol::ReadinessState::Ready) => HealthProbe::Ready,
            Some(gregg_protocol::ReadinessState::Warming) => HealthProbe::Warming,
            Some(gregg_protocol::ReadinessState::Failed) => HealthProbe::Failed,
            None => HealthProbe::NotGregg,
        },
    }
}

pub(crate) fn probe_greggd(target: SocketAddr) -> CroncheckProbe {
    // Same bounded fetch and strict validation as probe_health; only the
    // three-way watchdog answer differs. Refusal alone permits spawning;
    // anything else that is not a valid Gregg response stays ambiguous.
    match fetch_health_bytes(target) {
        FetchOutcome::Refused => CroncheckProbe::Absent,
        FetchOutcome::Responded(bytes) if classify_health_response(&bytes).is_some() => {
            CroncheckProbe::Running
        }
        FetchOutcome::Responded(_) | FetchOutcome::Failed => CroncheckProbe::Ambiguous,
    }
}

/// Build the [`Command`] used by `croncheck` to spawn `greggd run` as a
/// detached watchdog child. Stdio is closed; the daemon's own logging is
/// independent of croncheck's. On Unix the child is placed in a new
/// process group so signals sent to croncheck's group (for example
/// SIGHUP from a closing terminal) do not reach the daemon.
///
/// Exposed crate-internally so tests can inspect `program()` and `get_args()`
/// without actually forking. The caller is responsible for `.spawn()`.
pub(crate) fn build_daemon_command(
    config_path: &std::path::Path,
    explicit: bool,
) -> std::io::Result<ProcessCommand> {
    let exe = std::env::current_exe()?;
    Ok(build_daemon_command_for(&exe, config_path, explicit))
}

pub(crate) fn build_daemon_command_for(
    exe: &std::path::Path,
    config_path: &std::path::Path,
    explicit: bool,
) -> ProcessCommand {
    let mut cmd = ProcessCommand::new(exe);
    cmd.arg("run");
    if explicit {
        cmd.arg("--config").arg(config_path);
    }
    cmd.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }

    cmd
}

/// Dispatch a subcommand using the path's current existence as a compatibility
/// fallback. The binary entry point uses [`dispatch_with_config_intent`] so a
/// missing explicit path remains distinguishable from a missing default path.
///
/// # Errors
///
/// Returns an error if the command fails.
pub fn dispatch(
    command: &Command,
    config_path: &std::path::Path,
) -> Result<(), Box<dyn std::error::Error>> {
    let explicit = !matches!(
        std::fs::metadata(config_path),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound
    );
    dispatch_with_config_intent(command, config_path, explicit)
}

/// Dispatch a command while preserving whether the config path was explicit.
#[allow(clippy::too_many_lines)]
pub fn dispatch_with_config_intent(
    command: &Command,
    config_path: &std::path::Path,
    explicit: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    match command {
        Command::Run => {
            // Delegate to the async run entry point.
            // This is handled in main.rs.
            unreachable!("Command::Run is handled in main.rs")
        }
        Command::Stop => {
            // Unix uses the local control socket and is dispatched at the
            // binary boundary (see main.rs) so it can return errors as the
            // runtime/library boundary without a global tracing init.
            #[cfg(unix)]
            {
                unreachable!("Command::Stop is handled at the binary boundary on Unix")
            }
            #[cfg(not(unix))]
            {
                unreachable!("Command::Stop is handled at the binary boundary on Windows")
            }
        }
        Command::Croncheck => {
            let config = load_config(config_path, explicit)?;
            let target = croncheck_target(&config);
            match probe_greggd(target) {
                CroncheckProbe::Running => Ok(()),
                CroncheckProbe::Absent => {
                    build_daemon_command(config_path, explicit)?.spawn()?;
                    Ok(())
                }
                CroncheckProbe::Ambiguous => Err(Box::new(std::io::Error::other(
                    "croncheck could not prove greggd is absent or healthy",
                ))),
            }
        }
        Command::Configprint => {
            let config = load_config(config_path, explicit)?;
            println!("{}", display_address(&config));
            Ok(())
        }
        Command::Status => {
            let config = load_config(config_path, explicit)?;
            let report = crate::status::gather_status(
                &config,
                config_path,
                version_string(),
                probe_health,
                crate::startup::startup_state(),
            );
            print!("{}", crate::status::render_status(&report));
            if crate::status::status_is_present(&report) {
                Ok(())
            } else {
                Err(Box::new(std::io::Error::other(format!(
                    "greggd status: configured endpoint is {} (health: {})",
                    crate::status::status_outcome(&report),
                    crate::status::health_token(report.health),
                ))) as Box<dyn std::error::Error>)
            }
        }
        Command::Host { address } => mutate_config(config_path, explicit, |config| {
            config.host = *address;
        }),
        Command::Port { port } => mutate_config(config_path, explicit, |config| {
            config.port = *port;
        }),
        Command::Uninstall { dry_run, purge } => {
            crate::uninstall::run_uninstall(config_path, explicit, *dry_run, *purge)
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
        }
        Command::Version => {
            println!("{}", version_string());
            Ok(())
        }
        Command::Update => {
            let outcome = crate::update::run_update(config_path, explicit)
                .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
            match outcome {
                crate::update::UpdateOutcome::AlreadyCurrent { .. }
                | crate::update::UpdateOutcome::UpdatedBinary { .. }
                | crate::update::UpdateOutcome::UpdatedFromCargo { .. } => {
                    println!("{outcome}");
                    Ok(())
                }
                crate::update::UpdateOutcome::UpdatedButRestartFailed { .. } => {
                    // update.rs already printed the installed version and the
                    // exact restart command needed; convert to a nonzero exit
                    // so automation notices incomplete activation.
                    eprintln!("{outcome}");
                    Err(Box::new(crate::update::UpdateError::RestartFailed(
                        outcome.to_string(),
                    )) as Box<dyn std::error::Error>)
                }
            }
        }
        Command::Restart => {
            #[cfg(target_os = "windows")]
            {
                unreachable!("Windows service commands are dispatched at the binary boundary")
            }
            #[cfg(not(target_os = "windows"))]
            {
                let exe = std::env::current_exe()?;
                crate::startup::restart_daemon(&exe, config_path, explicit)
                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
                Ok(())
            }
        }
        Command::Startup { command } => match command {
            StartupCommand::Install { method } => {
                let exe = std::env::current_exe()?;
                crate::startup::install_startup(&exe, config_path, explicit, *method)
                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
                Ok(())
            }
            StartupCommand::Instructions { method } => {
                let exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("greggd"));
                let resolved = crate::startup::resolve_startup_method(*method);
                let text =
                    crate::startup::render_instructions(resolved, &exe, config_path, explicit);
                println!("{text}");
                Ok(())
            }
        },
        #[cfg(target_os = "windows")]
        Command::Start => {
            unreachable!("Windows service commands are dispatched at the binary boundary")
        }
        #[cfg(target_os = "windows")]
        Command::Service => {
            unreachable!("Command::Service is handled in main.rs")
        }
    }
}

#[cfg(all(test, not(target_os = "windows")))]
mod native_tests {
    use super::*;
    use clap::Parser;
    use std::net::TcpListener;

    #[test]
    fn parser_accepts_run_stop_croncheck_mutations_and_version_but_not_windows_lifecycle() {
        for args in [
            "run",
            "stop",
            "croncheck",
            "configprint",
            "version",
            "restart",
        ] {
            let argv = if args == "host" {
                vec!["greggd", "host", "127.0.0.1"]
            } else if args == "port" {
                vec!["greggd", "port", "11310"]
            } else {
                vec!["greggd", args]
            };
            assert!(Cli::try_parse_from(argv).is_ok(), "failed to parse {args}");
        }
        assert!(Cli::try_parse_from(["greggd", "host", "127.0.0.1"]).is_ok());
        assert!(Cli::try_parse_from(["greggd", "port", "11310"]).is_ok());
        assert!(Cli::try_parse_from(["greggd", "startup", "install"]).is_ok());
        assert!(
            Cli::try_parse_from(["greggd", "startup", "install", "--method", "systemd"]).is_ok()
        );
        assert!(Cli::try_parse_from(["greggd", "startup", "install", "--method", "cron"]).is_ok());
        assert!(Cli::try_parse_from(["greggd", "uninstall"]).is_ok());
        assert!(Cli::try_parse_from(["greggd", "uninstall", "--dry-run", "--purge"]).is_ok());
        assert!(Cli::try_parse_from(["greggd", "startup", "instructions"]).is_ok());
        assert!(
            Cli::try_parse_from(["greggd", "startup", "instructions", "--method", "launchd"])
                .is_ok()
        );
        // `croncheck` no longer takes a `--target` flag: it operates on
        // the configured local bind only.
        assert!(
            Cli::try_parse_from(["greggd", "croncheck", "--target", "192.168.182.143:11310"])
                .is_err()
        );
        {
            let command = "start";
            assert!(Cli::try_parse_from(["greggd", command]).is_err());
        }
    }

    #[test]
    fn wildcard_probe_addresses_use_loopback() {
        assert_eq!(
            probe_address("0.0.0.0".parse::<IpAddr>().unwrap()),
            "127.0.0.1".parse::<IpAddr>().unwrap()
        );
        assert_eq!(
            probe_address("::".parse::<IpAddr>().unwrap()),
            "::1".parse::<IpAddr>().unwrap()
        );
        assert_eq!(
            probe_address("192.0.2.1".parse::<IpAddr>().unwrap()),
            "192.0.2.1".parse::<IpAddr>().unwrap()
        );
    }

    #[test]
    fn config_address_preserves_wildcards_and_formats_ipv6() {
        let mut config = Config::default();
        assert_eq!(config_address(&config).to_string(), "0.0.0.0:11310");
        config.host = "fd00::10".parse().unwrap();
        config.port = 11320;
        assert_eq!(config_address(&config).to_string(), "[fd00::10]:11320");
    }

    #[test]
    fn display_address_preserves_specific_hosts() {
        let config = Config {
            host: "192.168.182.143".parse().unwrap(),
            port: 11310,
            ..Config::default()
        };
        assert_eq!(
            display_address_from(&config, || None, || None).to_string(),
            "192.168.182.143:11310"
        );
        let config = Config {
            host: "fd00::10".parse().unwrap(),
            port: 11320,
            ..Config::default()
        };
        assert_eq!(
            display_address_from(&config, || None, || None).to_string(),
            "[fd00::10]:11320"
        );
    }

    #[test]
    fn display_address_resolves_ipv4_wildcard_to_local_ipv4() {
        let config = Config {
            host: "0.0.0.0".parse().unwrap(),
            ..Config::default()
        };
        let resolved = display_address_from(
            &config,
            || Some("192.168.182.143".parse().unwrap()),
            || None,
        );
        assert_eq!(resolved.to_string(), "192.168.182.143:11310");
    }

    #[test]
    fn display_address_resolves_ipv6_wildcard_to_local_ipv6() {
        let config = Config {
            host: "::".parse().unwrap(),
            ..Config::default()
        };
        let resolved = display_address_from(&config, || None, || Some("fd00::10".parse().unwrap()));
        assert_eq!(resolved.to_string(), "[fd00::10]:11310");
    }

    #[test]
    fn display_address_falls_back_from_ipv6_to_ipv4_wildcard() {
        let config = Config {
            host: "::".parse().unwrap(),
            ..Config::default()
        };
        let resolved = display_address_from(
            &config,
            || Some("192.168.182.143".parse().unwrap()),
            || None,
        );
        assert_eq!(resolved.to_string(), "192.168.182.143:11310");
    }

    #[test]
    fn display_address_preserves_wildcard_when_no_local_address() {
        let config = Config {
            host: "0.0.0.0".parse().unwrap(),
            ..Config::default()
        };
        let resolved = display_address_from(&config, || None, || None);
        assert_eq!(resolved.to_string(), "0.0.0.0:11310");

        let config = Config {
            host: "::".parse().unwrap(),
            ..Config::default()
        };
        let resolved = display_address_from(&config, || None, || None);
        assert_eq!(resolved.to_string(), "[::]:11310");
    }

    #[test]
    fn display_address_prefers_configured_loopback_over_resolved_address() {
        // 127.0.0.1 is loopback but not unspecified, so it must pass
        // through unchanged; resolution only applies to wildcards.
        let config = Config {
            host: "127.0.0.1".parse().unwrap(),
            ..Config::default()
        };
        let resolved = display_address_from(
            &config,
            || Some("192.168.182.143".parse().unwrap()),
            || None,
        );
        assert_eq!(resolved.to_string(), "127.0.0.1:11310");
    }

    #[test]
    fn configprint_uses_default_for_missing_implicit_config() {
        let path =
            std::env::temp_dir().join(format!("greggd-configprint-{}.toml", std::process::id()));
        let _ = std::fs::remove_file(&path);
        dispatch_with_config_intent(&Command::Configprint, &path, false).unwrap();
        assert!(!path.exists());
    }

    #[test]
    fn configprint_rejects_missing_explicit_config() {
        let path = std::env::temp_dir().join(format!(
            "greggd-configprint-missing-{}.toml",
            std::process::id(),
        ));
        let _ = std::fs::remove_file(&path);
        assert!(dispatch_with_config_intent(&Command::Configprint, &path, true).is_err());
    }

    #[test]
    fn load_config_propagates_non_not_found_metadata_errors() {
        let dir = std::env::temp_dir().join(format!("greggd-config-error-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let blocker = dir.join("blocker");
        std::fs::write(&blocker, b"not a directory").unwrap();
        let path = blocker.join("config.toml");

        let result = load_config(&path, false);
        assert!(matches!(
            result,
            Err(ConfigError::Io { source, .. })
                if source.kind() == std::io::ErrorKind::NotADirectory
        ));
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn version_string_uses_package_version() {
        assert_eq!(
            version_string(),
            format!("greggd {}", env!("CARGO_PKG_VERSION"))
        );
    }

    #[test]
    fn config_mutation_is_persisted_without_service_dispatch() {
        let dir = std::env::temp_dir().join("greggd_native_mutation_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        mutate_config(&path, false, |config| config.port = 11320).unwrap();
        assert_eq!(Config::load(&path).unwrap().port, 11320);
        let _ = std::fs::remove_dir_all(dir);
    }

    fn http_fixture(status: u16, body: &str) -> SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let target = listener.local_addr().unwrap();
        let body = body.to_string();
        std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut request = [0_u8; 1024];
                let _ = stream.read(&mut request);
                let response = format!("HTTP/1.1 {status} Test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
                let _ = stream.write_all(response.as_bytes());
            }
        });
        target
    }

    fn silent_fixture() -> SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let target = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                let mut request = [0_u8; 1024];
                let _ = stream.read(&mut request);
                std::thread::sleep(Duration::from_secs(2));
            }
        });
        target
    }

    fn unbound_loopback() -> SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        listener.local_addr().unwrap()
    }

    #[test]
    fn croncheck_accepts_a_warming_health_response() {
        let target = http_fixture(
            503,
            r#"{"schema_version":2,"state":"warming","category":"warming","message":"warming"}"#,
        );
        assert_eq!(probe_greggd(target), CroncheckProbe::Running);
    }

    #[test]
    fn croncheck_refuses_a_closed_port() {
        let target = unbound_loopback();
        assert_eq!(probe_greggd(target), CroncheckProbe::Absent);
    }

    #[test]
    fn croncheck_accepts_a_failed_health_response() {
        let target = http_fixture(
            503,
            r#"{"schema_version":2,"state":"failed","category":"collector_failure","message":"failed"}"#,
        );
        assert_eq!(probe_greggd(target), CroncheckProbe::Running);
    }

    #[test]
    fn croncheck_rejects_unrelated_http() {
        let target = http_fixture(200, r#"{"ok":true}"#);
        assert_eq!(probe_greggd(target), CroncheckProbe::Ambiguous);
    }

    #[test]
    fn croncheck_rejects_malformed_health() {
        let target = http_fixture(200, "not-json");
        assert_eq!(probe_greggd(target), CroncheckProbe::Ambiguous);
    }

    #[test]
    fn croncheck_rejects_silent_peer_within_bound() {
        let target = silent_fixture();
        assert_eq!(probe_greggd(target), CroncheckProbe::Ambiguous);
    }

    #[test]
    fn croncheck_dispatch_exits_when_greggd_is_running_without_spawning() {
        // A valid non-ready Gregg health response still proves the daemon
        // exists; croncheck must not start a second copy.
        let target = http_fixture(
            503,
            r#"{"schema_version":2,"state":"failed","category":"collector_failure","message":"failed"}"#,
        );
        let dir = std::env::temp_dir().join("greggd_croncheck_listener_up_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("greggd.toml");
        std::fs::write(
            &path,
            format!(
                "name = \"loopback-croncheck-test\"\n\
                 host = \"127.0.0.1\"\n\
                 port = {}\n\
                 sample_interval_ms = 1000\n\
                 stale_after_ms = 10000\n",
                target.port()
            ),
        )
        .unwrap();
        dispatch_with_config_intent(&Command::Croncheck, &path, true).unwrap();
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn build_daemon_command_includes_run_and_explicit_config() {
        let dir = std::env::temp_dir().join("greggd_build_daemon_explicit_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        let cmd = build_daemon_command(&path, true).unwrap();
        assert_eq!(
            cmd.get_program(),
            std::env::current_exe().unwrap().as_os_str()
        );
        let args: Vec<std::ffi::OsString> =
            cmd.get_args().map(std::ffi::OsStr::to_os_string).collect();
        assert_eq!(
            args,
            vec![
                std::ffi::OsString::from("run"),
                std::ffi::OsString::from("--config"),
                path.as_os_str().to_os_string(),
            ]
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn build_daemon_command_omits_config_when_implicit() {
        let cmd = build_daemon_command(std::path::Path::new("/nonexistent.toml"), false).unwrap();
        assert_eq!(
            cmd.get_program(),
            std::env::current_exe().unwrap().as_os_str()
        );
        let args: Vec<std::ffi::OsString> =
            cmd.get_args().map(std::ffi::OsStr::to_os_string).collect();
        assert_eq!(args, vec![std::ffi::OsString::from("run")]);
    }
}