Skip to main content

eggup_service/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3#![doc = "Manager-neutral service registration, ownership, and lifecycle model"]
4#![doc = "plus Unix manager mechanics and a native Windows SCM adapter."]
5#![doc = ""]
6#![doc = "Destructive manager operations are authorized only for `Owned`"]
7#![doc = "registrations. `Foreign` and `Unknown` fail closed. Manager state and"]
8#![doc = "application health are separate. No privilege escalation, no updater or"]
9#![doc = "transport policy, and no shell interpolation live in this crate."]
10
11mod commit_engine;
12mod disposition;
13mod lifecycle_update;
14mod windows_scm;
15pub use commit_engine::{
16    CommitEnginePolicy, LifecycleFailure, LifecycleUpdatePhase, NoPostInstallCheck,
17    OwnershipLossTolerance, PostInstallCheck, PostInstallCheckError, PostTransitionVerification,
18};
19pub use disposition::{
20    commit_with_disposition, commit_with_disposition_with_engine_policy, plan_unix, plan_windows,
21    DirectObservation, DirectRuntimeControl, DirectState, DispositionBaseline, KnownConfig,
22    UnixPlannerInput, UpdateRuntimeDisposition, WindowsPlannerInput, WindowsServiceState,
23};
24pub use lifecycle_update::{
25    commit_with_lifecycle, commit_with_lifecycle_with_engine_policy, LifecycleRestorationStatus,
26    LifecycleUpdateError, LifecycleUpdatePolicy, LifecycleUpdateReceipt,
27};
28pub use windows_scm::{
29    WindowsErrorControl, WindowsScmInstall, WindowsScmManager, WindowsServiceDependency,
30    WindowsStartType,
31};
32
33use std::collections::{HashMap, VecDeque};
34use std::fmt;
35use std::path::{Path, PathBuf};
36use std::sync::Mutex;
37use std::time::{Duration, Instant};
38
39/// A validated opaque service identity (unit name, launchd label, SCM name).
40#[derive(Debug, Clone, PartialEq, Eq, Hash)]
41pub struct ServiceId(String);
42
43impl ServiceId {
44    /// Creates an identifier, rejecting empty, overlong, or control-character input.
45    ///
46    /// # Errors
47    ///
48    /// [`ServiceError::InvalidInput`] when the value is empty, longer than 256
49    /// bytes, or contains a control character.
50    pub fn new(value: impl Into<String>) -> Result<Self, ServiceError> {
51        let value = value.into();
52        if value.is_empty() || value.len() > 256 || value.chars().any(char::is_control) {
53            return Err(ServiceError::invalid(
54                "service id is empty, overlong, or has controls",
55            ));
56        }
57        Ok(Self(value))
58    }
59
60    /// Returns the stable string form.
61    pub fn as_str(&self) -> &str {
62        &self.0
63    }
64}
65
66impl fmt::Display for ServiceId {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.write_str(&self.0)
69    }
70}
71
72/// Consumer-supplied desired registration.
73///
74/// Identity includes the exact executable path plus critical arguments and an
75/// optional config path. Ownership compares all three: same name with a
76/// different executable is `Foreign`; same executable with different critical
77/// args is `Foreign` (documented rule); malformed registrations are `Unknown`.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct ServiceSpec {
80    id: ServiceId,
81    executable: PathBuf,
82    args: Vec<String>,
83    config: Option<PathBuf>,
84}
85
86impl ServiceSpec {
87    /// Creates a spec, validating the id, absolute executable, and arg safety.
88    ///
89    /// # Errors
90    ///
91    /// [`ServiceError::InvalidInput`] when the executable is not absolute or is
92    /// empty, when an argument contains a control character, or when the
93    /// optional config path is not absolute.
94    pub fn new(
95        id: ServiceId,
96        executable: PathBuf,
97        args: Vec<String>,
98        config: Option<PathBuf>,
99    ) -> Result<Self, ServiceError> {
100        if !executable.is_absolute() {
101            return Err(ServiceError::invalid("executable must be absolute"));
102        }
103        if executable.as_os_str().is_empty() {
104            return Err(ServiceError::invalid("executable must name a file"));
105        }
106        for a in &args {
107            if a.chars().any(char::is_control) {
108                return Err(ServiceError::invalid("argument has control characters"));
109            }
110        }
111        if let Some(c) = &config {
112            if !c.is_absolute() {
113                return Err(ServiceError::invalid("config path must be absolute"));
114            }
115        }
116        Ok(Self {
117            id,
118            executable,
119            args,
120            config,
121        })
122    }
123
124    /// Returns the service identity.
125    pub fn id(&self) -> &ServiceId {
126        &self.id
127    }
128
129    /// Returns the exact executable path.
130    pub fn executable(&self) -> &std::path::Path {
131        &self.executable
132    }
133
134    /// Returns critical arguments participating in ownership.
135    pub fn args(&self) -> &[String] {
136        &self.args
137    }
138
139    /// Returns the optional config path participating in ownership.
140    pub fn config(&self) -> Option<&std::path::Path> {
141        self.config.as_deref()
142    }
143}
144
145/// Canonical ownership classification, re-exported from `eggup-core`.
146///
147/// This is **the same type** as [`eggup_core::Ownership`], not a copy of it:
148/// `eggup_service::Ownership` and `eggup_core::Ownership` denote one type, so
149/// no conversion between them exists or is needed anywhere in the workspace.
150///
151/// # Service-context meaning
152///
153/// `eggup-core` states this classification in *destination* terms, because it
154/// classifies a filesystem object. The service crate uses the same
155/// classification for a *manager registration*:
156///
157/// * `Absent` — no registration exists under this identity;
158/// * `Owned` — the registration exactly matches this deployment and may be
159///   mutated;
160/// * `Foreign` — the registration belongs to another deployment and must not
161///   be mutated;
162/// * `Unknown` — ownership cannot be proven, so mutation is denied.
163///
164/// The core wording must not be read unqualified here: in the service context
165/// "destination" means the registered service unit, launchd label, or SCM
166/// service that the caller's identity claims.
167///
168/// # Fail-closed rule
169///
170/// `Owned` is **never inferred**. It is returned only by a caller-proven
171/// ownership check — in the service crate, by the manager adapter's exact
172/// identity comparison against the requested spec. `Foreign` and `Unknown`
173/// always fail closed: they are never destructively mutated, and they never
174/// produce a successful mutation outcome. See [`eggup_core::Ownership`] for
175/// core's canonical statement of the same rule.
176pub use eggup_core::Ownership;
177
178/// Manager-neutral lifecycle state. Health is separate.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180#[non_exhaustive]
181pub enum LifecycleState {
182    /// Registered but not running.
183    Stopped,
184    /// Running.
185    Running,
186    /// Start/stop/restart in flight.
187    Transitioning,
188    /// State cannot be determined.
189    Unknown,
190}
191
192/// Application health, distinct from manager state.
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194#[non_exhaustive]
195pub enum HealthState {
196    /// The application reports healthy.
197    Healthy,
198    /// The application reports degraded/unhealthy.
199    Degraded,
200    /// Health is unknown or no probe is configured.
201    Unknown,
202}
203
204/// A manager-neutral registration observation.
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct RegistrationSnapshot {
207    /// Whether a registration record exists.
208    pub present: bool,
209    /// The recorded executable, when present and parseable.
210    pub executable: Option<PathBuf>,
211    /// Recorded critical args, when parseable.
212    pub args: Vec<String>,
213    /// Recorded config path, when parseable.
214    pub config: Option<PathBuf>,
215    /// Whether the record was malformed.
216    pub malformed: bool,
217}
218
219impl RegistrationSnapshot {
220    /// An absent registration.
221    pub fn absent() -> Self {
222        Self {
223            present: false,
224            executable: None,
225            args: Vec::new(),
226            config: None,
227            malformed: false,
228        }
229    }
230
231    /// Classifies this observation against the desired spec.
232    pub fn ownership(&self, spec: &ServiceSpec) -> Ownership {
233        if !self.present {
234            return Ownership::Absent;
235        }
236        if self.malformed {
237            return Ownership::Unknown;
238        }
239        match &self.executable {
240            None => Ownership::Unknown,
241            Some(exe) if exe != spec.executable() => Ownership::Foreign,
242            Some(_) if self.args != spec.args => Ownership::Foreign,
243            Some(_) if self.config.as_deref() != spec.config() => Ownership::Foreign,
244            Some(_) => Ownership::Owned,
245        }
246    }
247}
248
249/// A point-in-time lifecycle observation plus desired restoration intent.
250#[derive(Debug, Clone, PartialEq, Eq)]
251pub struct LifecycleSnapshot {
252    /// The service identity observed.
253    pub id: ServiceId,
254    /// Ownership at observation time.
255    pub ownership: Ownership,
256    /// Manager state at observation time.
257    pub state: LifecycleState,
258    /// Health at observation time (never mutates manager state).
259    pub health: HealthState,
260    /// Whether the service was registered at observation time.
261    pub was_registered: bool,
262    /// Whether the service was running at observation time.
263    pub was_running: bool,
264}
265
266impl LifecycleSnapshot {
267    /// The restoration intent: restart only if it was running.
268    pub fn restore_running(&self) -> bool {
269        self.was_running
270    }
271}
272
273/// Desired post-update restoration.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275pub enum RestoreIntent {
276    /// Return to the observed running/stopped state.
277    Preserve,
278    /// Ensure running (explicit caller policy; overrides stopped-stays-stopped).
279    EnsureRunning,
280    /// Ensure stopped.
281    EnsureStopped,
282}
283
284/// Bounded transition outcome with conflict diagnostics.
285#[derive(Debug, Clone, PartialEq, Eq)]
286pub struct TransitionResult {
287    /// What was attempted.
288    pub operation: ServiceOperation,
289    /// Whether the manager reports the desired end state.
290    pub completed: bool,
291    /// Bounded human-readable detail (never embeds secrets).
292    pub detail: String,
293}
294
295impl TransitionResult {
296    /// Returns whether the operation completed.
297    pub fn completed(&self) -> bool {
298        self.completed
299    }
300}
301
302/// Manager operations. Destructive variants require `Owned`.
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
304#[non_exhaustive]
305pub enum ServiceOperation {
306    /// Inspect registration and state (always allowed).
307    Inspect,
308    /// Install/register (allowed for `Absent` with caller authorization, or `Owned` refresh).
309    Install,
310    /// Start an `Owned` stopped service.
311    Start,
312    /// Stop an `Owned` running service.
313    Stop,
314    /// Restart an `Owned` service.
315    Restart,
316    /// Remove an `Owned` registration.
317    Uninstall,
318}
319
320/// Machine-readable classification of a manager failure.
321///
322/// The kind — not the detail text — is the carrier of meaning. A consumer
323/// distinguishes "the manager timed out" from "the manager binary is missing"
324/// from "you lack privileges" by matching this value; nothing in this crate
325/// classifies a failure by substring-matching its own error text.
326///
327/// Every [`ServiceError::Manager`] construction site in this crate maps to
328/// exactly one kind. There is no "unclassified" fallback.
329///
330/// # Known limitation
331///
332/// A manager that *runs* and reports an access denial in its own stderr is
333/// [`ManagerFailureKind::Protocol`], because the platform supplied no
334/// structured denial. Only a structured platform denial — a Unix
335/// [`std::io::ErrorKind::PermissionDenied`] from the spawn path, or a Windows
336/// SCM access-denied code — is [`ManagerFailureKind::Permission`].
337#[derive(Debug, Clone, Copy, PartialEq, Eq)]
338#[non_exhaustive]
339pub enum ManagerFailureKind {
340    /// The manager child could not be created or driven.
341    Spawn,
342    /// A deadline expired before or during a manager command.
343    Timeout,
344    /// The platform reported an access denial.
345    Permission,
346    /// The manager program, or a manager resource it names, does not exist.
347    NotFound,
348    /// The manager ran and produced a result this crate cannot accept: a
349    /// non-zero exit on a mutation, malformed manager output, or an output
350    /// bound violation.
351    Protocol,
352    /// A local filesystem operation failed (definition write, unit removal).
353    LocalFilesystem,
354}
355
356impl ManagerFailureKind {
357    /// Classifies a manager child-creation failure from an operating-system error.
358    ///
359    /// `NotFound` maps to [`ManagerFailureKind::NotFound`], `PermissionDenied`
360    /// maps to [`ManagerFailureKind::Permission`], and every other error kind
361    /// maps to [`ManagerFailureKind::Spawn`]. This is a pure function: it
362    /// never inspects a message and never needs a real privilege failure.
363    pub fn from_spawn_error(error: &std::io::Error) -> Self {
364        match error.kind() {
365            std::io::ErrorKind::NotFound => Self::NotFound,
366            std::io::ErrorKind::PermissionDenied => Self::Permission,
367            _ => Self::Spawn,
368        }
369    }
370
371    /// Classifies a Windows SCM (Win32) OS error code.
372    ///
373    /// `5` (access denied) maps to [`ManagerFailureKind::Permission`], `1060`
374    /// (the specified service does not exist) maps to
375    /// [`ManagerFailureKind::NotFound`], and every other code maps to
376    /// [`ManagerFailureKind::Protocol`]. This is a pure function and is
377    /// platform-independent, so it is assertable on every lane.
378    pub fn from_scm_os_code(code: Option<i32>) -> Self {
379        match code {
380            Some(5) => Self::Permission,
381            Some(1060) => Self::NotFound,
382            _ => Self::Protocol,
383        }
384    }
385}
386
387impl fmt::Display for ManagerFailureKind {
388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389        let name = match self {
390            Self::Spawn => "spawn",
391            Self::Timeout => "timeout",
392            Self::Permission => "permission",
393            Self::NotFound => "not-found",
394            Self::Protocol => "protocol",
395            Self::LocalFilesystem => "local-filesystem",
396        };
397        f.write_str(name)
398    }
399}
400
401/// Typed service errors. Destructive attempts on `Foreign`/`Unknown` fail here.
402/// Error strings produced by crate helpers are capped at
403/// [`MAX_DIAGNOSTIC_BYTES`] UTF-8-safe bytes.
404#[derive(Debug, Clone, PartialEq, Eq)]
405#[non_exhaustive]
406pub enum ServiceError {
407    /// Caller input violates the contract.
408    InvalidInput(String),
409    /// The registration is foreign or unknown; destructive mutation denied.
410    OwnershipDenied {
411        /// The service identity.
412        id: String,
413        /// The observed ownership.
414        ownership: Ownership,
415    },
416    /// The manager reported a conflict (already exists, not found, transitioning).
417    Conflict(String),
418    /// A bounded manager call failed.
419    Manager {
420        /// The machine-readable failure classification.
421        kind: ManagerFailureKind,
422        /// The bounded diagnostic detail: the manager's own bounded stderr
423        /// excerpt, or the crate's bounded description of the failure.
424        detail: String,
425        /// The platform error code, when the platform supplied a structured
426        /// one. Windows SCM failures keep their raw OS code here so the
427        /// mapping stays lossless.
428        os_code: Option<i32>,
429    },
430}
431
432impl ServiceError {
433    pub(crate) fn invalid(detail: impl Into<String>) -> Self {
434        Self::InvalidInput(truncate_utf8_bytes(detail.into(), MAX_DIAGNOSTIC_BYTES))
435    }
436
437    pub(crate) fn bounded(detail: impl Into<String>) -> String {
438        truncate_utf8_bytes(detail.into(), MAX_DIAGNOSTIC_BYTES)
439    }
440
441    pub(crate) fn conflict(detail: impl Into<String>) -> Self {
442        Self::Conflict(Self::bounded(detail))
443    }
444
445    /// Builds a manager failure with the given classification.
446    ///
447    /// The detail is bounded at [`MAX_DIAGNOSTIC_BYTES`] UTF-8-safe bytes.
448    pub fn manager(kind: ManagerFailureKind, detail: impl Into<String>) -> Self {
449        Self::Manager {
450            kind,
451            detail: Self::bounded(detail),
452            os_code: None,
453        }
454    }
455
456    /// Builds a manager failure that carries a platform error code.
457    ///
458    /// The detail is bounded at [`MAX_DIAGNOSTIC_BYTES`] UTF-8-safe bytes. The
459    /// code stays reachable through [`ServiceError::manager_os_code`], so a
460    /// platform mapping never degrades into a rendered sentence.
461    pub fn manager_with_os_code(
462        kind: ManagerFailureKind,
463        detail: impl Into<String>,
464        os_code: Option<i32>,
465    ) -> Self {
466        Self::Manager {
467            kind,
468            detail: Self::bounded(detail),
469            os_code,
470        }
471    }
472
473    /// Reports an ownership denial.
474    pub fn denied(id: &ServiceId, ownership: Ownership) -> Self {
475        Self::OwnershipDenied {
476            id: id.as_str().to_string(),
477            ownership,
478        }
479    }
480
481    /// Returns the manager failure kind, when this is a manager failure.
482    ///
483    /// This is the programmatic discriminator: a consumer matches on the
484    /// returned kind instead of inspecting [`ServiceError::Manager`]'s detail
485    /// text.
486    pub fn manager_kind(&self) -> Option<ManagerFailureKind> {
487        match self {
488            Self::Manager { kind, .. } => Some(*kind),
489            _ => None,
490        }
491    }
492
493    /// Returns the platform error code of a manager failure, when the platform
494    /// supplied a structured one.
495    pub fn manager_os_code(&self) -> Option<i32> {
496        match self {
497            Self::Manager { os_code, .. } => *os_code,
498            _ => None,
499        }
500    }
501}
502
503impl fmt::Display for ServiceError {
504    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
505        match self {
506            Self::InvalidInput(d) => write!(f, "invalid service input: {d}"),
507            Self::OwnershipDenied { id, ownership } => {
508                write!(f, "service {id} ownership denies mutation ({ownership:?})")
509            }
510            Self::Conflict(d) => write!(f, "service conflict: {d}"),
511            Self::Manager {
512                kind,
513                detail,
514                os_code,
515            } => match os_code {
516                Some(code) => write!(
517                    f,
518                    "service manager failed ({kind}, os code {code}): {detail}"
519                ),
520                None => write!(f, "service manager failed ({kind}): {detail}"),
521            },
522        }
523    }
524}
525
526impl std::error::Error for ServiceError {}
527
528/// Consumer-supplied health probe. Read-only: never mutates manager state.
529pub trait HealthProbe: fmt::Debug {
530    /// Checks application health for an `Owned` service.
531    fn check(&self, spec: &ServiceSpec) -> HealthState;
532}
533
534/// Null probe: health is always unknown.
535#[derive(Debug, Default)]
536pub struct NoProbe;
537
538impl HealthProbe for NoProbe {
539    fn check(&self, _spec: &ServiceSpec) -> HealthState {
540        HealthState::Unknown
541    }
542}
543
544/// Manager-neutral service operations. Platform adapters implement this in
545/// later milestones; `TestDoubleManager` implements it for tests.
546pub trait ServiceManager {
547    /// Inspects registration and lifecycle state without mutating anything.
548    ///
549    /// # Errors
550    ///
551    /// [`ServiceError::Manager`] with a classified [`ManagerFailureKind`]:
552    /// `Timeout` when the operation's deadline expires, `NotFound` when the
553    /// manager binary or a named manager resource does not exist, `Permission`
554    /// when the platform reports an access denial, `Spawn` when the manager
555    /// child cannot be created or driven, and `Protocol` when the manager ran
556    /// and produced a result the adapter cannot accept.
557    ///
558    /// [`ServiceError::InvalidInput`] when the adapter cannot answer for the
559    /// given spec.
560    fn inspect(&self, spec: &ServiceSpec) -> Result<LifecycleSnapshot, ServiceError>;
561
562    /// Installs/registers. Allowed for `Absent` (creation) or `Owned` (refresh).
563    ///
564    /// # Errors
565    ///
566    /// [`ServiceError::OwnershipDenied`] when the observed ownership is
567    /// `Foreign` or `Unknown`, or when a pre-write recheck no longer proves
568    /// `Owned`.
569    ///
570    /// [`ServiceError::Manager`] with a classified [`ManagerFailureKind`]:
571    /// `Timeout` when the operation's deadline expires, `NotFound` when the
572    /// manager binary or a named manager resource does not exist, `Permission`
573    /// when the platform reports an access denial, `Spawn` when the manager
574    /// child cannot be created or driven, `Protocol` when the manager ran and
575    /// produced a result the adapter cannot accept, and `LocalFilesystem` when
576    /// a local definition write or removal failed.
577    ///
578    /// [`ServiceError::InvalidInput`] when the request material is
579    /// inconsistent with the spec.
580    ///
581    /// [`ServiceError::Conflict`] when a no-replace write lost a race with a
582    /// concurrent creation.
583    fn install(&mut self, spec: &ServiceSpec) -> Result<TransitionResult, ServiceError>;
584
585    /// Starts an `Owned` stopped service within `timeout`.
586    ///
587    /// # Errors
588    ///
589    /// [`ServiceError::OwnershipDenied`] when the observed ownership is not
590    /// `Owned`.
591    ///
592    /// [`ServiceError::Manager`] with a classified [`ManagerFailureKind`]:
593    /// `Timeout` when the deadline expires, `NotFound` when the manager binary
594    /// or a named manager resource does not exist, `Permission` when the
595    /// platform reports an access denial, `Spawn` when the manager child
596    /// cannot be created or driven, and `Protocol` when the manager ran and
597    /// produced a result the adapter cannot accept.
598    ///
599    /// [`ServiceError::InvalidInput`] when `timeout` is out of range, or when
600    /// the adapter has no start semantics (a cron adapter).
601    fn start(
602        &mut self,
603        spec: &ServiceSpec,
604        timeout: Duration,
605    ) -> Result<TransitionResult, ServiceError>;
606
607    /// Stops an `Owned` service within `timeout`.
608    ///
609    /// An adapter may stop a recognized manager failure state only when exact
610    /// ownership is revalidated and it can prove there is no remaining work.
611    /// Other unknown states fail closed.
612    ///
613    /// # Errors
614    ///
615    /// [`ServiceError::OwnershipDenied`] when the observed ownership is not
616    /// `Owned`.
617    ///
618    /// [`ServiceError::Manager`] with a classified [`ManagerFailureKind`]:
619    /// `Timeout` when the deadline expires, `NotFound` when the manager binary
620    /// or a named manager resource does not exist, `Permission` when the
621    /// platform reports an access denial, `Spawn` when the manager child
622    /// cannot be created or driven, and `Protocol` when the manager ran and
623    /// produced a result the adapter cannot accept.
624    ///
625    /// [`ServiceError::InvalidInput`] when `timeout` is out of range, or when
626    /// the adapter has no stop semantics (a cron adapter).
627    fn stop(
628        &mut self,
629        spec: &ServiceSpec,
630        timeout: Duration,
631    ) -> Result<TransitionResult, ServiceError>;
632
633    /// Restarts an `Owned` service within `timeout`.
634    ///
635    /// # Errors
636    ///
637    /// [`ServiceError::OwnershipDenied`] when the observed ownership is not
638    /// `Owned`.
639    ///
640    /// [`ServiceError::Manager`] with a classified [`ManagerFailureKind`]:
641    /// `Timeout` when the deadline expires, `NotFound` when the manager binary
642    /// or a named manager resource does not exist, `Permission` when the
643    /// platform reports an access denial, `Spawn` when the manager child
644    /// cannot be created or driven, and `Protocol` when the manager ran and
645    /// produced a result the adapter cannot accept.
646    ///
647    /// [`ServiceError::InvalidInput`] when `timeout` is out of range, or when
648    /// the adapter has no restart semantics (a cron adapter).
649    fn restart(
650        &mut self,
651        spec: &ServiceSpec,
652        timeout: Duration,
653    ) -> Result<TransitionResult, ServiceError>;
654
655    /// Removes an `Owned` registration.
656    ///
657    /// # Errors
658    ///
659    /// [`ServiceError::OwnershipDenied`] when the observed ownership is not
660    /// `Owned`, or when a pre-write recheck no longer proves `Owned`.
661    ///
662    /// [`ServiceError::Manager`] with a classified [`ManagerFailureKind`]:
663    /// `Timeout` when the operation's deadline expires, `NotFound` when the
664    /// manager binary or a named manager resource does not exist, `Permission`
665    /// when the platform reports an access denial, `Spawn` when the manager
666    /// child cannot be created or driven, `Protocol` when the manager ran and
667    /// produced a result the adapter cannot accept, and `LocalFilesystem` when
668    /// a local definition removal failed.
669    ///
670    /// [`ServiceError::InvalidInput`] when the request material is
671    /// inconsistent with the spec.
672    ///
673    /// [`ServiceError::Conflict`] when the observed state changed under the
674    /// operation.
675    fn uninstall(&mut self, spec: &ServiceSpec) -> Result<TransitionResult, ServiceError>;
676}
677
678/// Ownership guard shared by all destructive operations.
679///
680/// # Errors
681///
682/// [`ServiceError::OwnershipDenied`] when `ownership` is `Absent`, `Foreign`,
683/// or `Unknown`. `Owned` is the only accepted value; every other state fails
684/// closed.
685pub fn require_owned(id: &ServiceId, ownership: Ownership) -> Result<(), ServiceError> {
686    match ownership {
687        Ownership::Owned => Ok(()),
688        Ownership::Absent | Ownership::Foreign | Ownership::Unknown => {
689            Err(ServiceError::denied(id, ownership))
690        }
691    }
692}
693
694/// Deterministic in-memory manager for contract tests.
695#[derive(Debug, Default)]
696pub struct TestDoubleManager {
697    registrations: HashMap<String, TestRegistration>,
698}
699
700#[derive(Debug, Clone)]
701struct TestRegistration {
702    spec: ServiceSpec,
703    state: LifecycleState,
704    malformed: bool,
705}
706
707impl TestDoubleManager {
708    /// Creates an empty test manager.
709    pub fn new() -> Self {
710        Self::default()
711    }
712
713    /// Injects a registration with exact spec + state.
714    pub fn put(&mut self, spec: ServiceSpec, state: LifecycleState) {
715        self.registrations.insert(
716            spec.id().as_str().to_string(),
717            TestRegistration {
718                spec,
719                state,
720                malformed: false,
721            },
722        );
723    }
724
725    /// Injects a malformed registration record under an id.
726    pub fn put_malformed(&mut self, id: ServiceId) {
727        self.registrations.insert(
728            id.as_str().to_string(),
729            TestRegistration {
730                spec: ServiceSpec::new(id, absolute("/invalid"), vec![], None).expect("test spec"),
731                state: LifecycleState::Unknown,
732                malformed: true,
733            },
734        );
735    }
736
737    fn snapshot_for(&self, spec: &ServiceSpec) -> (Ownership, LifecycleSnapshot) {
738        match self.registrations.get(spec.id().as_str()) {
739            None => {
740                let snap = LifecycleSnapshot {
741                    id: spec.id().clone(),
742                    ownership: Ownership::Absent,
743                    state: LifecycleState::Stopped,
744                    health: HealthState::Unknown,
745                    was_registered: false,
746                    was_running: false,
747                };
748                (Ownership::Absent, snap)
749            }
750            Some(reg) => {
751                let observed = RegistrationSnapshot {
752                    present: true,
753                    executable: Some(reg.spec.executable().to_path_buf()),
754                    args: reg.spec.args().to_vec(),
755                    config: reg.spec.config().map(|p| p.to_path_buf()),
756                    malformed: reg.malformed,
757                };
758                let ownership = observed.ownership(spec);
759                let snap = LifecycleSnapshot {
760                    id: spec.id().clone(),
761                    ownership,
762                    state: reg.state,
763                    health: HealthState::Unknown,
764                    was_registered: true,
765                    was_running: reg.state == LifecycleState::Running,
766                };
767                (ownership, snap)
768            }
769        }
770    }
771}
772
773impl ServiceManager for TestDoubleManager {
774    fn inspect(&self, spec: &ServiceSpec) -> Result<LifecycleSnapshot, ServiceError> {
775        Ok(self.snapshot_for(spec).1)
776    }
777
778    fn install(&mut self, spec: &ServiceSpec) -> Result<TransitionResult, ServiceError> {
779        let (ownership, _) = self.snapshot_for(spec);
780        match ownership {
781            Ownership::Absent => {
782                self.put(spec.clone(), LifecycleState::Stopped);
783                Ok(TransitionResult {
784                    operation: ServiceOperation::Install,
785                    completed: true,
786                    detail: ServiceError::bounded("installed"),
787                })
788            }
789            Ownership::Owned => {
790                self.put(spec.clone(), LifecycleState::Stopped);
791                Ok(TransitionResult {
792                    operation: ServiceOperation::Install,
793                    completed: true,
794                    detail: ServiceError::bounded("refreshed owned registration"),
795                })
796            }
797            Ownership::Foreign | Ownership::Unknown => {
798                Err(ServiceError::denied(spec.id(), ownership))
799            }
800        }
801    }
802
803    fn start(
804        &mut self,
805        spec: &ServiceSpec,
806        _timeout: Duration,
807    ) -> Result<TransitionResult, ServiceError> {
808        let (ownership, snap) = self.snapshot_for(spec);
809        require_owned(spec.id(), ownership)?;
810        if snap.state == LifecycleState::Running {
811            return Ok(TransitionResult {
812                operation: ServiceOperation::Start,
813                completed: true,
814                detail: ServiceError::bounded("already running"),
815            });
816        }
817        if let Some(reg) = self.registrations.get_mut(spec.id().as_str()) {
818            reg.state = LifecycleState::Running;
819        }
820        Ok(TransitionResult {
821            operation: ServiceOperation::Start,
822            completed: true,
823            detail: ServiceError::bounded("started"),
824        })
825    }
826
827    fn stop(
828        &mut self,
829        spec: &ServiceSpec,
830        _timeout: Duration,
831    ) -> Result<TransitionResult, ServiceError> {
832        let (ownership, snap) = self.snapshot_for(spec);
833        require_owned(spec.id(), ownership)?;
834        if snap.state == LifecycleState::Stopped {
835            return Ok(TransitionResult {
836                operation: ServiceOperation::Stop,
837                completed: true,
838                detail: ServiceError::bounded("already stopped"),
839            });
840        }
841        if let Some(reg) = self.registrations.get_mut(spec.id().as_str()) {
842            reg.state = LifecycleState::Stopped;
843        }
844        Ok(TransitionResult {
845            operation: ServiceOperation::Stop,
846            completed: true,
847            detail: ServiceError::bounded("stopped"),
848        })
849    }
850
851    fn restart(
852        &mut self,
853        spec: &ServiceSpec,
854        timeout: Duration,
855    ) -> Result<TransitionResult, ServiceError> {
856        let (ownership, _) = self.snapshot_for(spec);
857        require_owned(spec.id(), ownership)?;
858        let stopped = self.stop(spec, timeout)?;
859        if !stopped.completed {
860            return Ok(TransitionResult {
861                operation: ServiceOperation::Restart,
862                completed: false,
863                detail: ServiceError::bounded("restart stop phase incomplete"),
864            });
865        }
866        let started = self.start(spec, timeout)?;
867        Ok(TransitionResult {
868            operation: ServiceOperation::Restart,
869            completed: started.completed,
870            detail: ServiceError::bounded(if started.completed {
871                "restarted"
872            } else {
873                "restart start phase incomplete"
874            }),
875        })
876    }
877
878    fn uninstall(&mut self, spec: &ServiceSpec) -> Result<TransitionResult, ServiceError> {
879        let (ownership, _) = self.snapshot_for(spec);
880        require_owned(spec.id(), ownership)?;
881        self.registrations.remove(spec.id().as_str());
882        Ok(TransitionResult {
883            operation: ServiceOperation::Uninstall,
884            completed: true,
885            detail: ServiceError::bounded("uninstalled"),
886        })
887    }
888}
889
890// ============================================================================
891// M002 — Unix manager adapters (systemd, launchd, cron) + shared mechanics.
892// ============================================================================
893
894/// Maximum captured bytes per stdout/stderr stream for one manager call.
895pub const MAX_COMMAND_OUTPUT_BYTES: usize = 256 * 1024;
896/// Maximum crontab content accepted for list/install (fail closed above).
897pub const MAX_CRONTAB_BYTES: usize = 1024 * 1024;
898/// Maximum service definition bytes accepted for atomic writes.
899pub const MAX_DEFINITION_BYTES: usize = 1024 * 1024;
900/// Upper bound for transition polling (callers supply smaller values).
901pub const MAX_TRANSITION_TIMEOUT: Duration = Duration::from_secs(300);
902/// The one byte ceiling for diagnostic text produced by this crate.
903///
904/// This governs **manager-output diagnostic text** — the bounded error and
905/// failure evidence the crate derives from a manager command or a manager
906/// observation — and it is the only declared ceiling for that data class.
907/// Every production truncation site for that class uses this value, including
908/// the failure-detail truncation in the unified commit engine.
909///
910/// This is *not* the capture bound for raw manager output
911/// ([`MAX_COMMAND_OUTPUT_BYTES`]), which is a different data class.
912pub const MAX_DIAGNOSTIC_BYTES: usize = 512;
913
914/// Bounded output of one manager command invocation.
915///
916/// The canonical service-side name states that this is a **manager** command
917/// output. The former `CommandOutput` spelling survives as the type alias
918/// [`CommandOutput`], so existing explicit-path callers and existing
919/// [`CommandExecutor`] implementations keep compiling.
920#[derive(Debug, Clone, PartialEq, Eq)]
921pub struct ManagerCommandOutput {
922    /// Process exit status code, when waited.
923    pub status: Option<i32>,
924    /// Captured stdout (bounded).
925    pub stdout: Vec<u8>,
926    /// Captured stderr (bounded).
927    pub stderr: Vec<u8>,
928}
929
930impl ManagerCommandOutput {
931    /// Stdout as lossy UTF-8 (manager output is ASCII/UTF-8 in practice).
932    pub fn stdout_text(&self) -> String {
933        String::from_utf8_lossy(&self.stdout).into_owned()
934    }
935
936    /// Stderr as lossy UTF-8.
937    pub fn stderr_text(&self) -> String {
938        String::from_utf8_lossy(&self.stderr).into_owned()
939    }
940}
941
942/// Compatibility alias for the former [`CommandOutput`] name.
943///
944/// This is a **type alias** to [`ManagerCommandOutput`], so the two spellings
945/// denote one type: an existing [`CommandExecutor`] implementation written
946/// against either spelling still satisfies the trait, and a consumer naming
947/// `eggup_service::CommandOutput` in a type position keeps compiling.
948///
949/// The alias is deliberately **not** marked `#[deprecated]`: deprecation is a
950/// publication-policy decision owned by a later republication milestone, and a
951/// deprecated alias would break downstream `-D warnings` builds. Its
952/// disposition is therefore settled at the intentional 0.2/1.0 API boundary.
953pub type CommandOutput = ManagerCommandOutput;
954
955/// Injectable manager-command executor (literal argv, no shell).
956///
957/// Implementations run the program directly with the given arguments, a
958/// controlled stdin policy, a deadline, and bounded output. No shell
959/// interpolation is performed. [`SystemExecutor`] is the production
960/// implementation; [`FakeExecutor`] scripts deterministic responses for tests.
961pub trait CommandExecutor: fmt::Debug {
962    /// Runs `argv[0]` with `argv[1..]` within `timeout`.
963    ///
964    /// `stdin_data` is `None` for null stdin; `Some(bytes)` streams bounded
965    /// input (used only for `crontab -`). Missing binaries, timeouts, and
966    /// output-bound overflows are `Err(ServiceError::Manager)`; nonzero
967    /// exits are `Ok` with the observed status for caller classification.
968    fn run(
969        &self,
970        argv: &[String],
971        stdin_data: Option<&[u8]>,
972        timeout: Duration,
973    ) -> Result<ManagerCommandOutput, ServiceError>;
974}
975
976/// Production bounded command runner (literal argv, no shell).
977///
978/// Manager names resolve only through trusted absolute platform paths. The
979/// child environment is cleared; user-scoped systemd receives only explicit
980/// session-bus variables. Stdin is null unless the caller supplies bounded
981/// input. Stdout/stderr are each bounded by `max_output_bytes`; overflow
982/// fails closed without assuming state. Deadlines kill and reap the child.
983///
984/// The bounded execution itself is delegated to `eggup_core::run_bounded`;
985/// this type keeps the service's own pre-flight policy — allowlisted
986/// absolute paths, a cleared environment, a bounded stdin payload, and the
987/// timeout range check — ahead of that call.
988#[derive(Debug, Clone)]
989pub struct SystemExecutor {
990    /// Per-stream output bound.
991    pub max_output_bytes: usize,
992}
993
994impl Default for SystemExecutor {
995    fn default() -> Self {
996        Self {
997            max_output_bytes: MAX_COMMAND_OUTPUT_BYTES,
998        }
999    }
1000}
1001
1002impl SystemExecutor {
1003    /// Creates a runner with the default output bound.
1004    pub fn new() -> Self {
1005        Self::default()
1006    }
1007
1008    /// Creates a runner with an explicit per-stream bound.
1009    ///
1010    /// # Errors
1011    ///
1012    /// [`ServiceError::InvalidInput`] when the bound is zero or above 16 MiB.
1013    pub fn with_max_output(max_output_bytes: usize) -> Result<Self, ServiceError> {
1014        if max_output_bytes == 0 || max_output_bytes > 16 * 1024 * 1024 {
1015            return Err(ServiceError::invalid("output bound out of range"));
1016        }
1017        Ok(Self { max_output_bytes })
1018    }
1019}
1020
1021impl CommandExecutor for SystemExecutor {
1022    fn run(
1023        &self,
1024        argv: &[String],
1025        stdin_data: Option<&[u8]>,
1026        timeout: Duration,
1027    ) -> Result<ManagerCommandOutput, ServiceError> {
1028        // ---- The service's own pre-flight policy ----
1029        //
1030        // These checks are this crate's policy, not core's. They run ahead of
1031        // every call into core, and core never sees the raw `argv[0]`.
1032        if argv.is_empty() || argv[0].is_empty() {
1033            return Err(ServiceError::invalid("manager command has no program"));
1034        }
1035        if argv.iter().any(|a| a.contains('\0')) {
1036            return Err(ServiceError::invalid("manager command contains nul bytes"));
1037        }
1038        if timeout.is_zero() || timeout > MAX_TRANSITION_TIMEOUT + Duration::from_secs(60) {
1039            return Err(ServiceError::invalid("manager timeout out of range"));
1040        }
1041        if let Some(data) = stdin_data {
1042            if data.len() > MAX_CRONTAB_BYTES {
1043                return Err(ServiceError::invalid("manager stdin exceeds bound"));
1044            }
1045        }
1046        // The caller's timeout bounds the whole call, so the budget starts
1047        // before the resolve, exactly as it does today, and the remaining
1048        // budget is what core receives.
1049        let started = Instant::now();
1050        let program_path = resolve_manager_program(&argv[0])?;
1051        let program = program_path.to_string_lossy().into_owned();
1052        let remaining = timeout
1053            .checked_sub(started.elapsed())
1054            .unwrap_or(Duration::ZERO);
1055        if remaining.is_zero() {
1056            return Err(ServiceError::manager(
1057                ManagerFailureKind::Timeout,
1058                format!("manager command timed out for {program}"),
1059            ));
1060        }
1061
1062        let mut spec = eggup_core::CommandSpec::new(program_path.clone())
1063            .args(argv[1..].iter().map(|argument| argument.as_str()))
1064            .timeout(remaining)
1065            .max_output_bytes(self.max_output_bytes);
1066        // The child environment is the filtered pair list, never the ambient
1067        // environment. A pair that is not valid UTF-8 is dropped rather than
1068        // lossily converted: a mangled session-bus address is worse than no
1069        // session-bus address at all.
1070        for (key, value) in filtered_manager_environment(argv, std::env::vars_os()) {
1071            let (Ok(key), Ok(value)) = (key.into_string(), value.into_string()) else {
1072                continue;
1073            };
1074            spec = spec.environment(key, value);
1075        }
1076        if let Some(data) = stdin_data {
1077            spec = spec.stdin_data(data.to_vec());
1078        }
1079
1080        match eggup_core::run_bounded(&spec) {
1081            Ok(out) => {
1082                if out.timed_out() {
1083                    return Err(ServiceError::manager(
1084                        ManagerFailureKind::Timeout,
1085                        format!("manager command timed out for {program}"),
1086                    ));
1087                }
1088                if out.output_limited() {
1089                    return Err(ServiceError::manager(
1090                        ManagerFailureKind::Protocol,
1091                        format!("manager output exceeded bound for {program}"),
1092                    ));
1093                }
1094                Ok(ManagerCommandOutput {
1095                    status: out.exit_code(),
1096                    stdout: out.stdout().to_vec(),
1097                    stderr: out.stderr().to_vec(),
1098                })
1099            }
1100            Err(eggup_core::Error::Io { operation, source }) => match operation {
1101                // The classification is decided here, where the platform's
1102                // error kind is still available. Nothing downstream inspects
1103                // the text.
1104                "spawning bounded candidate" => {
1105                    let kind = ManagerFailureKind::from_spawn_error(&source);
1106                    let detail = match kind {
1107                        ManagerFailureKind::NotFound => format!("manager binary missing: {program}"),
1108                        _ => format!("manager spawn failed for {program}: {source}"),
1109                    };
1110                    Err(ServiceError::manager(kind, detail))
1111                }
1112                "polling bounded candidate" => Err(ServiceError::manager(
1113                    ManagerFailureKind::Spawn,
1114                    format!("manager wait failed for {program}: {source}"),
1115                )),
1116                "writing bounded stdin" => Err(ServiceError::manager(
1117                    ManagerFailureKind::Spawn,
1118                    format!("manager stdin failed for {program}"),
1119                )),
1120                // The fallback names the unrecognised operation, so a future
1121                // core change is attributable rather than silently folded
1122                // into "spawn failed".
1123                other => Err(ServiceError::manager(
1124                    ManagerFailureKind::Spawn,
1125                    format!(
1126                        "manager spawn failed for {program}: unrecognised bounded execution operation {other}"
1127                    ),
1128                )),
1129            },
1130            Err(eggup_core::Error::CandidateExecution(msg)) => Err(ServiceError::manager(
1131                ManagerFailureKind::Protocol,
1132                format!("manager command failed for {program}: {msg}"),
1133            )),
1134            Err(eggup_core::Error::InvalidInput(msg)) => Err(ServiceError::invalid(msg)),
1135            Err(other) => Err(ServiceError::manager(
1136                ManagerFailureKind::Spawn,
1137                format!("manager command failed for {program}: {other}"),
1138            )),
1139        }
1140    }
1141}
1142
1143fn resolve_manager_program(program: &str) -> Result<PathBuf, ServiceError> {
1144    let requested = Path::new(program);
1145    if requested.is_absolute() {
1146        return validate_executable_path(requested, program);
1147    }
1148    let candidates: &[&str] = match program {
1149        "systemctl" => &["/usr/bin/systemctl", "/bin/systemctl"],
1150        "launchctl" => &["/bin/launchctl", "/usr/bin/launchctl"],
1151        "crontab" => &["/usr/bin/crontab", "/bin/crontab"],
1152        _ => {
1153            return Err(ServiceError::invalid(
1154                "manager program must be absolute or allowlisted",
1155            ))
1156        }
1157    };
1158    for candidate in candidates {
1159        let path = Path::new(candidate);
1160        if validate_executable_path(path, program).is_err() {
1161            continue;
1162        }
1163        return Ok(path.to_path_buf());
1164    }
1165    Err(ServiceError::manager(
1166        ManagerFailureKind::NotFound,
1167        format!("trusted manager binary missing: {program}"),
1168    ))
1169}
1170
1171fn validate_executable_path(path: &Path, display: &str) -> Result<PathBuf, ServiceError> {
1172    if !path.is_absolute() {
1173        return Err(ServiceError::invalid(
1174            "manager program override must be absolute",
1175        ));
1176    }
1177    let metadata = std::fs::metadata(path).map_err(|_| {
1178        ServiceError::manager(
1179            ManagerFailureKind::NotFound,
1180            format!("manager binary missing: {display}"),
1181        )
1182    })?;
1183    if !metadata.is_file() {
1184        return Err(ServiceError::invalid(
1185            "manager program is not a regular file",
1186        ));
1187    }
1188    #[cfg(unix)]
1189    {
1190        use std::os::unix::fs::PermissionsExt;
1191        if metadata.permissions().mode() & 0o111 == 0 {
1192            return Err(ServiceError::invalid("manager program is not executable"));
1193        }
1194    }
1195    Ok(path.to_path_buf())
1196}
1197
1198fn filtered_manager_environment(
1199    argv: &[String],
1200    source: impl IntoIterator<Item = (std::ffi::OsString, std::ffi::OsString)>,
1201) -> Vec<(std::ffi::OsString, std::ffi::OsString)> {
1202    let user_systemd = argv
1203        .first()
1204        .is_some_and(|p| Path::new(p).file_name().is_some_and(|n| n == "systemctl"))
1205        && argv.iter().any(|arg| arg == "--user");
1206    let allow: &[&std::ffi::OsStr] = if user_systemd {
1207        &[
1208            std::ffi::OsStr::new("DBUS_SESSION_BUS_ADDRESS"),
1209            std::ffi::OsStr::new("XDG_RUNTIME_DIR"),
1210            std::ffi::OsStr::new("SYSTEMD_BUS_ADDRESS"),
1211        ]
1212    } else {
1213        &[]
1214    };
1215    source
1216        .into_iter()
1217        .filter(|(key, _)| allow.contains(&key.as_os_str()))
1218        .collect()
1219}
1220
1221/// One scripted expectation for [`FakeExecutor`].
1222#[derive(Debug, Clone)]
1223struct FakeExpectation {
1224    expected_argv: Vec<String>,
1225    result: Result<ManagerCommandOutput, ServiceError>,
1226}
1227
1228/// One observed call for [`FakeExecutor`].
1229#[derive(Debug, Clone, PartialEq, Eq)]
1230pub struct FakeCall {
1231    /// Exact argv observed.
1232    pub argv: Vec<String>,
1233    /// Stdin bytes observed, when any.
1234    pub stdin: Option<Vec<u8>>,
1235}
1236
1237/// Deterministic test executor with scripted responses.
1238#[derive(Debug, Default)]
1239pub struct FakeExecutor {
1240    expectations: Mutex<VecDeque<FakeExpectation>>,
1241    calls: Mutex<Vec<FakeCall>>,
1242}
1243
1244impl FakeExecutor {
1245    /// Creates an empty fake executor.
1246    pub fn new() -> Self {
1247        Self::default()
1248    }
1249
1250    /// Scripts a successful response for the next matching call.
1251    ///
1252    /// # Panics
1253    ///
1254    /// Panics if the internal expectation lock is poisoned by a panic in
1255    /// another thread that also used this executor.
1256    pub fn expect(&self, argv: &[&str], output: ManagerCommandOutput) {
1257        self.expectations
1258            .lock()
1259            .expect("fake lock")
1260            .push_back(FakeExpectation {
1261                expected_argv: argv.iter().map(|s| s.to_string()).collect(),
1262                result: Ok(output),
1263            });
1264    }
1265
1266    /// Scripts a failure for the next matching call.
1267    ///
1268    /// # Panics
1269    ///
1270    /// Panics if the internal expectation lock is poisoned by a panic in
1271    /// another thread that also used this executor.
1272    pub fn expect_error(&self, argv: &[&str], err: ServiceError) {
1273        self.expectations
1274            .lock()
1275            .expect("fake lock")
1276            .push_back(FakeExpectation {
1277                expected_argv: argv.iter().map(|s| s.to_string()).collect(),
1278                result: Err(err),
1279            });
1280    }
1281
1282    /// Returns all observed calls in order.
1283    ///
1284    /// # Panics
1285    ///
1286    /// Panics if the internal call lock is poisoned by a panic in another
1287    /// thread that also used this executor.
1288    pub fn calls(&self) -> Vec<FakeCall> {
1289        self.calls.lock().expect("fake lock").clone()
1290    }
1291
1292    /// Returns the number of observed calls.
1293    ///
1294    /// # Panics
1295    ///
1296    /// Panics if the internal call lock is poisoned by a panic in another
1297    /// thread that also used this executor.
1298    pub fn call_count(&self) -> usize {
1299        self.calls.lock().expect("fake lock").len()
1300    }
1301
1302    /// Returns true when all expectations were consumed.
1303    ///
1304    /// # Panics
1305    ///
1306    /// Panics if the internal expectation lock is poisoned by a panic in
1307    /// another thread that also used this executor.
1308    pub fn is_exhausted(&self) -> bool {
1309        self.expectations.lock().expect("fake lock").is_empty()
1310    }
1311}
1312
1313impl CommandExecutor for FakeExecutor {
1314    fn run(
1315        &self,
1316        argv: &[String],
1317        stdin_data: Option<&[u8]>,
1318        _timeout: Duration,
1319    ) -> Result<ManagerCommandOutput, ServiceError> {
1320        self.calls.lock().expect("fake lock").push(FakeCall {
1321            argv: argv.to_vec(),
1322            stdin: stdin_data.map(|b| b.to_vec()),
1323        });
1324        let mut queue = self.expectations.lock().expect("fake lock");
1325        let Some(exp) = queue.pop_front() else {
1326            return Err(ServiceError::manager(
1327                ManagerFailureKind::Spawn,
1328                "unexpected manager command",
1329            ));
1330        };
1331        if exp.expected_argv != argv {
1332            return Err(ServiceError::manager(
1333                ManagerFailureKind::Protocol,
1334                format!(
1335                    "unexpected manager argv: got {:?}, want {:?}",
1336                    argv, exp.expected_argv
1337                ),
1338            ));
1339        }
1340        exp.result
1341    }
1342}
1343
1344impl CommandExecutor for &FakeExecutor {
1345    fn run(
1346        &self,
1347        argv: &[String],
1348        stdin_data: Option<&[u8]>,
1349        timeout: Duration,
1350    ) -> Result<ManagerCommandOutput, ServiceError> {
1351        (*self).run(argv, stdin_data, timeout)
1352    }
1353}
1354
1355// ---- Definition file safety ----
1356
1357/// Atomically writes a manager definition file.
1358///
1359/// Uses a same-directory exclusively-created owner-private temp, `fsync`s the
1360/// temp, sets an appropriate mode (`0644` for new files; preserves the
1361/// existing mode on overwrite), then promotes. `allow_overwrite = false`
1362/// uses no-replace promotion and fails with `Conflict` when `dest` exists;
1363/// `true` replaces an owned destination via rename. Never creates missing
1364/// parents and never changes parent permissions. Cleans only the owned temp.
1365///
1366/// # Errors
1367///
1368/// [`ServiceError::InvalidInput`] when the definition bytes are empty,
1369/// overlong, or contain a NUL byte, when the destination has no parent
1370/// directory, or when the destination exists and `allow_overwrite` is
1371/// `false`.
1372///
1373/// [`ServiceError::Conflict`] when a no-replace promotion loses the race with
1374/// a destination created concurrently.
1375///
1376/// [`ServiceError::Manager`] with [`ManagerFailureKind::LocalFilesystem`] when
1377/// a local filesystem operation fails: reading the parent directory, creating
1378/// the owner-private temp, writing, flushing, syncing, securing, or promoting
1379/// it.
1380pub fn atomic_write_definition(
1381    path: &Path,
1382    bytes: &[u8],
1383    allow_overwrite: bool,
1384) -> Result<(), ServiceError> {
1385    if bytes.is_empty() || bytes.len() > MAX_DEFINITION_BYTES {
1386        return Err(ServiceError::invalid(
1387            "definition bytes are empty or overlong",
1388        ));
1389    }
1390    if bytes.contains(&0) {
1391        return Err(ServiceError::invalid("definition contains nul bytes"));
1392    }
1393    let parent = path
1394        .parent()
1395        .ok_or_else(|| ServiceError::invalid("definition path has no parent"))?;
1396    let parent_meta = std::fs::symlink_metadata(parent).map_err(|e| {
1397        ServiceError::manager(
1398            ManagerFailureKind::LocalFilesystem,
1399            format!("reading definition parent: {e}"),
1400        )
1401    })?;
1402    if !parent_meta.is_dir() || parent_meta.file_type().is_symlink() {
1403        return Err(ServiceError::invalid(
1404            "definition parent must be an existing real directory",
1405        ));
1406    }
1407    let dest_exists = std::fs::symlink_metadata(path).is_ok();
1408    if dest_exists && !allow_overwrite {
1409        return Err(ServiceError::conflict(
1410            "definition already exists; refusing to overwrite",
1411        ));
1412    }
1413    // Preserve the existing mode on overwrite; otherwise use 0644.
1414    #[cfg(unix)]
1415    let final_mode: u32 = {
1416        use std::os::unix::fs::PermissionsExt;
1417        if dest_exists {
1418            std::fs::symlink_metadata(path)
1419                .map(|m| m.permissions().mode() & 0o777)
1420                .unwrap_or(0o644)
1421        } else {
1422            0o644
1423        }
1424    };
1425    // Exclusive temp in the same directory (same filesystem for promotion).
1426    let nonce = std::time::SystemTime::now()
1427        .duration_since(std::time::UNIX_EPOCH)
1428        .map(|d| d.as_nanos())
1429        .unwrap_or(0);
1430    let mut tmp: PathBuf = parent.join(format!(".eggup-def-{}-{nonce}.tmp", std::process::id()));
1431    // Retry on collision with a bounded suffix loop.
1432    let mut file: Option<std::fs::File> = None;
1433    for attempt in 0..32u32 {
1434        if attempt > 0 {
1435            tmp = parent.join(format!(
1436                ".eggup-def-{}-{nonce}-{attempt}.tmp",
1437                std::process::id()
1438            ));
1439        }
1440        let mut opts = std::fs::OpenOptions::new();
1441        opts.write(true).create_new(true);
1442        #[cfg(unix)]
1443        {
1444            use std::os::unix::fs::OpenOptionsExt;
1445            opts.mode(0o600);
1446        }
1447        match opts.open(&tmp) {
1448            Ok(f) => {
1449                file = Some(f);
1450                break;
1451            }
1452            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
1453            Err(e) => {
1454                return Err(ServiceError::manager(
1455                    ManagerFailureKind::LocalFilesystem,
1456                    format!("creating definition temp: {e}"),
1457                ));
1458            }
1459        }
1460    }
1461    let mut file = file.ok_or_else(|| {
1462        ServiceError::manager(
1463            ManagerFailureKind::LocalFilesystem,
1464            "definition temp collisions exhausted".to_string(),
1465        )
1466    })?;
1467    struct Guard<'a> {
1468        path: &'a Path,
1469        disarm: bool,
1470    }
1471    impl Drop for Guard<'_> {
1472        fn drop(&mut self) {
1473            if !self.disarm {
1474                let _ = std::fs::remove_file(self.path);
1475            }
1476        }
1477    }
1478    let mut guard = Guard {
1479        path: &tmp,
1480        disarm: false,
1481    };
1482    {
1483        use std::io::Write;
1484        file.write_all(bytes).map_err(|e| {
1485            ServiceError::manager(
1486                ManagerFailureKind::LocalFilesystem,
1487                format!("writing definition temp: {e}"),
1488            )
1489        })?;
1490        file.flush().map_err(|e| {
1491            ServiceError::manager(
1492                ManagerFailureKind::LocalFilesystem,
1493                format!("flushing definition temp: {e}"),
1494            )
1495        })?;
1496        file.sync_all().map_err(|e| {
1497            ServiceError::manager(
1498                ManagerFailureKind::LocalFilesystem,
1499                format!("syncing definition temp: {e}"),
1500            )
1501        })?;
1502    }
1503    #[cfg(unix)]
1504    {
1505        use std::os::unix::fs::PermissionsExt;
1506        let perms = std::fs::Permissions::from_mode(final_mode);
1507        std::fs::set_permissions(&tmp, perms).map_err(|e| {
1508            ServiceError::manager(
1509                ManagerFailureKind::LocalFilesystem,
1510                format!("securing definition temp: {e}"),
1511            )
1512        })?;
1513    }
1514    drop(file);
1515    if allow_overwrite {
1516        // `std::fs::rename` is `MoveFileEx(MOVEFILE_REPLACE_EXISTING)` on
1517        // Windows, so it already replaces an existing destination. A former
1518        // `AlreadyExists` arm that removed the destination and re-renamed was
1519        // therefore unreachable, and had it ever run it would have opened a
1520        // data-loss window: the destination is already gone and the promotion
1521        // can still fail, leaving nothing at the path.
1522        match std::fs::rename(&tmp, path) {
1523            Ok(()) => {
1524                guard.disarm = true;
1525                // Best-effort parent fsync for durability; ignore platform errors.
1526                if let Ok(dir) = std::fs::File::open(parent) {
1527                    let _ = dir.sync_all();
1528                }
1529                Ok(())
1530            }
1531            Err(e) => Err(ServiceError::manager(
1532                ManagerFailureKind::LocalFilesystem,
1533                format!("promoting definition: {e}"),
1534            )),
1535        }
1536    } else {
1537        match std::fs::hard_link(&tmp, path) {
1538            Ok(()) => {
1539                let _ = std::fs::remove_file(&tmp);
1540                guard.disarm = true;
1541                if let Ok(dir) = std::fs::File::open(parent) {
1542                    let _ = dir.sync_all();
1543                }
1544                Ok(())
1545            }
1546            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Err(ServiceError::conflict(
1547                "definition already exists; refusing to overwrite",
1548            )),
1549            Err(e) => Err(ServiceError::manager(
1550                ManagerFailureKind::LocalFilesystem,
1551                format!("promoting definition: {e}"),
1552            )),
1553        }
1554    }
1555}
1556
1557// ---- systemd adapter ----
1558
1559/// systemd scope without privilege guessing.
1560#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1561pub enum SystemdScope {
1562    /// System manager (`--system`).
1563    System,
1564    /// User manager (`--user`).
1565    User,
1566}
1567
1568impl SystemdScope {
1569    fn flag(&self) -> &'static str {
1570        match self {
1571            Self::System => "--system",
1572            Self::User => "--user",
1573        }
1574    }
1575}
1576
1577/// Caller-owned systemd install material (mechanics only, no product policy).
1578#[derive(Debug, Clone, PartialEq, Eq)]
1579pub struct SystemdInstall {
1580    /// Unit name (for example `my-daemon.service`). `*.service` only.
1581    pub unit_name: String,
1582    /// Explicit scope (never guessed from EUID).
1583    pub scope: SystemdScope,
1584    /// Absolute unit file path supplied by the caller.
1585    pub unit_path: PathBuf,
1586    /// Exact desired unit file bytes (caller-owned content).
1587    pub definition: Vec<u8>,
1588    /// Whether to run `enable` after install/refresh (explicit only).
1589    pub enable: bool,
1590    /// Whether to run `daemon-reload` after install/refresh (explicit only).
1591    pub reload: bool,
1592    /// Bounded wait for state transitions.
1593    pub transition_timeout: Duration,
1594}
1595
1596impl SystemdInstall {
1597    /// Validates install material without touching the manager.
1598    ///
1599    /// # Errors
1600    ///
1601    /// [`ServiceError::InvalidInput`] when the unit name is empty, overlong,
1602    /// contains a control character, is not a bare `*.service` file name, when
1603    /// the unit path is not absolute, when the definition bytes are empty,
1604    /// overlong, or contain a NUL byte, or when the transition timeout is zero
1605    /// or above [`MAX_TRANSITION_TIMEOUT`].
1606    pub fn new(
1607        unit_name: String,
1608        scope: SystemdScope,
1609        unit_path: PathBuf,
1610        definition: Vec<u8>,
1611        enable: bool,
1612        reload: bool,
1613        transition_timeout: Duration,
1614    ) -> Result<Self, ServiceError> {
1615        validate_unit_name(&unit_name)?;
1616        if !unit_path.is_absolute() {
1617            return Err(ServiceError::invalid("unit path must be absolute"));
1618        }
1619        if definition.is_empty() || definition.len() > MAX_DEFINITION_BYTES {
1620            return Err(ServiceError::invalid(
1621                "unit definition is empty or overlong",
1622            ));
1623        }
1624        if definition.contains(&0) {
1625            return Err(ServiceError::invalid("unit definition contains nul"));
1626        }
1627        if transition_timeout.is_zero() || transition_timeout > MAX_TRANSITION_TIMEOUT {
1628            return Err(ServiceError::invalid("transition timeout out of range"));
1629        }
1630        Ok(Self {
1631            unit_name,
1632            scope,
1633            unit_path,
1634            definition,
1635            enable,
1636            reload,
1637            transition_timeout,
1638        })
1639    }
1640}
1641
1642fn validate_unit_name(name: &str) -> Result<(), ServiceError> {
1643    if name.is_empty() || name.len() > 256 || name.chars().any(char::is_control) {
1644        return Err(ServiceError::invalid(
1645            "unit name is empty, overlong, or has controls",
1646        ));
1647    }
1648    if name.contains(['/', '\\', ' ', '@']) {
1649        return Err(ServiceError::invalid("unit name must be a bare unit file"));
1650    }
1651    if !name.ends_with(".service") {
1652        return Err(ServiceError::invalid("only *.service units are supported"));
1653    }
1654    Ok(())
1655}
1656
1657/// systemd manager implementing the neutral contract.
1658#[derive(Debug)]
1659pub struct SystemdManager<E: CommandExecutor = SystemExecutor> {
1660    executor: E,
1661    install: SystemdInstall,
1662}
1663
1664impl<E: CommandExecutor> SystemdManager<E> {
1665    /// Creates a systemd adapter. No manager calls are made here.
1666    pub fn new(executor: E, install: SystemdInstall) -> Self {
1667        Self { executor, install }
1668    }
1669
1670    /// Returns the install descriptor.
1671    pub fn install_config(&self) -> &SystemdInstall {
1672        &self.install
1673    }
1674
1675    /// Returns the command executor (test visibility).
1676    pub fn executor(&self) -> &E {
1677        &self.executor
1678    }
1679
1680    /// Creates the single per-operation deadline for this adapter.
1681    ///
1682    /// `install`, `uninstall` and `inspect` take no timeout parameter: their
1683    /// budget is `install.transition_timeout` for the *whole* operation. The
1684    /// clamp is applied exactly once, here, at deadline construction. Every
1685    /// manager invocation the operation makes draws from this one deadline, so
1686    /// no invocation is ever granted a fresh full budget.
1687    fn operation_deadline(&self) -> Result<OperationDeadline, ServiceError> {
1688        OperationDeadline::new(bounded_timeout(self.install.transition_timeout))
1689    }
1690
1691    fn show_argv(&self) -> Vec<String> {
1692        vec![
1693            "systemctl".to_string(),
1694            self.install.scope.flag().to_string(),
1695            "show".to_string(),
1696            self.install.unit_name.clone(),
1697            "-p".to_string(),
1698            "LoadState,ActiveState,ExecStart".to_string(),
1699        ]
1700    }
1701
1702    fn quiescence_show_argv(&self) -> Vec<String> {
1703        vec![
1704            "systemctl".to_string(),
1705            self.install.scope.flag().to_string(),
1706            "show".to_string(),
1707            self.install.unit_name.clone(),
1708            "-p".to_string(),
1709            "LoadState,ActiveState,SubState,ExecStart,MainPID,ControlPID,ControlGroup,Job"
1710                .to_string(),
1711        ]
1712    }
1713
1714    fn ownership_until(
1715        &self,
1716        spec: &ServiceSpec,
1717        deadline: OperationDeadline,
1718    ) -> Result<(Ownership, LifecycleState), ServiceError> {
1719        let out = self
1720            .executor
1721            .run(&self.show_argv(), None, deadline.command_timeout()?)?;
1722        if out.status != Some(0) {
1723            return Ok((Ownership::Unknown, LifecycleState::Unknown));
1724        }
1725        let (ownership, state, _) = systemd_ownership(&out.stdout_text(), spec)?;
1726        Ok((ownership, state))
1727    }
1728
1729    fn run_unit(
1730        &self,
1731        verb: &str,
1732        deadline: OperationDeadline,
1733    ) -> Result<ManagerCommandOutput, ServiceError> {
1734        let argv = vec![
1735            "systemctl".to_string(),
1736            self.install.scope.flag().to_string(),
1737            verb.to_string(),
1738            self.install.unit_name.clone(),
1739        ];
1740        let out = self
1741            .executor
1742            .run(&argv, None, deadline.command_timeout()?)?;
1743        if out.status != Some(0) {
1744            return Err(ServiceError::manager(
1745                ManagerFailureKind::Protocol,
1746                format!(
1747                    "systemctl {verb} exited {}: {}",
1748                    out.status.unwrap_or(-1),
1749                    ServiceError::bounded(out.stderr_text()),
1750                ),
1751            ));
1752        }
1753        Ok(out)
1754    }
1755
1756    fn poll_active(
1757        &self,
1758        want_active: bool,
1759        deadline: OperationDeadline,
1760    ) -> Result<bool, ServiceError> {
1761        loop {
1762            let argv = vec![
1763                "systemctl".to_string(),
1764                self.install.scope.flag().to_string(),
1765                "is-active".to_string(),
1766                self.install.unit_name.clone(),
1767            ];
1768            let out = self
1769                .executor
1770                .run(&argv, None, deadline.command_timeout()?)?;
1771            let state = out.stdout_text().trim().to_string();
1772            let confirmed = if want_active {
1773                state == "active" && out.status == Some(0)
1774            } else {
1775                state == "inactive" && out.status == Some(3)
1776            };
1777            if confirmed {
1778                return Ok(!deadline.expired());
1779            }
1780            if deadline.expired() {
1781                return Ok(false);
1782            }
1783            std::thread::sleep(
1784                deadline
1785                    .remaining()
1786                    .unwrap_or_default()
1787                    .min(Duration::from_millis(100)),
1788            );
1789        }
1790    }
1791
1792    fn stop_failed_owned(
1793        &mut self,
1794        spec: &ServiceSpec,
1795        deadline: OperationDeadline,
1796    ) -> Result<TransitionResult, ServiceError> {
1797        let before = self.quiescence_observation(spec, deadline)?;
1798        require_owned(spec.id(), before.ownership)?;
1799        if before.active_state != "failed" {
1800            if before.active_state == "inactive"
1801                && quiescence_proven(&before, Path::new("/sys/fs/cgroup"))
1802            {
1803                return Ok(stopped_result(true, "already quiescent"));
1804            }
1805            return Ok(stopped_result(
1806                false,
1807                "failed-unit state changed before stop; quiescence unconfirmed",
1808            ));
1809        }
1810
1811        self.run_unit("stop", deadline)?;
1812        loop {
1813            let Some(remaining) = deadline.remaining() else {
1814                return Ok(stopped_result(
1815                    false,
1816                    "failed-unit stop deadline expired; quiescence unconfirmed",
1817                ));
1818            };
1819            let after = match self.quiescence_observation(spec, deadline) {
1820                Ok(observation) => observation,
1821                Err(error) => {
1822                    return Ok(stopped_result(
1823                        false,
1824                        &format!("failed-unit post-stop observation failed: {error}"),
1825                    ));
1826                }
1827            };
1828            if after.ownership != Ownership::Owned || after.control_group != before.control_group {
1829                return Ok(stopped_result(
1830                    false,
1831                    "failed-unit ownership or control group changed; quiescence unconfirmed",
1832                ));
1833            }
1834            if !matches!(after.active_state.as_str(), "failed" | "inactive") {
1835                return Ok(stopped_result(
1836                    false,
1837                    "failed unit became active or transitioning; quiescence unconfirmed",
1838                ));
1839            }
1840            if quiescence_proven(&after, Path::new("/sys/fs/cgroup")) {
1841                let confirmed = match self.quiescence_observation(spec, deadline) {
1842                    Ok(observation) => observation,
1843                    Err(_) => {
1844                        return Ok(stopped_result(
1845                            false,
1846                            "failed-unit proof revalidation failed; quiescence unconfirmed",
1847                        ));
1848                    }
1849                };
1850                if confirmed != after || !quiescence_proven(&confirmed, Path::new("/sys/fs/cgroup"))
1851                {
1852                    return Ok(stopped_result(
1853                        false,
1854                        "failed-unit proof changed during revalidation; quiescence unconfirmed",
1855                    ));
1856                }
1857                let active = self.is_active(deadline)?;
1858                let expected = if after.active_state == "failed" {
1859                    ("failed", Some(3))
1860                } else {
1861                    ("inactive", Some(3))
1862                };
1863                if active.0 == expected.0 && active.1 == expected.1 {
1864                    return Ok(stopped_result(true, "owned failed unit is quiescent"));
1865                }
1866                return Ok(stopped_result(
1867                    false,
1868                    "systemd active-state observations disagree; quiescence unconfirmed",
1869                ));
1870            }
1871            std::thread::sleep(remaining.min(Duration::from_millis(50)));
1872        }
1873    }
1874
1875    fn quiescence_observation(
1876        &self,
1877        spec: &ServiceSpec,
1878        deadline: OperationDeadline,
1879    ) -> Result<SystemdQuiescenceObservation, ServiceError> {
1880        let out = self.executor.run(
1881            &self.quiescence_show_argv(),
1882            None,
1883            deadline.command_timeout()?,
1884        )?;
1885        if out.status != Some(0) {
1886            return Err(ServiceError::manager(
1887                ManagerFailureKind::Protocol,
1888                "systemd quiescence observation failed",
1889            ));
1890        }
1891        parse_quiescence_observation(&out.stdout_text(), spec)
1892    }
1893
1894    fn is_active(
1895        &self,
1896        deadline: OperationDeadline,
1897    ) -> Result<(String, Option<i32>), ServiceError> {
1898        let argv = vec![
1899            "systemctl".to_string(),
1900            self.install.scope.flag().to_string(),
1901            "is-active".to_string(),
1902            self.install.unit_name.clone(),
1903        ];
1904        let out = self
1905            .executor
1906            .run(&argv, None, deadline.command_timeout()?)?;
1907        Ok((out.stdout_text().trim().to_owned(), out.status))
1908    }
1909}
1910
1911#[derive(Debug, PartialEq, Eq)]
1912struct SystemdQuiescenceObservation {
1913    ownership: Ownership,
1914    active_state: String,
1915    sub_state: String,
1916    main_pid: u32,
1917    control_pid: u32,
1918    control_group: String,
1919    job: String,
1920}
1921
1922fn stopped_result(completed: bool, detail: &str) -> TransitionResult {
1923    TransitionResult {
1924        operation: ServiceOperation::Stop,
1925        completed,
1926        detail: ServiceError::bounded(detail),
1927    }
1928}
1929
1930fn parse_quiescence_observation(
1931    text: &str,
1932    spec: &ServiceSpec,
1933) -> Result<SystemdQuiescenceObservation, ServiceError> {
1934    let mut properties = std::collections::HashMap::new();
1935    for line in text.lines() {
1936        let Some((key, value)) = line.split_once('=') else {
1937            return Err(ServiceError::manager(
1938                ManagerFailureKind::Protocol,
1939                "malformed systemd observation",
1940            ));
1941        };
1942        if properties.insert(key, value).is_some() {
1943            return Err(ServiceError::manager(
1944                ManagerFailureKind::Protocol,
1945                "duplicate systemd observation field",
1946            ));
1947        }
1948    }
1949    let property = |key| {
1950        properties.get(key).copied().ok_or_else(|| {
1951            ServiceError::manager(
1952                ManagerFailureKind::Protocol,
1953                "incomplete systemd observation",
1954            )
1955        })
1956    };
1957    let (ownership, _, _) = systemd_ownership(text, spec)?;
1958    let main_pid = property("MainPID")?.parse().map_err(|_| {
1959        ServiceError::manager(ManagerFailureKind::Protocol, "invalid systemd MainPID")
1960    })?;
1961    let control_pid = property("ControlPID")?.parse().map_err(|_| {
1962        ServiceError::manager(ManagerFailureKind::Protocol, "invalid systemd ControlPID")
1963    })?;
1964    Ok(SystemdQuiescenceObservation {
1965        ownership,
1966        active_state: property("ActiveState")?.to_string(),
1967        sub_state: property("SubState")?.to_string(),
1968        main_pid,
1969        control_pid,
1970        control_group: property("ControlGroup")?.to_string(),
1971        job: property("Job")?.to_string(),
1972    })
1973}
1974
1975fn quiescence_proven(observation: &SystemdQuiescenceObservation, cgroup_root: &Path) -> bool {
1976    if observation.ownership != Ownership::Owned
1977        || !matches!(observation.active_state.as_str(), "failed" | "inactive")
1978        || (observation.active_state == "failed" && observation.sub_state != "failed")
1979        || (observation.active_state == "inactive"
1980            && !matches!(observation.sub_state.as_str(), "dead" | "exited"))
1981        || observation.main_pid != 0
1982        || observation.control_pid != 0
1983        || !matches!(observation.job.as_str(), "" | "n/a")
1984    {
1985        return false;
1986    }
1987    if observation.control_group.is_empty() {
1988        // systemd has removed the unit's cgroup after all its tasks exited.
1989        return true;
1990    }
1991    let Ok(root_metadata) = std::fs::symlink_metadata(cgroup_root) else {
1992        return false;
1993    };
1994    if !root_metadata.is_dir() || root_metadata.file_type().is_symlink() {
1995        return false;
1996    }
1997    let Some(relative) = observation.control_group.strip_prefix('/') else {
1998        return false;
1999    };
2000    let mut path = cgroup_root.to_path_buf();
2001    for component in relative.split('/') {
2002        if component.is_empty() || component == "." || component == ".." {
2003            return false;
2004        }
2005        path.push(component);
2006        let metadata = match std::fs::symlink_metadata(&path) {
2007            Ok(metadata) => metadata,
2008            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return true,
2009            Err(_) => return false,
2010        };
2011        if !metadata.is_dir() || metadata.file_type().is_symlink() {
2012            return false;
2013        }
2014    }
2015    let Ok(processes) = std::fs::read_to_string(path.join("cgroup.procs")) else {
2016        return false;
2017    };
2018    let Ok(events) = std::fs::read_to_string(path.join("cgroup.events")) else {
2019        return false;
2020    };
2021    let mut populated = None;
2022    for line in events.lines() {
2023        if let Some(value) = line.strip_prefix("populated ") {
2024            if populated.is_some() || !matches!(value, "0" | "1") {
2025                return false;
2026            }
2027            populated = Some(value == "1");
2028        }
2029    }
2030    processes.trim().is_empty() && populated == Some(false)
2031}
2032
2033#[derive(Debug, Clone, Copy)]
2034struct OperationDeadline(Instant);
2035
2036impl OperationDeadline {
2037    fn new(timeout: Duration) -> Result<Self, ServiceError> {
2038        Self::new_at(Instant::now(), timeout)
2039    }
2040
2041    fn new_at(now: Instant, timeout: Duration) -> Result<Self, ServiceError> {
2042        if timeout.is_zero() || timeout > MAX_TRANSITION_TIMEOUT {
2043            return Err(ServiceError::invalid("transition timeout out of range"));
2044        }
2045        Ok(Self(now + timeout))
2046    }
2047
2048    fn remaining(self) -> Option<Duration> {
2049        self.remaining_at(Instant::now())
2050    }
2051
2052    fn remaining_at(self, now: Instant) -> Option<Duration> {
2053        self.0
2054            .checked_duration_since(now)
2055            .filter(|duration| !duration.is_zero())
2056    }
2057
2058    fn command_timeout(self) -> Result<Duration, ServiceError> {
2059        self.command_timeout_at(Instant::now())
2060    }
2061
2062    fn command_timeout_at(self, now: Instant) -> Result<Duration, ServiceError> {
2063        self.remaining_at(now).ok_or_else(|| {
2064            ServiceError::manager(
2065                ManagerFailureKind::Timeout,
2066                "transition deadline exhausted before manager command",
2067            )
2068        })
2069    }
2070
2071    fn expired(self) -> bool {
2072        self.remaining().is_none()
2073    }
2074}
2075
2076fn bounded_timeout(t: Duration) -> Duration {
2077    std::cmp::min(t, MAX_TRANSITION_TIMEOUT)
2078}
2079
2080fn reconcile_config_identity(
2081    mut observed: RegistrationSnapshot,
2082    spec: &ServiceSpec,
2083) -> RegistrationSnapshot {
2084    let Some(config) = spec.config() else {
2085        return observed;
2086    };
2087    let Some(config_text) = config.to_str() else {
2088        observed.malformed = true;
2089        return observed;
2090    };
2091    let expected_count = spec
2092        .args()
2093        .iter()
2094        .filter(|arg| arg.as_str() == config_text)
2095        .count();
2096    let observed_count = observed
2097        .args
2098        .iter()
2099        .filter(|arg| arg.as_str() == config_text)
2100        .count();
2101    if observed_count == 0 {
2102        // A parseable registration without the specified config is Foreign.
2103        return observed;
2104    }
2105    if expected_count > 1 || observed_count > 1 {
2106        observed.malformed = true;
2107        return observed;
2108    }
2109    if expected_count == 1 && observed_count == 1 {
2110        observed.config = Some(config.to_path_buf());
2111    }
2112    observed
2113}
2114
2115fn truncate_utf8_bytes(mut text: String, max_bytes: usize) -> String {
2116    if text.len() > max_bytes {
2117        let mut end = max_bytes;
2118        while !text.is_char_boundary(end) {
2119            end -= 1;
2120        }
2121        text.truncate(end);
2122    }
2123    text
2124}
2125
2126fn ensure_mutation_success(out: &ManagerCommandOutput, command: &str) -> Result<(), ServiceError> {
2127    if out.status == Some(0) {
2128        Ok(())
2129    } else {
2130        Err(ServiceError::manager(
2131            ManagerFailureKind::Protocol,
2132            format!(
2133                "{command} exited {}: {}",
2134                out.status.unwrap_or(-1),
2135                ServiceError::bounded(out.stderr_text()),
2136            ),
2137        ))
2138    }
2139}
2140
2141/// Parses one `ExecStart={ path=... ; argv[]=... ; ... }` value.
2142///
2143/// Returns `(executable, args)` where `args` excludes `argv[0]`. Returns
2144/// `None` for any ambiguous or unsupported shape.
2145fn parse_exec_start(value: &str) -> Option<(PathBuf, Vec<String>)> {
2146    let v = value.trim();
2147    if v.is_empty() {
2148        return None;
2149    }
2150    // Expected shape: `{ path=... ; argv[]=... ; ... }`. Reject multiple
2151    // command blocks by requiring exactly one `{...}` group.
2152    if v.matches('{').count() != 1 || v.matches('}').count() != 1 {
2153        return None;
2154    }
2155    let inner = v.strip_prefix('{')?.strip_suffix('}')?;
2156    let mut path: Option<String> = None;
2157    let mut argv: Option<String> = None;
2158    for part in inner.split(';') {
2159        let part = part.trim();
2160        if let Some(p) = part.strip_prefix("path=") {
2161            if path.is_some() {
2162                return None;
2163            }
2164            path = Some(p.trim().to_string());
2165        } else if let Some(a) = part.strip_prefix("argv[]=") {
2166            if argv.is_some() {
2167                return None;
2168            }
2169            argv = Some(a.trim().to_string());
2170        }
2171    }
2172    let path = path?;
2173    let argv = argv?;
2174    if path.is_empty() || path.contains(['%', '$']) {
2175        return None;
2176    }
2177    // Split argv on whitespace (systemd show quotes simply; narrow rule:
2178    // reject embedded quotes/escapes we do not understand).
2179    if argv.contains(['"', '\'', '\\', '%', '$']) {
2180        return None;
2181    }
2182    let parts: Vec<String> = argv.split_whitespace().map(|s| s.to_string()).collect();
2183    if parts.is_empty() || parts[0] != path {
2184        return None;
2185    }
2186    let exe = PathBuf::from(path);
2187    if !exe.is_absolute() {
2188        return None;
2189    }
2190    Some((exe, parts[1..].to_vec()))
2191}
2192
2193/// Computes systemd ownership for a spec from show output.
2194fn systemd_ownership(
2195    text: &str,
2196    spec: &ServiceSpec,
2197) -> Result<(Ownership, LifecycleState, bool), ServiceError> {
2198    let mut load: Option<&str> = None;
2199    let mut active: Option<&str> = None;
2200    let mut execstarts: Vec<&str> = Vec::new();
2201    for line in text.lines() {
2202        if let Some(v) = line.strip_prefix("LoadState=") {
2203            load = Some(v.trim());
2204        } else if let Some(v) = line.strip_prefix("ActiveState=") {
2205            active = Some(v.trim());
2206        } else if let Some(v) = line.strip_prefix("ExecStart=") {
2207            execstarts.push(v.trim());
2208        }
2209    }
2210    match load.unwrap_or("") {
2211        "" | "not-found" => return Ok((Ownership::Absent, LifecycleState::Stopped, false)),
2212        "loaded" => {}
2213        _ => return Ok((Ownership::Unknown, LifecycleState::Unknown, true)),
2214    }
2215    let state = match active.unwrap_or("") {
2216        "active" => LifecycleState::Running,
2217        "inactive" => LifecycleState::Stopped,
2218        "activating" | "deactivating" | "reloading" => LifecycleState::Transitioning,
2219        _ => LifecycleState::Unknown,
2220    };
2221    if execstarts.len() != 1 {
2222        return Ok((Ownership::Unknown, state, true));
2223    }
2224    let Some((exe, args)) = parse_exec_start(execstarts[0]) else {
2225        return Ok((Ownership::Unknown, state, true));
2226    };
2227    let observed = reconcile_config_identity(
2228        RegistrationSnapshot {
2229            present: true,
2230            executable: Some(exe),
2231            args,
2232            config: None,
2233            malformed: false,
2234        },
2235        spec,
2236    );
2237    Ok((observed.ownership(spec), state, true))
2238}
2239
2240impl<E: CommandExecutor> ServiceManager for SystemdManager<E> {
2241    fn inspect(&self, spec: &ServiceSpec) -> Result<LifecycleSnapshot, ServiceError> {
2242        let deadline = self.operation_deadline()?;
2243        let out = self
2244            .executor
2245            .run(&self.show_argv(), None, deadline.command_timeout()?)?;
2246        let (ownership, state, present) = if out.status == Some(0) {
2247            systemd_ownership(&out.stdout_text(), spec)?
2248        } else {
2249            (Ownership::Unknown, LifecycleState::Unknown, true)
2250        };
2251        Ok(LifecycleSnapshot {
2252            id: spec.id().clone(),
2253            ownership,
2254            state,
2255            health: HealthState::Unknown,
2256            was_registered: present,
2257            was_running: state == LifecycleState::Running,
2258        })
2259    }
2260
2261    fn install(&mut self, spec: &ServiceSpec) -> Result<TransitionResult, ServiceError> {
2262        // One deadline for the whole operation: the ownership probe, the
2263        // pre-write recheck, and the post-write reload/enable all draw from
2264        // it.
2265        let deadline = self.operation_deadline()?;
2266        let (ownership, _) = self.ownership_until(spec, deadline)?;
2267        match ownership {
2268            Ownership::Absent => {
2269                atomic_write_definition(&self.install.unit_path, &self.install.definition, false)?;
2270                self.post_write(deadline)?;
2271                Ok(TransitionResult {
2272                    operation: ServiceOperation::Install,
2273                    completed: true,
2274                    detail: ServiceError::bounded("installed systemd unit"),
2275                })
2276            }
2277            Ownership::Owned => {
2278                // Re-inspect before destructive overwrite (external changes).
2279                let (recheck, _) = self.ownership_until(spec, deadline)?;
2280                if recheck != Ownership::Owned {
2281                    return Err(ServiceError::denied(spec.id(), recheck));
2282                }
2283                atomic_write_definition(&self.install.unit_path, &self.install.definition, true)?;
2284                self.post_write(deadline)?;
2285                Ok(TransitionResult {
2286                    operation: ServiceOperation::Install,
2287                    completed: true,
2288                    detail: ServiceError::bounded("refreshed owned systemd unit"),
2289                })
2290            }
2291            Ownership::Foreign | Ownership::Unknown => {
2292                Err(ServiceError::denied(spec.id(), ownership))
2293            }
2294        }
2295    }
2296
2297    fn start(
2298        &mut self,
2299        spec: &ServiceSpec,
2300        timeout: Duration,
2301    ) -> Result<TransitionResult, ServiceError> {
2302        let deadline = OperationDeadline::new(timeout)?;
2303        let (ownership, state) = self.ownership_until(spec, deadline)?;
2304        require_owned(spec.id(), ownership)?;
2305        if state == LifecycleState::Running {
2306            return Ok(TransitionResult {
2307                operation: ServiceOperation::Start,
2308                completed: !deadline.expired(),
2309                detail: ServiceError::bounded("already running"),
2310            });
2311        }
2312        self.run_unit("start", deadline)?;
2313        let completed = self.poll_active(true, deadline)?;
2314        Ok(TransitionResult {
2315            operation: ServiceOperation::Start,
2316            completed,
2317            detail: ServiceError::bounded(if completed {
2318                "started"
2319            } else {
2320                "start incomplete; state unconfirmed"
2321            }),
2322        })
2323    }
2324
2325    fn stop(
2326        &mut self,
2327        spec: &ServiceSpec,
2328        timeout: Duration,
2329    ) -> Result<TransitionResult, ServiceError> {
2330        let deadline = OperationDeadline::new(timeout)?;
2331        let (ownership, state) = self.ownership_until(spec, deadline)?;
2332        require_owned(spec.id(), ownership)?;
2333        if state == LifecycleState::Unknown {
2334            return self.stop_failed_owned(spec, deadline);
2335        }
2336        if state == LifecycleState::Stopped {
2337            return Ok(TransitionResult {
2338                operation: ServiceOperation::Stop,
2339                completed: !deadline.expired(),
2340                detail: ServiceError::bounded("already stopped"),
2341            });
2342        }
2343        self.run_unit("stop", deadline)?;
2344        let completed = self.poll_active(false, deadline)?;
2345        Ok(TransitionResult {
2346            operation: ServiceOperation::Stop,
2347            completed,
2348            detail: ServiceError::bounded(if completed {
2349                "stopped"
2350            } else {
2351                "stop incomplete; state unconfirmed"
2352            }),
2353        })
2354    }
2355
2356    fn restart(
2357        &mut self,
2358        spec: &ServiceSpec,
2359        timeout: Duration,
2360    ) -> Result<TransitionResult, ServiceError> {
2361        let deadline = OperationDeadline::new(timeout)?;
2362        let (ownership, _) = self.ownership_until(spec, deadline)?;
2363        require_owned(spec.id(), ownership)?;
2364        self.run_unit("restart", deadline)?;
2365        let completed = self.poll_active(true, deadline)?;
2366        Ok(TransitionResult {
2367            operation: ServiceOperation::Restart,
2368            completed,
2369            detail: ServiceError::bounded(if completed {
2370                "restarted"
2371            } else {
2372                "restart incomplete; state unconfirmed"
2373            }),
2374        })
2375    }
2376
2377    fn uninstall(&mut self, spec: &ServiceSpec) -> Result<TransitionResult, ServiceError> {
2378        // One deadline for the whole operation: both ownership probes, the
2379        // disable, and the daemon-reload all draw from it.
2380        let deadline = self.operation_deadline()?;
2381        let (ownership, _) = self.ownership_until(spec, deadline)?;
2382        require_owned(spec.id(), ownership)?;
2383        // Re-inspect before destructive removal.
2384        let (recheck, _) = self.ownership_until(spec, deadline)?;
2385        if recheck != Ownership::Owned {
2386            return Err(ServiceError::denied(spec.id(), recheck));
2387        }
2388        // Best-effort disable; a failing disable does not delete the file.
2389        let disable_argv = vec![
2390            "systemctl".to_string(),
2391            self.install.scope.flag().to_string(),
2392            "disable".to_string(),
2393            self.install.unit_name.clone(),
2394        ];
2395        match self
2396            .executor
2397            .run(&disable_argv, None, deadline.command_timeout()?)
2398        {
2399            Ok(out) if out.status == Some(0) => {}
2400            Ok(out) => {
2401                return Ok(TransitionResult {
2402                    operation: ServiceOperation::Uninstall,
2403                    completed: false,
2404                    detail: ServiceError::bounded(format!(
2405                        "disable failed with exit status {}",
2406                        out.status.unwrap_or(-1)
2407                    )),
2408                });
2409            }
2410            Err(e) => {
2411                return Ok(TransitionResult {
2412                    operation: ServiceOperation::Uninstall,
2413                    completed: false,
2414                    detail: ServiceError::bounded(format!("disable failed: {e}")),
2415                });
2416            }
2417        }
2418        std::fs::remove_file(&self.install.unit_path).map_err(|e| {
2419            ServiceError::manager(
2420                ManagerFailureKind::LocalFilesystem,
2421                format!("removing owned unit: {e}"),
2422            )
2423        })?;
2424        if self.install.reload {
2425            let reload_argv = vec![
2426                "systemctl".to_string(),
2427                self.install.scope.flag().to_string(),
2428                "daemon-reload".to_string(),
2429            ];
2430            match self
2431                .executor
2432                .run(&reload_argv, None, deadline.command_timeout()?)
2433            {
2434                Ok(out) if out.status == Some(0) => {}
2435                Ok(out) => {
2436                    return Ok(TransitionResult {
2437                        operation: ServiceOperation::Uninstall,
2438                        completed: false,
2439                        detail: ServiceError::bounded(format!(
2440                            "removed unit but reload exited {}",
2441                            out.status.unwrap_or(-1)
2442                        )),
2443                    });
2444                }
2445                Err(e) => {
2446                    return Ok(TransitionResult {
2447                        operation: ServiceOperation::Uninstall,
2448                        completed: false,
2449                        detail: ServiceError::bounded(format!(
2450                            "removed unit but reload failed: {e}"
2451                        )),
2452                    });
2453                }
2454            }
2455        }
2456        Ok(TransitionResult {
2457            operation: ServiceOperation::Uninstall,
2458            completed: true,
2459            detail: ServiceError::bounded("uninstalled systemd unit"),
2460        })
2461    }
2462}
2463
2464impl<E: CommandExecutor> SystemdManager<E> {
2465    fn post_write(&self, deadline: OperationDeadline) -> Result<(), ServiceError> {
2466        if self.install.reload {
2467            let argv = vec![
2468                "systemctl".to_string(),
2469                self.install.scope.flag().to_string(),
2470                "daemon-reload".to_string(),
2471            ];
2472            let out = self
2473                .executor
2474                .run(&argv, None, deadline.command_timeout()?)?;
2475            ensure_mutation_success(&out, "systemctl daemon-reload")?;
2476        }
2477        if self.install.enable {
2478            let argv = vec![
2479                "systemctl".to_string(),
2480                self.install.scope.flag().to_string(),
2481                "enable".to_string(),
2482                self.install.unit_name.clone(),
2483            ];
2484            let out = self
2485                .executor
2486                .run(&argv, None, deadline.command_timeout()?)?;
2487            ensure_mutation_success(&out, "systemctl enable")?;
2488        }
2489        Ok(())
2490    }
2491}
2492
2493// ---- launchd adapter ----
2494
2495/// launchd domain without automatic EUID-based choice.
2496#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2497pub enum LaunchdDomain {
2498    /// Per-user agent (`gui/<uid>` target supplied by the caller).
2499    UserAgent,
2500    /// System daemon (`system` target, requires appropriate privileges).
2501    SystemDaemon,
2502}
2503
2504/// Caller-owned launchd install material.
2505#[derive(Debug, Clone, PartialEq, Eq)]
2506pub struct LaunchdInstall {
2507    /// Job label (for example `com.example.daemon`).
2508    pub label: String,
2509    /// Explicit domain (never guessed).
2510    pub domain: LaunchdDomain,
2511    /// Bootstrap target: `gui/<uid>` for user agents, `system` for daemons.
2512    pub target: String,
2513    /// Absolute plist path supplied by the caller.
2514    pub plist_path: PathBuf,
2515    /// Exact desired plist bytes (caller-owned content).
2516    pub definition: Vec<u8>,
2517    /// Whether install should bootstrap the job (explicit only).
2518    pub bootstrap_on_install: bool,
2519    /// Bounded wait for state transitions.
2520    pub transition_timeout: Duration,
2521}
2522
2523impl LaunchdInstall {
2524    /// Validates install material.
2525    ///
2526    /// # Errors
2527    ///
2528    /// [`ServiceError::InvalidInput`] when the label or target is empty,
2529    /// overlong, or contains a control character, when the domain and target
2530    /// disagree (a user-agent target must look like `gui/<uid>`, a
2531    /// system-daemon target must be `system`), when the plist path is not
2532    /// absolute, when the definition bytes are empty, overlong, or contain a
2533    /// NUL byte, or when the transition timeout is zero or above
2534    /// [`MAX_TRANSITION_TIMEOUT`].
2535    pub fn new(
2536        label: String,
2537        domain: LaunchdDomain,
2538        target: String,
2539        plist_path: PathBuf,
2540        definition: Vec<u8>,
2541        bootstrap_on_install: bool,
2542        transition_timeout: Duration,
2543    ) -> Result<Self, ServiceError> {
2544        validate_label(&label)?;
2545        if target.is_empty() || target.len() > 128 || target.chars().any(char::is_control) {
2546            return Err(ServiceError::invalid("launchd target is invalid"));
2547        }
2548        match domain {
2549            LaunchdDomain::UserAgent if !target.starts_with("gui/") => {
2550                return Err(ServiceError::invalid(
2551                    "user-agent target must look like gui/<uid>",
2552                ));
2553            }
2554            LaunchdDomain::SystemDaemon if target != "system" => {
2555                return Err(ServiceError::invalid(
2556                    "system-daemon target must be `system`",
2557                ));
2558            }
2559            _ => {}
2560        }
2561        if !plist_path.is_absolute() {
2562            return Err(ServiceError::invalid("plist path must be absolute"));
2563        }
2564        if definition.is_empty() || definition.len() > MAX_DEFINITION_BYTES {
2565            return Err(ServiceError::invalid(
2566                "plist definition is empty or overlong",
2567            ));
2568        }
2569        if definition.contains(&0) {
2570            return Err(ServiceError::invalid("plist definition contains nul"));
2571        }
2572        if transition_timeout.is_zero() || transition_timeout > MAX_TRANSITION_TIMEOUT {
2573            return Err(ServiceError::invalid("transition timeout out of range"));
2574        }
2575        Ok(Self {
2576            label,
2577            domain,
2578            target,
2579            plist_path,
2580            definition,
2581            bootstrap_on_install,
2582            transition_timeout,
2583        })
2584    }
2585}
2586
2587fn validate_label(label: &str) -> Result<(), ServiceError> {
2588    if label.is_empty() || label.len() > 256 || label.chars().any(char::is_control) {
2589        return Err(ServiceError::invalid(
2590            "label is empty, overlong, or has controls",
2591        ));
2592    }
2593    if label.contains(['/', '\\', ' ', '@']) {
2594        return Err(ServiceError::invalid("label must be a bare job label"));
2595    }
2596    if !label
2597        .chars()
2598        .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_')
2599    {
2600        return Err(ServiceError::invalid("label must use [A-Za-z0-9._-] only"));
2601    }
2602    Ok(())
2603}
2604
2605/// launchd manager implementing the neutral contract.
2606#[derive(Debug)]
2607pub struct LaunchdManager<E: CommandExecutor = SystemExecutor> {
2608    executor: E,
2609    install: LaunchdInstall,
2610}
2611
2612impl<E: CommandExecutor> LaunchdManager<E> {
2613    /// Creates a launchd adapter. No manager calls are made here.
2614    pub fn new(executor: E, install: LaunchdInstall) -> Self {
2615        Self { executor, install }
2616    }
2617
2618    /// Returns the install descriptor.
2619    pub fn install_config(&self) -> &LaunchdInstall {
2620        &self.install
2621    }
2622
2623    /// Returns the command executor (test visibility).
2624    pub fn executor(&self) -> &E {
2625        &self.executor
2626    }
2627
2628    fn read_plist_observation(&self) -> Result<RegistrationSnapshot, ServiceError> {
2629        match std::fs::read(&self.install.plist_path) {
2630            Ok(bytes) => parse_launchd_plist(&bytes),
2631            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
2632                Ok(RegistrationSnapshot::absent())
2633            }
2634            Err(e) => Err(ServiceError::manager(
2635                ManagerFailureKind::LocalFilesystem,
2636                format!("reading plist: {e}"),
2637            )),
2638        }
2639    }
2640
2641    /// Creates the single per-operation deadline for this adapter.
2642    ///
2643    /// `install`, `uninstall` and `inspect` take no timeout parameter: their
2644    /// budget is `install.transition_timeout` for the *whole* operation. The
2645    /// clamp is applied exactly once, here, at deadline construction. Every
2646    /// manager invocation the operation makes draws from this one deadline, so
2647    /// no invocation is ever granted a fresh full budget.
2648    fn operation_deadline(&self) -> Result<OperationDeadline, ServiceError> {
2649        OperationDeadline::new(bounded_timeout(self.install.transition_timeout))
2650    }
2651
2652    fn loaded_and_running(
2653        &self,
2654        deadline: OperationDeadline,
2655    ) -> Result<(bool, LifecycleState), ServiceError> {
2656        let argv = vec![
2657            "launchctl".to_string(),
2658            "list".to_string(),
2659            self.install.label.clone(),
2660        ];
2661        let out = self
2662            .executor
2663            .run(&argv, None, deadline.command_timeout()?)?;
2664        if out.status != Some(0) {
2665            return Ok((false, LifecycleState::Stopped));
2666        }
2667        // `launchctl list` prints `"PID" = <n>;` when running, `"PID" = -;`
2668        // or missing when loaded but not running. Narrow rule: running only
2669        // when a numeric PID is present.
2670        let text = out.stdout_text();
2671        for line in text.lines() {
2672            let line = line.trim();
2673            if line.starts_with("\"PID\"") || line.starts_with("PID") {
2674                if let Some(eq) = line.find('=') {
2675                    let val = line[eq + 1..]
2676                        .trim()
2677                        .trim_matches([';', '"', ' ', '\t'])
2678                        .to_string();
2679                    if val.parse::<i64>().is_ok() {
2680                        return Ok((true, LifecycleState::Running));
2681                    }
2682                    return Ok((true, LifecycleState::Stopped));
2683                }
2684            }
2685        }
2686        // Loaded (exit 0) but no PID line: conservatively Stopped, not Unknown,
2687        // because the file observation already gates ownership.
2688        Ok((true, LifecycleState::Stopped))
2689    }
2690
2691    fn ownership_until(
2692        &self,
2693        spec: &ServiceSpec,
2694        deadline: OperationDeadline,
2695    ) -> Result<(Ownership, LifecycleState, bool, bool), ServiceError> {
2696        let observed = self.read_plist_observation()?;
2697        if !observed.present {
2698            return Ok((Ownership::Absent, LifecycleState::Stopped, false, false));
2699        }
2700        let observed = reconcile_config_identity(observed, spec);
2701        let ownership = observed.ownership(spec);
2702        if ownership != Ownership::Owned {
2703            // Foreign/Unknown files are never probed for loaded state beyond
2704            // what is needed to report Stopped (no destructive calls).
2705            return Ok((ownership, LifecycleState::Unknown, true, false));
2706        }
2707        match self.loaded_and_running(deadline) {
2708            Ok((loaded, state)) => Ok((ownership, state, true, loaded)),
2709            Err(_) => Ok((ownership, LifecycleState::Unknown, true, false)),
2710        }
2711    }
2712}
2713
2714/// Parses plist bytes for `ProgramArguments` ownership.
2715///
2716/// Narrow structured scan (no XML library): finds exactly one
2717/// `<key>ProgramArguments</key>` followed by `<array>` of `<string>`
2718/// entries. Any ambiguity, unsupported escaping, or missing key yields a
2719/// malformed (`Unknown`) snapshot. Label-only observations are never `Owned`.
2720fn parse_launchd_plist(bytes: &[u8]) -> Result<RegistrationSnapshot, ServiceError> {
2721    if bytes.len() > MAX_DEFINITION_BYTES {
2722        return Ok(malformed_snapshot());
2723    }
2724    let text = match std::str::from_utf8(bytes) {
2725        Ok(t) => t,
2726        Err(_) => return Ok(malformed_snapshot()),
2727    };
2728    let key = "<key>ProgramArguments</key>";
2729    if text.matches(key).count() != 1 {
2730        return Ok(malformed_snapshot());
2731    }
2732    let key_pos = text.find(key).expect("counted");
2733    let after_key = &text[key_pos + key.len()..];
2734    let array_open = "<array>";
2735    let array_close = "</array>";
2736    let Some(array_start_rel) = after_key.find(array_open) else {
2737        return Ok(malformed_snapshot());
2738    };
2739    // No other keys may intervene between the key and its array.
2740    if after_key[..array_start_rel].contains("<key>") {
2741        return Ok(malformed_snapshot());
2742    }
2743    let array_body_start = array_start_rel + array_open.len();
2744    let Some(array_end_rel) = after_key[array_body_start..].find(array_close) else {
2745        return Ok(malformed_snapshot());
2746    };
2747    let array_body = &after_key[array_body_start..array_body_start + array_end_rel];
2748    // Only `<string>` entries are supported inside the array.
2749    if array_body.contains('<') && !array_body.contains("<string>") {
2750        // Contains tags but no strings: malformed.
2751        if !array_body.trim().is_empty() {
2752            return Ok(malformed_snapshot());
2753        }
2754    }
2755    let mut args: Vec<String> = Vec::new();
2756    let mut rest = array_body;
2757    while let Some(open) = rest.find("<string>") {
2758        let Some(close) = rest[open..].find("</string>") else {
2759            return Ok(malformed_snapshot());
2760        };
2761        let value = rest[open + "<string>".len()..open + close].to_string();
2762        // Reject unsupported XML constructs inside values: no tags, and only
2763        // the five predefined entities.
2764        if value.contains('<') {
2765            return Ok(malformed_snapshot());
2766        }
2767        if value.contains('&') && !is_supported_entity(&value) {
2768            return Ok(malformed_snapshot());
2769        }
2770        args.push(unescape_plist(&value));
2771        rest = &rest[open + close + "</string>".len()..];
2772    }
2773    // Any leftover non-whitespace tags mean an unsupported shape.
2774    let stripped = rest.replace([' ', '\t', '\n', '\r'], "");
2775    if !stripped.is_empty() {
2776        return Ok(malformed_snapshot());
2777    }
2778    if args.is_empty() {
2779        return Ok(malformed_snapshot());
2780    }
2781    let exe = PathBuf::from(&args[0]);
2782    if !exe.is_absolute() {
2783        return Ok(malformed_snapshot());
2784    }
2785    Ok(RegistrationSnapshot {
2786        present: true,
2787        executable: Some(exe),
2788        args: args[1..].to_vec(),
2789        config: None,
2790        malformed: false,
2791    })
2792}
2793
2794fn malformed_snapshot() -> RegistrationSnapshot {
2795    RegistrationSnapshot {
2796        present: true,
2797        executable: None,
2798        args: Vec::new(),
2799        config: None,
2800        malformed: true,
2801    }
2802}
2803
2804fn is_supported_entity(v: &str) -> bool {
2805    // Cheap check: only &amp; &lt; &gt; &quot; &apos; are understood.
2806    let mut rest = v;
2807    while let Some(pos) = rest.find('&') {
2808        let tail = &rest[pos..];
2809        if !(tail.starts_with("&amp;")
2810            || tail.starts_with("&lt;")
2811            || tail.starts_with("&gt;")
2812            || tail.starts_with("&quot;")
2813            || tail.starts_with("&apos;"))
2814        {
2815            return false;
2816        }
2817        rest = &tail[1..];
2818    }
2819    true
2820}
2821
2822fn unescape_plist(v: &str) -> String {
2823    v.replace("&amp;", "&")
2824        .replace("&lt;", "<")
2825        .replace("&gt;", ">")
2826        .replace("&quot;", "\"")
2827        .replace("&apos;", "'")
2828}
2829
2830impl<E: CommandExecutor> ServiceManager for LaunchdManager<E> {
2831    fn inspect(&self, spec: &ServiceSpec) -> Result<LifecycleSnapshot, ServiceError> {
2832        let deadline = self.operation_deadline()?;
2833        let (ownership, state, present, loaded) = self.ownership_until(spec, deadline)?;
2834        Ok(LifecycleSnapshot {
2835            id: spec.id().clone(),
2836            ownership,
2837            state,
2838            health: HealthState::Unknown,
2839            was_registered: present,
2840            was_running: state == LifecycleState::Running && loaded,
2841        })
2842    }
2843
2844    fn install(&mut self, spec: &ServiceSpec) -> Result<TransitionResult, ServiceError> {
2845        // One deadline for the whole operation: the ownership probe, the
2846        // pre-write recheck, and the bootstrap all draw from it.
2847        let deadline = self.operation_deadline()?;
2848        let (ownership, _, present, _) = self.ownership_until(spec, deadline)?;
2849        match ownership {
2850            Ownership::Absent => {
2851                let _ = present;
2852                atomic_write_definition(&self.install.plist_path, &self.install.definition, false)?;
2853                if self.install.bootstrap_on_install {
2854                    self.bootstrap(deadline)?;
2855                }
2856                Ok(TransitionResult {
2857                    operation: ServiceOperation::Install,
2858                    completed: true,
2859                    detail: ServiceError::bounded("installed launchd plist"),
2860                })
2861            }
2862            Ownership::Owned => {
2863                let (recheck, _, _, _) = self.ownership_until(spec, deadline)?;
2864                if recheck != Ownership::Owned {
2865                    return Err(ServiceError::denied(spec.id(), recheck));
2866                }
2867                atomic_write_definition(&self.install.plist_path, &self.install.definition, true)?;
2868                if self.install.bootstrap_on_install {
2869                    self.bootstrap(deadline)?;
2870                }
2871                Ok(TransitionResult {
2872                    operation: ServiceOperation::Install,
2873                    completed: true,
2874                    detail: ServiceError::bounded("refreshed owned launchd plist"),
2875                })
2876            }
2877            Ownership::Foreign | Ownership::Unknown => {
2878                Err(ServiceError::denied(spec.id(), ownership))
2879            }
2880        }
2881    }
2882
2883    fn start(
2884        &mut self,
2885        spec: &ServiceSpec,
2886        timeout: Duration,
2887    ) -> Result<TransitionResult, ServiceError> {
2888        self.start_until(spec, OperationDeadline::new(timeout)?)
2889    }
2890
2891    fn stop(
2892        &mut self,
2893        spec: &ServiceSpec,
2894        timeout: Duration,
2895    ) -> Result<TransitionResult, ServiceError> {
2896        self.stop_until(spec, OperationDeadline::new(timeout)?)
2897    }
2898
2899    fn restart(
2900        &mut self,
2901        spec: &ServiceSpec,
2902        timeout: Duration,
2903    ) -> Result<TransitionResult, ServiceError> {
2904        let deadline = OperationDeadline::new(timeout)?;
2905        let stopped = self.stop_until(spec, deadline)?;
2906        if !stopped.completed {
2907            return Ok(TransitionResult {
2908                operation: ServiceOperation::Restart,
2909                completed: false,
2910                detail: ServiceError::bounded("restart stop phase incomplete; start not attempted"),
2911            });
2912        }
2913        let started = self.start_until(spec, deadline)?;
2914        Ok(TransitionResult {
2915            operation: ServiceOperation::Restart,
2916            completed: started.completed,
2917            detail: ServiceError::bounded(if started.completed {
2918                "restarted"
2919            } else {
2920                "restart start phase incomplete; state unconfirmed"
2921            }),
2922        })
2923    }
2924
2925    fn uninstall(&mut self, spec: &ServiceSpec) -> Result<TransitionResult, ServiceError> {
2926        // One deadline for the whole operation: both ownership probes and the
2927        // bootout all draw from it.
2928        let deadline = self.operation_deadline()?;
2929        let (ownership, _, _, loaded) = self.ownership_until(spec, deadline)?;
2930        require_owned(spec.id(), ownership)?;
2931        let (recheck, _, _, _) = self.ownership_until(spec, deadline)?;
2932        if recheck != Ownership::Owned {
2933            return Err(ServiceError::denied(spec.id(), recheck));
2934        }
2935        if loaded {
2936            let argv = vec![
2937                "launchctl".to_string(),
2938                "bootout".to_string(),
2939                self.install.target.clone(),
2940                self.install.plist_path.to_string_lossy().into_owned(),
2941            ];
2942            match self.executor.run(&argv, None, deadline.command_timeout()?) {
2943                Ok(out) if out.status == Some(0) => {}
2944                Ok(out) => {
2945                    return Ok(TransitionResult {
2946                        operation: ServiceOperation::Uninstall,
2947                        completed: false,
2948                        detail: ServiceError::bounded(format!(
2949                            "bootout exited {}",
2950                            out.status.unwrap_or(-1)
2951                        )),
2952                    });
2953                }
2954                Err(e) => {
2955                    return Ok(TransitionResult {
2956                        operation: ServiceOperation::Uninstall,
2957                        completed: false,
2958                        detail: ServiceError::bounded(format!("bootout failed: {e}")),
2959                    });
2960                }
2961            }
2962        }
2963        std::fs::remove_file(&self.install.plist_path).map_err(|e| {
2964            ServiceError::manager(
2965                ManagerFailureKind::LocalFilesystem,
2966                format!("removing owned plist: {e}"),
2967            )
2968        })?;
2969        Ok(TransitionResult {
2970            operation: ServiceOperation::Uninstall,
2971            completed: true,
2972            detail: ServiceError::bounded("uninstalled launchd plist"),
2973        })
2974    }
2975}
2976
2977impl<E: CommandExecutor> LaunchdManager<E> {
2978    fn start_until(
2979        &self,
2980        spec: &ServiceSpec,
2981        deadline: OperationDeadline,
2982    ) -> Result<TransitionResult, ServiceError> {
2983        let (ownership, state, _, loaded) = self.ownership_until(spec, deadline)?;
2984        require_owned(spec.id(), ownership)?;
2985        if state == LifecycleState::Running {
2986            return Ok(TransitionResult {
2987                operation: ServiceOperation::Start,
2988                completed: !deadline.expired(),
2989                detail: ServiceError::bounded("already running"),
2990            });
2991        }
2992        if !loaded {
2993            self.bootstrap(deadline)?;
2994        }
2995        self.kickstart(deadline)?;
2996        let completed = self.confirm_running(deadline)?;
2997        Ok(TransitionResult {
2998            operation: ServiceOperation::Start,
2999            completed,
3000            detail: ServiceError::bounded(if completed {
3001                "started"
3002            } else {
3003                "start incomplete; state unconfirmed"
3004            }),
3005        })
3006    }
3007
3008    fn stop_until(
3009        &self,
3010        spec: &ServiceSpec,
3011        deadline: OperationDeadline,
3012    ) -> Result<TransitionResult, ServiceError> {
3013        let (ownership, state, _, _) = self.ownership_until(spec, deadline)?;
3014        require_owned(spec.id(), ownership)?;
3015        if state == LifecycleState::Stopped {
3016            return Ok(TransitionResult {
3017                operation: ServiceOperation::Stop,
3018                completed: !deadline.expired(),
3019                detail: ServiceError::bounded("already stopped"),
3020            });
3021        }
3022        let argv = vec![
3023            "launchctl".to_string(),
3024            "stop".to_string(),
3025            self.install.label.clone(),
3026        ];
3027        let out = self
3028            .executor
3029            .run(&argv, None, deadline.command_timeout()?)?;
3030        ensure_mutation_success(&out, "launchctl stop")?;
3031        let completed = self.confirm_stopped(deadline)?;
3032        Ok(TransitionResult {
3033            operation: ServiceOperation::Stop,
3034            completed,
3035            detail: ServiceError::bounded(if completed {
3036                "stopped"
3037            } else {
3038                "stop incomplete; state unconfirmed"
3039            }),
3040        })
3041    }
3042
3043    fn bootstrap(&self, deadline: OperationDeadline) -> Result<(), ServiceError> {
3044        let argv = vec![
3045            "launchctl".to_string(),
3046            "bootstrap".to_string(),
3047            self.install.target.clone(),
3048            self.install.plist_path.to_string_lossy().into_owned(),
3049        ];
3050        let out = self
3051            .executor
3052            .run(&argv, None, deadline.command_timeout()?)?;
3053        ensure_mutation_success(&out, "launchctl bootstrap")
3054    }
3055
3056    fn kickstart(&self, deadline: OperationDeadline) -> Result<(), ServiceError> {
3057        let argv = vec![
3058            "launchctl".to_string(),
3059            "kickstart".to_string(),
3060            "-k".to_string(),
3061            format!("{}/{}", self.install.target, self.install.label),
3062        ];
3063        let out = self
3064            .executor
3065            .run(&argv, None, deadline.command_timeout()?)?;
3066        ensure_mutation_success(&out, "launchctl kickstart")
3067    }
3068
3069    fn confirm_running(&self, deadline: OperationDeadline) -> Result<bool, ServiceError> {
3070        loop {
3071            match self.loaded_and_running(deadline) {
3072                Ok((_, LifecycleState::Running)) => return Ok(!deadline.expired()),
3073                Ok(_) => {}
3074                Err(e) => return Err(e),
3075            }
3076            if deadline.expired() {
3077                return Ok(false);
3078            }
3079            std::thread::sleep(
3080                deadline
3081                    .remaining()
3082                    .unwrap_or_default()
3083                    .min(Duration::from_millis(100)),
3084            );
3085        }
3086    }
3087
3088    fn confirm_stopped(&self, deadline: OperationDeadline) -> Result<bool, ServiceError> {
3089        loop {
3090            match self.loaded_and_running(deadline) {
3091                Ok((_, LifecycleState::Stopped)) => return Ok(!deadline.expired()),
3092                Ok(_) => {}
3093                Err(e) => return Err(e),
3094            }
3095            if deadline.expired() {
3096                return Ok(false);
3097            }
3098            std::thread::sleep(
3099                deadline
3100                    .remaining()
3101                    .unwrap_or_default()
3102                    .min(Duration::from_millis(100)),
3103            );
3104        }
3105    }
3106}
3107
3108// ---- cron adapter ----
3109
3110/// How a crontab relates to one managed block.
3111///
3112/// This is an **alias** of the canonical [`Ownership`] classification, not a
3113/// distinct enum: `eggup_service::CronOwnership` and
3114/// `eggup_core::Ownership` denote one type. `CronOwnership::Absent` and
3115/// friends keep resolving, and [`cron_classify`] keeps its public return
3116/// spelling.
3117///
3118/// The classification *logic* is unchanged: no managed block is `Absent`,
3119/// exactly one block matching the desired content is `Owned`, the same marker
3120/// with different content (another deployment) is `Foreign`, and an ambiguous
3121/// or malformed crontab is `Unknown` and fails closed.
3122pub type CronOwnership = Ownership;
3123
3124/// Validates a cron marker (unique, single-line, no shell).
3125fn validate_marker(marker: &str) -> Result<(), ServiceError> {
3126    if marker.is_empty() || marker.len() > 128 || marker.chars().any(char::is_control) {
3127        return Err(ServiceError::invalid("cron marker is invalid"));
3128    }
3129    if marker.contains(['\n', '\r']) {
3130        return Err(ServiceError::invalid("cron marker must be single-line"));
3131    }
3132    Ok(())
3133}
3134
3135/// Validates a desired cron block (exact lines between markers).
3136fn validate_block(block: &str) -> Result<(), ServiceError> {
3137    if block.len() > MAX_CRONTAB_BYTES / 2 {
3138        return Err(ServiceError::invalid("cron block exceeds bound"));
3139    }
3140    if block.contains('\0') {
3141        return Err(ServiceError::invalid("cron block contains nul"));
3142    }
3143    Ok(())
3144}
3145
3146fn begin_line(marker: &str) -> String {
3147    format!("# BEGIN {marker}")
3148}
3149
3150fn end_line(marker: &str) -> String {
3151    format!("# END {marker}")
3152}
3153
3154/// Locates managed blocks: returns `(begin_line_idx, end_line_idx)` pairs.
3155fn find_blocks(lines: &[&str], marker: &str) -> Vec<(usize, usize)> {
3156    let begin = begin_line(marker);
3157    let end = end_line(marker);
3158    let mut out = Vec::new();
3159    let mut i = 0;
3160    while i < lines.len() {
3161        if lines[i].trim_end() == begin {
3162            let mut j = i + 1;
3163            while j < lines.len() && lines[j].trim_end() != end {
3164                j += 1;
3165            }
3166            if j < lines.len() {
3167                out.push((i, j));
3168                i = j + 1;
3169                continue;
3170            }
3171            // Unterminated BEGIN without END: treat as a block to the end
3172            // (malformed → Unknown at classification).
3173            out.push((i, lines.len()));
3174            break;
3175        }
3176        i += 1;
3177    }
3178    out
3179}
3180
3181/// Classifies a crontab against one desired block.
3182pub fn cron_classify(crontab: &str, marker: &str, desired: &str) -> CronOwnership {
3183    let lines: Vec<&str> = crontab.lines().collect();
3184    let blocks = find_blocks(&lines, marker);
3185    match blocks.len() {
3186        0 => CronOwnership::Absent,
3187        1 => {
3188            let (b, e) = blocks[0];
3189            if e >= lines.len() {
3190                return CronOwnership::Unknown;
3191            }
3192            let current = lines[b + 1..e].join("\n");
3193            if current == desired.trim_matches('\n') || current == desired {
3194                CronOwnership::Owned
3195            } else {
3196                // Documented rule: same marker with different content is
3197                // Foreign (another deployment owns the marker name).
3198                CronOwnership::Foreign
3199            }
3200        }
3201        _ => CronOwnership::Unknown,
3202    }
3203}
3204
3205/// Merges one managed block idempotently, preserving unrelated bytes.
3206///
3207/// Returns `(new_crontab, changed)`. Fails closed on duplicate markers or
3208/// foreign content (no destructive overwrite). Appends with exactly one
3209/// trailing newline when creating.
3210///
3211/// # Errors
3212///
3213/// [`ServiceError::InvalidInput`] when the marker is invalid, when the
3214/// desired block is overlong or contains a NUL byte, or when the merged
3215/// crontab would exceed the crontab bound.
3216///
3217/// [`ServiceError::OwnershipDenied`] when the managed block exists with
3218/// different content (`Foreign`): the block is never overwritten.
3219///
3220/// [`ServiceError::Conflict`] when the crontab holds multiple or malformed
3221/// managed blocks (`Unknown`).
3222pub fn cron_merge(
3223    crontab: &str,
3224    marker: &str,
3225    desired: &str,
3226) -> Result<(String, bool), ServiceError> {
3227    validate_marker(marker)?;
3228    validate_block(desired)?;
3229    match cron_classify(crontab, marker, desired) {
3230        CronOwnership::Owned => Ok((crontab.to_string(), false)),
3231        CronOwnership::Absent => {
3232            let desired_trimmed = desired.trim_matches('\n');
3233            let block = format!(
3234                "{}\n{}\n{}",
3235                begin_line(marker),
3236                desired_trimmed,
3237                end_line(marker)
3238            );
3239            let mut out = crontab.to_string();
3240            if out.is_empty() {
3241                out = format!("{block}\n");
3242            } else if out.ends_with('\n') {
3243                out.push_str(&format!("{block}\n"));
3244            } else {
3245                out.push_str(&format!("\n{block}\n"));
3246            }
3247            if out.len() > MAX_CRONTAB_BYTES {
3248                return Err(ServiceError::invalid("merged crontab exceeds bound"));
3249            }
3250            Ok((out, true))
3251        }
3252        CronOwnership::Foreign => Err(ServiceError::denied(
3253            &ServiceId::new(format!("cron:{marker}"))
3254                .unwrap_or_else(|_| ServiceId::new("cron").expect("static")),
3255            Ownership::Foreign,
3256        )),
3257        CronOwnership::Unknown => Err(ServiceError::conflict(
3258            "multiple or malformed managed cron blocks; refusing to mutate",
3259        )),
3260    }
3261}
3262
3263/// Removes the owned managed block, preserving unrelated bytes.
3264///
3265/// Returns `(new_crontab, changed)`. Only an exact `Owned` block is removed;
3266/// `Absent` is a no-op without rewrite; `Foreign`/`Unknown` fail closed.
3267///
3268/// # Errors
3269///
3270/// [`ServiceError::InvalidInput`] when the marker is invalid.
3271///
3272/// [`ServiceError::OwnershipDenied`] when the managed block exists with
3273/// different content (`Foreign`): the block is never removed.
3274///
3275/// [`ServiceError::Conflict`] when the crontab holds multiple or malformed
3276/// managed blocks (`Unknown`).
3277pub fn cron_remove(
3278    crontab: &str,
3279    marker: &str,
3280    desired: &str,
3281) -> Result<(String, bool), ServiceError> {
3282    validate_marker(marker)?;
3283    match cron_classify(crontab, marker, desired) {
3284        CronOwnership::Absent => Ok((crontab.to_string(), false)),
3285        CronOwnership::Owned => {
3286            let lines: Vec<&str> = crontab.lines().collect();
3287            let blocks = find_blocks(&lines, marker);
3288            debug_assert_eq!(blocks.len(), 1);
3289            let (b, e) = blocks[0];
3290            let mut kept: Vec<&str> = Vec::new();
3291            for (i, line) in lines.iter().enumerate() {
3292                if i < b || i > e {
3293                    kept.push(line);
3294                }
3295            }
3296            let mut out = kept.join("\n");
3297            if !crontab.is_empty() && !out.is_empty() {
3298                // Preserve the trailing-newline convention of the input.
3299                if crontab.ends_with('\n') {
3300                    out.push('\n');
3301                }
3302            }
3303            // Removing the only block from a file that was exactly the block
3304            // yields an empty crontab (valid: `crontab -r` equivalent via
3305            // `crontab -` with empty input is avoided; caller handles empty
3306            // as `crontab -r`? To keep one code path, return empty string and
3307            // let the adapter decide between `crontab -` and `crontab -r`.
3308            // Here we return the empty string; the adapter writes it via
3309            // `crontab -` only when changed (empty write clears the crontab
3310            // on most implementations; documented).
3311            Ok((out, true))
3312        }
3313        CronOwnership::Foreign => Err(ServiceError::denied(
3314            &ServiceId::new(format!("cron:{marker}"))
3315                .unwrap_or_else(|_| ServiceId::new("cron").expect("static")),
3316            Ownership::Foreign,
3317        )),
3318        CronOwnership::Unknown => Err(ServiceError::conflict(
3319            "multiple or malformed managed cron blocks; refusing to mutate",
3320        )),
3321    }
3322}
3323
3324/// Cron manager: a managed block inside the user's crontab.
3325///
3326/// Cron has no native start/stop process semantics; those operations return
3327/// explicit `InvalidInput` errors instead of pretending success.
3328#[derive(Debug)]
3329pub struct CronManager<E: CommandExecutor = SystemExecutor> {
3330    executor: E,
3331    marker: String,
3332    desired_block: String,
3333    transition_timeout: Duration,
3334}
3335
3336impl<E: CommandExecutor> CronManager<E> {
3337    /// Creates a cron adapter with a unique marker and exact desired block.
3338    ///
3339    /// # Errors
3340    ///
3341    /// [`ServiceError::InvalidInput`] when the marker is empty, overlong, or
3342    /// contains a control character, when the desired block is overlong or
3343    /// contains a NUL byte, or when the transition timeout is zero or above
3344    /// [`MAX_TRANSITION_TIMEOUT`].
3345    pub fn new(
3346        executor: E,
3347        marker: String,
3348        desired_block: String,
3349        transition_timeout: Duration,
3350    ) -> Result<Self, ServiceError> {
3351        validate_marker(&marker)?;
3352        validate_block(&desired_block)?;
3353        if transition_timeout.is_zero() || transition_timeout > MAX_TRANSITION_TIMEOUT {
3354            return Err(ServiceError::invalid("transition timeout out of range"));
3355        }
3356        Ok(Self {
3357            executor,
3358            marker,
3359            desired_block,
3360            transition_timeout,
3361        })
3362    }
3363
3364    /// Returns the marker.
3365    pub fn marker(&self) -> &str {
3366        &self.marker
3367    }
3368
3369    /// Creates the single per-operation deadline for this adapter.
3370    ///
3371    /// Cron's declared budget is `transition_timeout` for the *whole*
3372    /// operation. The clamp is applied exactly once, here, at deadline
3373    /// construction, so no manager invocation is ever granted a fresh full
3374    /// budget.
3375    fn operation_deadline(&self) -> Result<OperationDeadline, ServiceError> {
3376        OperationDeadline::new(bounded_timeout(self.transition_timeout))
3377    }
3378
3379    /// The single cron ownership rule.
3380    ///
3381    /// Ownership is decided **only** by [`cron_classify`]: exactly one block
3382    /// with this marker whose body byte-equals `desired_block` is `Owned`; a
3383    /// same-marker block with different content is `Foreign`; multiple or
3384    /// unterminated blocks are `Unknown`; no block is `Absent`.
3385    ///
3386    /// The executable-containment gate
3387    /// ([`CronManager::require_consistent_request`]) is a separate, explicit
3388    /// check applied before any listing or mutation. It is not part of this
3389    /// rule, and the rule never inspects the whole crontab.
3390    fn cron_ownership(&self, crontab: &str) -> CronOwnership {
3391        cron_classify(crontab, &self.marker, &self.desired_block)
3392    }
3393
3394    /// The executable-containment gate for the cron request material.
3395    ///
3396    /// The managed block body is caller-supplied material. It must name the
3397    /// spec executable; otherwise the request asks this adapter to manage a
3398    /// block for a different binary. The gate fails closed: the request is
3399    /// refused with [`ServiceError::InvalidInput`] before any listing or
3400    /// mutation happens.
3401    fn require_consistent_request(&self, spec: &ServiceSpec) -> Result<(), ServiceError> {
3402        let exe = spec.executable().to_string_lossy().into_owned();
3403        if !self.desired_block.contains(&exe) {
3404            return Err(ServiceError::invalid(
3405                "cron managed block body must contain the spec executable path",
3406            ));
3407        }
3408        Ok(())
3409    }
3410
3411    fn list_crontab(&self, deadline: OperationDeadline) -> Result<String, ServiceError> {
3412        let argv = vec!["crontab".to_string(), "-l".to_string()];
3413        match self.executor.run(&argv, None, deadline.command_timeout()?) {
3414            Ok(out) => {
3415                if out.status == Some(0) {
3416                    let text = out.stdout_text();
3417                    if text.len() > MAX_CRONTAB_BYTES {
3418                        return Err(ServiceError::manager(
3419                            ManagerFailureKind::Protocol,
3420                            "crontab exceeds bound",
3421                        ));
3422                    }
3423                    Ok(text)
3424                } else {
3425                    // `crontab -l` exits 1 with "no crontab" when empty.
3426                    // Treat that as empty, not as failure.
3427                    let combined =
3428                        format!("{}{}", out.stdout_text(), out.stderr_text()).to_lowercase();
3429                    if combined.contains("no crontab") {
3430                        Ok(String::new())
3431                    } else {
3432                        Err(ServiceError::manager(
3433                            ManagerFailureKind::Protocol,
3434                            format!(
3435                                "crontab -l exited {}: {}",
3436                                out.status.unwrap_or(-1),
3437                                ServiceError::bounded(out.stderr_text()),
3438                            ),
3439                        ))
3440                    }
3441                }
3442            }
3443            Err(e) => Err(e),
3444        }
3445    }
3446
3447    fn write_crontab(
3448        &self,
3449        content: &str,
3450        deadline: OperationDeadline,
3451    ) -> Result<(), ServiceError> {
3452        if content.len() > MAX_CRONTAB_BYTES {
3453            return Err(ServiceError::invalid("crontab content exceeds bound"));
3454        }
3455        let argv = vec!["crontab".to_string(), "-".to_string()];
3456        let out =
3457            self.executor
3458                .run(&argv, Some(content.as_bytes()), deadline.command_timeout()?)?;
3459        if out.status != Some(0) {
3460            return Err(ServiceError::manager(
3461                ManagerFailureKind::Protocol,
3462                format!(
3463                    "crontab - exited {}: {}",
3464                    out.status.unwrap_or(-1),
3465                    ServiceError::bounded(out.stderr_text()),
3466                ),
3467            ));
3468        }
3469        Ok(())
3470    }
3471}
3472
3473impl<E: CommandExecutor> ServiceManager for CronManager<E> {
3474    fn inspect(&self, spec: &ServiceSpec) -> Result<LifecycleSnapshot, ServiceError> {
3475        // Cron has no running process semantics; state is Stopped when the
3476        // block exists (supervised externally) and Stopped when absent.
3477        // Health remains a separate consumer probe.
3478        //
3479        // The executable-containment gate refuses an inconsistent request
3480        // before any listing happens.
3481        self.require_consistent_request(spec)?;
3482        // Exactly one `crontab -l` for the whole inspection.
3483        let deadline = self.operation_deadline()?;
3484        let (ownership, state, present) = match self.list_crontab(deadline) {
3485            Ok(text) => {
3486                let ownership = self.cron_ownership(&text);
3487                let present = ownership != CronOwnership::Absent;
3488                (ownership, LifecycleState::Stopped, present)
3489            }
3490            // A crontab that cannot be listed is Unknown, never Absent, and
3491            // never permits a mutation.
3492            Err(_) => (Ownership::Unknown, LifecycleState::Unknown, false),
3493        };
3494        Ok(LifecycleSnapshot {
3495            id: spec.id().clone(),
3496            ownership,
3497            state,
3498            health: HealthState::Unknown,
3499            was_registered: present,
3500            was_running: false,
3501        })
3502    }
3503
3504    fn install(&mut self, spec: &ServiceSpec) -> Result<TransitionResult, ServiceError> {
3505        // The executable-containment gate refuses an inconsistent request
3506        // before any listing happens.
3507        self.require_consistent_request(spec)?;
3508        let deadline = self.operation_deadline()?;
3509        let current = self.list_crontab(deadline)?;
3510        // The single ownership rule decides what may happen here.
3511        if self.cron_ownership(&current) == CronOwnership::Owned {
3512            return Ok(TransitionResult {
3513                operation: ServiceOperation::Install,
3514                completed: true,
3515                detail: ServiceError::bounded("cron block already installed"),
3516            });
3517        }
3518        // Reuse pure merge (fail-closed on Foreign/Unknown, idempotent).
3519        //
3520        // `cron_merge` applies the same rule, so it already rejects `Foreign`
3521        // and `Unknown` before returning, and it reports `Foreign` against
3522        // the synthetic `cron:{marker}` id that owns the block.
3523        let (merged, changed) = cron_merge(&current, &self.marker, &self.desired_block)?;
3524        if !changed {
3525            return Ok(TransitionResult {
3526                operation: ServiceOperation::Install,
3527                completed: true,
3528                detail: ServiceError::bounded("cron block already installed"),
3529            });
3530        }
3531        // Re-list before destructive write (external crontab changes).
3532        let fresh = self.list_crontab(deadline)?;
3533        if fresh != current {
3534            return Err(ServiceError::conflict(
3535                "crontab changed during install; re-inspect before retry",
3536            ));
3537        }
3538        self.write_crontab(&merged, deadline)?;
3539        Ok(TransitionResult {
3540            operation: ServiceOperation::Install,
3541            completed: true,
3542            detail: ServiceError::bounded("installed cron block"),
3543        })
3544    }
3545
3546    fn start(
3547        &mut self,
3548        _spec: &ServiceSpec,
3549        _timeout: Duration,
3550    ) -> Result<TransitionResult, ServiceError> {
3551        Err(ServiceError::invalid(
3552            "cron has no start semantics; supervision is external",
3553        ))
3554    }
3555
3556    fn stop(
3557        &mut self,
3558        _spec: &ServiceSpec,
3559        _timeout: Duration,
3560    ) -> Result<TransitionResult, ServiceError> {
3561        Err(ServiceError::invalid(
3562            "cron has no stop semantics; supervision is external",
3563        ))
3564    }
3565
3566    fn restart(
3567        &mut self,
3568        _spec: &ServiceSpec,
3569        _timeout: Duration,
3570    ) -> Result<TransitionResult, ServiceError> {
3571        Err(ServiceError::invalid(
3572            "cron has no restart semantics; supervision is external",
3573        ))
3574    }
3575
3576    fn uninstall(&mut self, spec: &ServiceSpec) -> Result<TransitionResult, ServiceError> {
3577        // The executable-containment gate refuses an inconsistent request
3578        // before any listing happens.
3579        self.require_consistent_request(spec)?;
3580        let deadline = self.operation_deadline()?;
3581        let current = self.list_crontab(deadline)?;
3582        // The single ownership rule decides what may happen here.
3583        match self.cron_ownership(&current) {
3584            CronOwnership::Owned => {}
3585            CronOwnership::Absent => {
3586                return Ok(TransitionResult {
3587                    operation: ServiceOperation::Uninstall,
3588                    completed: true,
3589                    detail: ServiceError::bounded("cron block already absent"),
3590                });
3591            }
3592            CronOwnership::Foreign => {
3593                return Err(ServiceError::denied(spec.id(), Ownership::Foreign));
3594            }
3595            CronOwnership::Unknown => {
3596                return Err(ServiceError::denied(spec.id(), Ownership::Unknown));
3597            }
3598        }
3599        let (removed, changed) = cron_remove(&current, &self.marker, &self.desired_block)?;
3600        if !changed {
3601            return Ok(TransitionResult {
3602                operation: ServiceOperation::Uninstall,
3603                completed: true,
3604                detail: ServiceError::bounded("cron block already absent"),
3605            });
3606        }
3607        let fresh = self.list_crontab(deadline)?;
3608        if fresh != current {
3609            return Err(ServiceError::conflict(
3610                "crontab changed during uninstall; re-inspect before retry",
3611            ));
3612        }
3613        // Avoid a redundant write when nothing changes (handled above);
3614        // here a change is required, so write exactly once.
3615        self.write_crontab(&removed, deadline)?;
3616        Ok(TransitionResult {
3617            operation: ServiceOperation::Uninstall,
3618            completed: true,
3619            detail: ServiceError::bounded("removed owned cron block"),
3620        })
3621    }
3622}
3623
3624// ---- host detection ----
3625
3626/// Candidate manager families for auto-selection (policy helper output).
3627#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3628pub enum CandidateManager {
3629    /// systemd with an explicit scope.
3630    Systemd(SystemdScope),
3631    /// launchd with an explicit domain.
3632    Launchd(LaunchdDomain),
3633    /// User crontab supervision.
3634    Cron,
3635}
3636
3637/// Observed host facts (separate from selection policy).
3638#[derive(Debug, Clone, PartialEq, Eq)]
3639pub struct HostFacts {
3640    /// `std::env::consts::OS` value at detection time.
3641    pub os: String,
3642    /// Whether a usable systemd manager was observed (Linux only).
3643    pub systemd_available: bool,
3644    /// Whether `launchctl` was observed (macOS only).
3645    pub launchd_available: bool,
3646    /// Whether `crontab` was observed.
3647    pub crontab_available: bool,
3648}
3649
3650/// Inspects host manager facts without choosing policy.
3651///
3652/// Distinguishes detection failure (`Err`) from "not installed"
3653/// (`Ok` with `*_available = false`). Never elevates or mutates.
3654///
3655/// # Errors
3656///
3657/// [`ServiceError::Manager`] with a classified [`ManagerFailureKind`] when a
3658/// probe fails for a reason other than "the manager is not installed":
3659/// `Timeout` when the probe exceeds its deadline, `NotFound` when the manager
3660/// binary is absent, `Permission` when the platform reports an access
3661/// denial, `Spawn` when the child cannot be created or driven, and
3662/// `Protocol` when the manager ran and produced a result that cannot be
3663/// interpreted.
3664///
3665/// The classification is read from the typed kind, never from the error
3666/// text:
3667///
3668/// ```no_run
3669/// use eggup_service::{inspect_host, ManagerFailureKind, SystemExecutor};
3670///
3671/// let facts = inspect_host(&SystemExecutor::new())?;
3672/// # Ok::<(), eggup_service::ServiceError>(())
3673/// ```
3674///
3675/// A consumer distinguishes two failure kinds by matching the kind, not by
3676/// parsing the rendered message:
3677///
3678/// ```no_run
3679/// use eggup_service::{inspect_host, ManagerFailureKind, SystemExecutor};
3680///
3681/// match inspect_host(&SystemExecutor::new()) {
3682///     Ok(facts) => {
3683///         let _ = facts.systemd_available;
3684///     }
3685///     Err(err) => match err.manager_kind() {
3686///         Some(ManagerFailureKind::Timeout) => {
3687///             // The manager probe exceeded its deadline: retry later.
3688///         }
3689///         Some(ManagerFailureKind::NotFound) => {
3690///             // The manager is not installed on this host.
3691///         }
3692///         _ => {
3693///             // Any other classified manager failure.
3694///         }
3695///     },
3696/// }
3697/// # Ok::<(), eggup_service::ServiceError>(())
3698/// ```
3699pub fn inspect_host(executor: &impl CommandExecutor) -> Result<HostFacts, ServiceError> {
3700    let os = std::env::consts::OS.to_string();
3701    // systemd: Linux only. Binary probe + well-known runtime dir.
3702    let systemd_available = if os == "linux" {
3703        let runtime_dir = std::path::Path::new("/run/systemd/system").exists();
3704        match executor.run(
3705            &["systemctl".to_string(), "--version".to_string()],
3706            None,
3707            Duration::from_secs(5),
3708        ) {
3709            Ok(out) => out.status == Some(0) && runtime_dir,
3710            // A missing manager binary is "not installed", not a failure.
3711            // The classification is read from the typed kind, never from the
3712            // error text.
3713            Err(e) if e.manager_kind() == Some(ManagerFailureKind::NotFound) => false,
3714            Err(e) => return Err(e),
3715        }
3716    } else {
3717        false
3718    };
3719    let launchd_available = if os == "macos" {
3720        match executor.run(
3721            &["launchctl".to_string(), "version".to_string()],
3722            None,
3723            Duration::from_secs(5),
3724        ) {
3725            Ok(out) => out.status == Some(0),
3726            // A missing manager binary is "not installed", not a failure.
3727            // The classification is read from the typed kind, never from the
3728            // error text.
3729            Err(e) if e.manager_kind() == Some(ManagerFailureKind::NotFound) => false,
3730            Err(e) => return Err(e),
3731        }
3732    } else {
3733        false
3734    };
3735    let crontab_available = match executor.run(
3736        &["crontab".to_string(), "-l".to_string()],
3737        None,
3738        Duration::from_secs(5),
3739    ) {
3740        Ok(_) => true,
3741        // A missing manager binary is "not installed", not a failure. The
3742        // classification is read from the typed kind, never from the error
3743        // text.
3744        Err(e) if e.manager_kind() == Some(ManagerFailureKind::NotFound) => false,
3745        Err(e) => return Err(e),
3746    };
3747    Ok(HostFacts {
3748        os,
3749        systemd_available,
3750        launchd_available,
3751        crontab_available,
3752    })
3753}
3754
3755/// Small explicit auto-selection policy over [`HostFacts`].
3756///
3757/// Overridable: consumers may ignore this and construct a specific adapter.
3758/// Linux with usable systemd yields systemd; macOS with launchd yields
3759/// launchd; otherwise cron is the candidate where available. Empty output
3760/// means no candidate (distinct from detection failure, which is `Err` from
3761/// [`inspect_host`]).
3762pub fn candidate_managers(facts: &HostFacts) -> Vec<CandidateManager> {
3763    if facts.os == "macos" && facts.launchd_available {
3764        let mut out = vec![CandidateManager::Launchd(LaunchdDomain::UserAgent)];
3765        if facts.crontab_available {
3766            out.push(CandidateManager::Cron);
3767        }
3768        return out;
3769    }
3770    if facts.os == "linux" && facts.systemd_available {
3771        let mut out = vec![CandidateManager::Systemd(SystemdScope::System)];
3772        if facts.crontab_available {
3773            out.push(CandidateManager::Cron);
3774        }
3775        return out;
3776    }
3777    if facts.crontab_available {
3778        return vec![CandidateManager::Cron];
3779    }
3780    Vec::new()
3781}
3782
3783/// Builds an absolute path for the host platform.
3784///
3785/// `ServiceSpec` requires an absolute executable on every platform, so a
3786/// hardcoded POSIX path is simply not absolute on Windows and is refused there.
3787/// Prefixing a drive keeps one fixture valid on both, and on Unix it is the
3788/// identity function. Not test-gated: the public `TestDoubleManager` uses it.
3789pub(crate) fn absolute(path: &str) -> PathBuf {
3790    if cfg!(windows) {
3791        PathBuf::from(format!(r"C:\{}", path.trim_start_matches('/')))
3792    } else {
3793        PathBuf::from(path)
3794    }
3795}
3796
3797#[cfg(test)]
3798mod tests {
3799    use super::*;
3800    use std::time::Duration;
3801
3802    fn spec(id: &str, exe: &str, args: &[&str]) -> ServiceSpec {
3803        ServiceSpec::new(
3804            ServiceId::new(id).unwrap(),
3805            // Callers pass POSIX-looking strings; `absolute` makes them valid on
3806            // Windows too, where a bare "/opt/app/bin" is not absolute.
3807            absolute(exe),
3808            args.iter().map(|s| s.to_string()).collect(),
3809            None,
3810        )
3811        .unwrap()
3812    }
3813
3814    #[test]
3815    fn diagnostic_byte_bounds_preserve_utf8_at_256_and_512_edges() {
3816        for bound in [256, 512] {
3817            let exact = truncate_utf8_bytes("a".repeat(bound), bound);
3818            assert_eq!(exact.len(), bound);
3819            let over = truncate_utf8_bytes("a".repeat(bound + 1), bound);
3820            assert_eq!(over.len(), bound);
3821
3822            for character in ["é", "€", "🧡"] {
3823                let width = character.len();
3824                let mut input = "a".repeat(bound - width + 1);
3825                input.push_str(character);
3826                input.push_str("tail");
3827                let bounded = truncate_utf8_bytes(input, bound);
3828                assert_eq!(bounded.len(), bound - width + 1);
3829                assert!(bounded.is_char_boundary(bounded.len()));
3830            }
3831        }
3832    }
3833
3834    #[test]
3835    fn service_errors_output_and_permission_remediation_stay_utf8_bounded() {
3836        let unicode = "🧡".repeat(200);
3837        // One declared ceiling governs the manager-output diagnostic data
3838        // class; every production truncation site for that class uses it.
3839        assert_eq!(MAX_DIAGNOSTIC_BYTES, 512);
3840        let invalid = ServiceError::invalid(unicode.clone());
3841        assert!(
3842            matches!(invalid, ServiceError::InvalidInput(text) if text.len() <= MAX_DIAGNOSTIC_BYTES && text.is_char_boundary(text.len()))
3843        );
3844        assert!(ServiceError::bounded(unicode.clone()).len() <= MAX_DIAGNOSTIC_BYTES);
3845        assert!(ServiceError::bounded(&unicode).len() <= MAX_DIAGNOSTIC_BYTES);
3846
3847        let manager = ServiceError::manager(
3848            ManagerFailureKind::Protocol,
3849            format!("manager failed: {unicode}"),
3850        );
3851        assert!(
3852            matches!(manager, ServiceError::Manager { detail, .. } if detail.len() <= MAX_DIAGNOSTIC_BYTES && detail.is_char_boundary(detail.len()))
3853        );
3854        // The crate declares exactly one ceiling for manager-derived text:
3855        // `MAX_DIAGNOSTIC_BYTES`. There is no second, smaller re-cap and no
3856        // text-derived reclassification.
3857        let permission = ServiceError::manager(
3858            ManagerFailureKind::Permission,
3859            format!("permission denied: {unicode}"),
3860        );
3861        assert!(
3862            matches!(permission, ServiceError::Manager { kind, detail, .. } if kind == ManagerFailureKind::Permission && detail.len() <= MAX_DIAGNOSTIC_BYTES && detail.is_char_boundary(detail.len()))
3863        );
3864    }
3865
3866    #[test]
3867    fn manager_output_diagnostics_use_the_one_declared_ceiling() {
3868        // The declared ceiling for manager-output diagnostic text.
3869        const DECLARED: usize = MAX_DIAGNOSTIC_BYTES;
3870        assert_eq!(DECLARED, 512);
3871
3872        let stderr = "e".repeat(DECLARED * 2);
3873        let out = ManagerCommandOutput {
3874            status: Some(1),
3875            stdout: Vec::new(),
3876            stderr: stderr.into_bytes(),
3877        };
3878        let error = ensure_mutation_success(&out, "systemctl stop")
3879            .expect_err("a nonzero manager exit must be a typed failure");
3880        let ServiceError::Manager { detail: text, .. } = error else {
3881            panic!("a manager failure must be reported as a manager error");
3882        };
3883        // No diagnostic may exceed the declared ceiling.
3884        assert!(
3885            text.len() <= DECLARED,
3886            "the diagnostic exceeded the ceiling"
3887        );
3888        assert!(text.is_char_boundary(text.len()));
3889        // The manager's own output must be retained up to the declared
3890        // ceiling. A second, smaller ceiling for the same data class would
3891        // silently discard the manager's diagnostic text.
3892        assert!(
3893            text.len() >= DECLARED - 64,
3894            "the manager output must be retained up to the declared ceiling, got {} bytes",
3895            text.len()
3896        );
3897    }
3898
3899    #[test]
3900    fn exact_owned_registration_allows_lifecycle() {
3901        let mut m = TestDoubleManager::new();
3902        let s = spec("svc", "/opt/app/bin", &["--serve"]);
3903        m.put(s.clone(), LifecycleState::Stopped);
3904        let snap = m.inspect(&s).unwrap();
3905        assert_eq!(snap.ownership, Ownership::Owned);
3906        assert_eq!(snap.state, LifecycleState::Stopped);
3907        assert!(!snap.was_running);
3908        m.start(&s, Duration::from_secs(5)).unwrap();
3909        assert_eq!(m.inspect(&s).unwrap().state, LifecycleState::Running);
3910        m.stop(&s, Duration::from_secs(5)).unwrap();
3911        assert_eq!(m.inspect(&s).unwrap().state, LifecycleState::Stopped);
3912    }
3913
3914    #[test]
3915    fn same_name_different_executable_is_foreign() {
3916        let mut m = TestDoubleManager::new();
3917        m.put(
3918            spec("svc", "/opt/other/bin", &["--serve"]),
3919            LifecycleState::Running,
3920        );
3921        let want = spec("svc", "/opt/app/bin", &["--serve"]);
3922        assert_eq!(m.inspect(&want).unwrap().ownership, Ownership::Foreign);
3923        assert!(m.stop(&want, Duration::from_secs(1)).is_err());
3924        assert!(m.uninstall(&want).is_err());
3925    }
3926
3927    #[test]
3928    fn same_executable_different_critical_args_is_foreign() {
3929        let mut m = TestDoubleManager::new();
3930        m.put(
3931            spec("svc", "/opt/app/bin", &["--serve", "--port=1"]),
3932            LifecycleState::Stopped,
3933        );
3934        let want = spec("svc", "/opt/app/bin", &["--serve", "--port=2"]);
3935        assert_eq!(
3936            m.inspect(&want).unwrap().ownership,
3937            Ownership::Foreign,
3938            "documented rule: critical-arg drift is Foreign"
3939        );
3940        assert!(m.start(&want, Duration::from_secs(1)).is_err());
3941    }
3942
3943    #[test]
3944    fn malformed_registration_is_unknown_and_denies_mutation() {
3945        let mut m = TestDoubleManager::new();
3946        let id = ServiceId::new("svc").unwrap();
3947        m.put_malformed(id.clone());
3948        let want = ServiceSpec::new(id, absolute("/invalid"), vec![], None).unwrap();
3949        assert_eq!(m.inspect(&want).unwrap().ownership, Ownership::Unknown);
3950        assert!(m.stop(&want, Duration::from_secs(1)).is_err());
3951        assert!(m.restart(&want, Duration::from_secs(1)).is_err());
3952    }
3953
3954    #[test]
3955    fn absent_install_then_lifecycle() {
3956        let mut m = TestDoubleManager::new();
3957        let s = spec("svc", "/opt/app/bin", &[]);
3958        assert_eq!(m.inspect(&s).unwrap().ownership, Ownership::Absent);
3959        m.install(&s).unwrap();
3960        assert_eq!(m.inspect(&s).unwrap().ownership, Ownership::Owned);
3961        m.start(&s, Duration::from_secs(1)).unwrap();
3962        m.uninstall(&s).unwrap();
3963        assert_eq!(m.inspect(&s).unwrap().ownership, Ownership::Absent);
3964    }
3965
3966    #[test]
3967    fn stopped_and_running_snapshots_preserve_intent() {
3968        let mut m = TestDoubleManager::new();
3969        let s = spec("svc", "/opt/app/bin", &[]);
3970        m.put(s.clone(), LifecycleState::Stopped);
3971        let stopped = m.inspect(&s).unwrap();
3972        assert!(!stopped.restore_running());
3973        assert!(stopped.was_registered);
3974        m.start(&s, Duration::from_secs(1)).unwrap();
3975        let running = m.inspect(&s).unwrap();
3976        assert!(running.restore_running());
3977        // Stopped stays stopped by default: no auto-start on inspect/install refresh.
3978        m.stop(&s, Duration::from_secs(1)).unwrap();
3979        assert_eq!(m.inspect(&s).unwrap().state, LifecycleState::Stopped);
3980    }
3981
3982    #[test]
3983    fn health_failure_does_not_mutate_manager_state() {
3984        #[derive(Debug)]
3985        struct Fail;
3986        impl HealthProbe for Fail {
3987            fn check(&self, _spec: &ServiceSpec) -> HealthState {
3988                HealthState::Degraded
3989            }
3990        }
3991        let mut m = TestDoubleManager::new();
3992        let s = spec("svc", "/opt/app/bin", &[]);
3993        m.put(s.clone(), LifecycleState::Running);
3994        let probe = Fail;
3995        assert_eq!(probe.check(&s), HealthState::Degraded);
3996        assert_eq!(m.inspect(&s).unwrap().state, LifecycleState::Running);
3997    }
3998
3999    #[test]
4000    fn foreign_and_unknown_destructive_operations_are_denied() {
4001        let mut m = TestDoubleManager::new();
4002        m.put(spec("svc", "/opt/other/bin", &[]), LifecycleState::Running);
4003        let foreign = spec("svc", "/opt/app/bin", &[]);
4004        for op in [
4005            ServiceOperation::Start,
4006            ServiceOperation::Stop,
4007            ServiceOperation::Restart,
4008            ServiceOperation::Uninstall,
4009        ] {
4010            let err = match op {
4011                ServiceOperation::Start => m.start(&foreign, Duration::from_secs(1)).unwrap_err(),
4012                ServiceOperation::Stop => m.stop(&foreign, Duration::from_secs(1)).unwrap_err(),
4013                ServiceOperation::Restart => {
4014                    m.restart(&foreign, Duration::from_secs(1)).unwrap_err()
4015                }
4016                ServiceOperation::Uninstall => m.uninstall(&foreign).unwrap_err(),
4017                _ => continue,
4018            };
4019            assert!(
4020                matches!(err, ServiceError::OwnershipDenied { .. }),
4021                "{op:?}"
4022            );
4023        }
4024        // Install on Foreign is also denied (creation vs replacement are distinct).
4025        assert!(m.install(&foreign).is_err());
4026    }
4027
4028    #[test]
4029    fn manager_state_and_health_are_separate() {
4030        let snap = LifecycleSnapshot {
4031            id: ServiceId::new("svc").unwrap(),
4032            ownership: Ownership::Owned,
4033            state: LifecycleState::Running,
4034            health: HealthState::Degraded,
4035            was_registered: true,
4036            was_running: true,
4037        };
4038        assert_eq!(snap.state, LifecycleState::Running);
4039        assert_eq!(snap.health, HealthState::Degraded);
4040    }
4041
4042    #[test]
4043    fn restore_intent_is_explicit() {
4044        assert_eq!(RestoreIntent::Preserve, RestoreIntent::Preserve);
4045        assert_ne!(RestoreIntent::Preserve, RestoreIntent::EnsureRunning);
4046    }
4047}
4048
4049#[cfg(all(test, unix))]
4050mod unix_tests {
4051    use super::*;
4052    use std::path::PathBuf;
4053
4054    fn spec(id: &str, exe: &str, args: &[&str]) -> ServiceSpec {
4055        ServiceSpec::new(
4056            ServiceId::new(id).unwrap(),
4057            // Callers pass POSIX-looking strings; `absolute` makes them valid on
4058            // Windows too, where a bare "/opt/app/bin" is not absolute.
4059            absolute(exe),
4060            args.iter().map(|s| s.to_string()).collect(),
4061            None,
4062        )
4063        .unwrap()
4064    }
4065
4066    fn temp_dir(prefix: &str) -> PathBuf {
4067        let nanos = std::time::SystemTime::now()
4068            .duration_since(std::time::UNIX_EPOCH)
4069            .map(|d| d.as_nanos())
4070            .unwrap_or(0);
4071        // Include a per-call counter to avoid collisions within one nanos tick.
4072        use std::sync::atomic::{AtomicU64, Ordering};
4073        static N: AtomicU64 = AtomicU64::new(0);
4074        let n = N.fetch_add(1, Ordering::Relaxed);
4075        let p = std::env::temp_dir().join(format!("{prefix}-{}-{nanos}-{n}", std::process::id()));
4076        let _ = std::fs::create_dir_all(&p);
4077        p
4078    }
4079
4080    fn out(status: i32, stdout: &str) -> ManagerCommandOutput {
4081        ManagerCommandOutput {
4082            status: Some(status),
4083            stdout: stdout.as_bytes().to_vec(),
4084            stderr: Vec::new(),
4085        }
4086    }
4087
4088    fn show_loaded_active(exe: &str, args: &str, active: &str) -> String {
4089        format!(
4090            "LoadState=loaded\nActiveState={active}\nExecStart={{ path={exe} ; argv[]={exe} {args} ; ignore_errors=no }}\n"
4091        )
4092    }
4093
4094    // ---- Shared command runner ----
4095
4096    // Unix-only fixture: the program paths are POSIX absolute paths,
4097    // which are not absolute on Windows. The portable counterparts
4098    // live in the crate's integration targets.
4099    #[cfg(unix)]
4100    #[test]
4101    fn command_timeout_kills_and_reaps() {
4102        let ex = SystemExecutor::new();
4103        let start = Instant::now();
4104        let err = ex
4105            .run(
4106                &["/bin/sleep".to_string(), "5".to_string()],
4107                None,
4108                Duration::from_millis(200),
4109            )
4110            .unwrap_err();
4111        assert!(matches!(err, ServiceError::Manager { .. }));
4112        assert_eq!(err.manager_kind(), Some(ManagerFailureKind::Timeout));
4113        assert!(start.elapsed() < Duration::from_secs(4));
4114    }
4115
4116    // Unix-only fixture: the program paths are POSIX absolute paths,
4117    // which are not absolute on Windows. The portable counterparts
4118    // live in the crate's integration targets.
4119    #[cfg(unix)]
4120    #[test]
4121    fn command_output_bound_fails_closed() {
4122        let ex = SystemExecutor::with_max_output(64).unwrap();
4123        // `/bin/echo` with a long argument exceeds the 64-byte bound.
4124        let big = "x".repeat(1024);
4125        let err = ex
4126            .run(
4127                &["/bin/echo".to_string(), big],
4128                None,
4129                Duration::from_secs(5),
4130            )
4131            .unwrap_err();
4132        assert!(matches!(err, ServiceError::Manager { .. }));
4133        assert_eq!(err.manager_kind(), Some(ManagerFailureKind::Protocol));
4134    }
4135
4136    // Unix-only fixture: the program paths are POSIX absolute paths,
4137    // which are not absolute on Windows. The portable counterparts
4138    // live in the crate's integration targets.
4139    #[cfg(unix)]
4140    #[test]
4141    fn command_passes_argv_literally_without_shell() {
4142        let ex = SystemExecutor::new();
4143        // Semicolons, pipes, and dollars must not be interpreted.
4144        let payload = "hello; echo PWNED | cat $HOME `id`";
4145        let output = ex
4146            .run(
4147                &["/bin/echo".to_string(), payload.to_string()],
4148                None,
4149                Duration::from_secs(5),
4150            )
4151            .unwrap();
4152        assert_eq!(output.status, Some(0));
4153        assert_eq!(output.stdout_text().trim(), payload);
4154    }
4155
4156    // Unix-only fixture: the program paths are POSIX absolute paths,
4157    // which are not absolute on Windows. The portable counterparts
4158    // live in the crate's integration targets.
4159    #[cfg(unix)]
4160    #[test]
4161    fn command_nonzero_exit_is_ok_with_status() {
4162        let ex = SystemExecutor::new();
4163        let output = ex
4164            .run(
4165                &[
4166                    "/bin/sh".to_string(),
4167                    "-c".to_string(),
4168                    "exit 3".to_string(),
4169                ],
4170                None,
4171                Duration::from_secs(5),
4172            )
4173            .unwrap();
4174        assert_eq!(output.status, Some(3));
4175    }
4176
4177    // Unix-only fixture: the program paths are POSIX absolute paths,
4178    // which are not absolute on Windows. The portable counterparts
4179    // live in the crate's integration targets.
4180    #[cfg(unix)]
4181    #[test]
4182    fn command_missing_binary_fails_closed() {
4183        let ex = SystemExecutor::new();
4184        let err = ex
4185            .run(
4186                &["/nonexistent-eggup-binary-xyz".to_string()],
4187                None,
4188                Duration::from_secs(5),
4189            )
4190            .unwrap_err();
4191        assert!(matches!(err, ServiceError::Manager { .. }));
4192        assert_eq!(err.manager_kind(), Some(ManagerFailureKind::NotFound));
4193    }
4194
4195    // Unix-only fixture: the program paths are POSIX absolute paths,
4196    // which are not absolute on Windows. The portable counterparts
4197    // live in the crate's integration targets.
4198    #[cfg(unix)]
4199    #[test]
4200    fn command_environment_adds_nothing() {
4201        // The child environment is cleared for a system-scoped command.
4202        let ex = SystemExecutor::new();
4203        let output = ex
4204            .run(&["/usr/bin/env".to_string()], None, Duration::from_secs(5))
4205            .unwrap();
4206        assert_eq!(output.status, Some(0));
4207        assert!(
4208            output.stdout_text().is_empty(),
4209            "system scope starts env-free"
4210        );
4211    }
4212
4213    #[test]
4214    fn manager_resolution_ignores_ambient_path_and_environment_filters_sentinels() {
4215        let dir = temp_dir("manager-path");
4216        let fake = dir.join("systemctl");
4217        std::fs::write(&fake, b"#!/bin/sh\nexit 0\n").unwrap();
4218        #[cfg(unix)]
4219        {
4220            use std::os::unix::fs::PermissionsExt;
4221            std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
4222        }
4223        match resolve_manager_program("systemctl") {
4224            Ok(resolved) => {
4225                assert_ne!(resolved, fake, "ambient PATH candidate must be ignored");
4226                assert!(resolved.is_absolute());
4227            }
4228            Err(ServiceError::Manager { kind, detail, .. }) => {
4229                assert_eq!(kind, ManagerFailureKind::NotFound);
4230                assert!(detail.contains("trusted manager binary missing"));
4231            }
4232            Err(other) => panic!("unexpected resolver error: {other}"),
4233        }
4234
4235        let source = [
4236            ("PATH".into(), "/tmp/attacker".into()),
4237            ("EGGUP_SENTINEL".into(), "secret".into()),
4238            ("LD_PRELOAD".into(), "/tmp/inject.so".into()),
4239            (
4240                "DBUS_SESSION_BUS_ADDRESS".into(),
4241                "unix:path=/run/user/1/bus".into(),
4242            ),
4243            ("XDG_RUNTIME_DIR".into(), "/run/user/1".into()),
4244        ];
4245        let system =
4246            filtered_manager_environment(&["systemctl".into(), "start".into()], source.clone());
4247        assert!(system.is_empty());
4248        let user = filtered_manager_environment(
4249            &["systemctl".into(), "--user".into(), "start".into()],
4250            source,
4251        );
4252        let keys: Vec<_> = user
4253            .iter()
4254            .map(|(key, _)| key.to_string_lossy().into_owned())
4255            .collect();
4256        assert_eq!(keys, ["DBUS_SESSION_BUS_ADDRESS", "XDG_RUNTIME_DIR"]);
4257        let _ = std::fs::remove_dir_all(&dir);
4258    }
4259
4260    /// The user-scoped environment policy is exactly three variables.
4261    ///
4262    /// This is the portable counterpart of the end-to-end environment fixture
4263    /// in the crate's integration targets: the filter itself is a pure
4264    /// function of the argv and the source environment, so it is assertable on
4265    /// every lane, including the one that cannot run a program named
4266    /// `systemctl`.
4267    #[test]
4268    fn the_session_bus_filter_is_exactly_three_variables() {
4269        let source = [
4270            (
4271                "DBUS_SESSION_BUS_ADDRESS".into(),
4272                "unix:path=/run/user/1/bus".into(),
4273            ),
4274            (
4275                "SYSTEMD_BUS_ADDRESS".into(),
4276                "unix:path=/run/user/1/systemd/private".into(),
4277            ),
4278            ("XDG_RUNTIME_DIR".into(), "/run/user/1".into()),
4279            ("PATH".into(), "/usr/bin".into()),
4280            ("EGGUP_EXECUTOR_SENTINEL".into(), "secret".into()),
4281        ];
4282        let user = filtered_manager_environment(
4283            &["systemctl".into(), "--user".into(), "start".into()],
4284            source.clone(),
4285        );
4286        let mut keys: Vec<String> = user
4287            .iter()
4288            .map(|(key, _)| key.to_string_lossy().into_owned())
4289            .collect();
4290        keys.sort();
4291        assert_eq!(
4292            keys,
4293            [
4294                "DBUS_SESSION_BUS_ADDRESS",
4295                "SYSTEMD_BUS_ADDRESS",
4296                "XDG_RUNTIME_DIR"
4297            ]
4298        );
4299        // The value is the caller's own, byte for byte.
4300        assert_eq!(
4301            user.iter()
4302                .find(|(key, _)| key == "XDG_RUNTIME_DIR")
4303                .map(|(_, value)| value.to_string_lossy().into_owned())
4304                .unwrap_or_default(),
4305            "/run/user/1"
4306        );
4307        // Without `--user` nothing is injected at all.
4308        let system =
4309            filtered_manager_environment(&["systemctl".into(), "start".into()], source.clone());
4310        assert!(system.is_empty());
4311        // Only a program named `systemctl` is user-scoped systemd.
4312        let other =
4313            filtered_manager_environment(&["/usr/bin/crontab".into(), "--user".into()], source);
4314        assert!(other.is_empty());
4315    }
4316
4317    #[test]
4318    fn transition_deadline_rejects_zero_and_only_shrinks() {
4319        assert!(OperationDeadline::new(Duration::ZERO).is_err());
4320        assert!(OperationDeadline::new(MAX_TRANSITION_TIMEOUT + Duration::from_secs(1)).is_err());
4321        // Deterministic injected-time proof: no wall-clock sleep, so hosted
4322        // scheduler delays cannot exhaust the deadline mid-assertion.
4323        let start = Instant::now();
4324        let deadline = OperationDeadline::new_at(start, Duration::from_millis(80)).unwrap();
4325        assert_eq!(
4326            deadline.remaining_at(start),
4327            Some(Duration::from_millis(80))
4328        );
4329        assert_eq!(
4330            deadline.command_timeout_at(start).unwrap(),
4331            Duration::from_millis(80)
4332        );
4333        let ten_ms_later = start + Duration::from_millis(10);
4334        assert_eq!(
4335            deadline.remaining_at(ten_ms_later),
4336            Some(Duration::from_millis(70))
4337        );
4338        let second = deadline.command_timeout_at(ten_ms_later).unwrap();
4339        assert!(second < Duration::from_millis(80));
4340        assert_eq!(second, Duration::from_millis(70));
4341        assert_eq!(
4342            deadline.remaining_at(start + Duration::from_millis(79)),
4343            Some(Duration::from_millis(1))
4344        );
4345        assert!(deadline
4346            .command_timeout_at(start + Duration::from_millis(80))
4347            .is_err());
4348        assert!(deadline
4349            .command_timeout_at(start + Duration::from_millis(81))
4350            .is_err());
4351    }
4352
4353    // ---- systemd ----
4354
4355    fn systemd_manager(fake: FakeExecutor, unit_path: PathBuf) -> SystemdManager<FakeExecutor> {
4356        let install = SystemdInstall::new(
4357            "my-daemon.service".to_string(),
4358            SystemdScope::User,
4359            unit_path,
4360            b"[Unit]\nDescription=test\n[Service]\nExecStart=/opt/app/bin --serve\n".to_vec(),
4361            false,
4362            false,
4363            Duration::from_secs(5),
4364        )
4365        .unwrap();
4366        SystemdManager::new(fake, install)
4367    }
4368
4369    #[test]
4370    fn systemd_absent_allows_install() {
4371        let fake = FakeExecutor::new();
4372        for _ in 0..2 {
4373            fake.expect(
4374                &[
4375                    "systemctl",
4376                    "--user",
4377                    "show",
4378                    "my-daemon.service",
4379                    "-p",
4380                    "LoadState,ActiveState,ExecStart",
4381                ],
4382                out(0, "LoadState=not-found\nActiveState=inactive\n"),
4383            );
4384        }
4385        let dir = temp_dir("sysd-absent");
4386        let unit = dir.join("my-daemon.service");
4387        let mut m = systemd_manager(fake, unit.clone());
4388        let s = spec("my-daemon.service", "/opt/app/bin", &["--serve"]);
4389        assert_eq!(m.inspect(&s).unwrap().ownership, Ownership::Absent);
4390        // Install writes the definition file (no reload/enable in this config).
4391        m.install(&s).unwrap();
4392        assert!(unit.exists());
4393        let _ = std::fs::remove_dir_all(&dir);
4394    }
4395
4396    #[test]
4397    fn systemd_exact_owned() {
4398        let fake = FakeExecutor::new();
4399        let show = show_loaded_active("/opt/app/bin", "--serve", "inactive");
4400        fake.expect(
4401            &[
4402                "systemctl",
4403                "--user",
4404                "show",
4405                "my-daemon.service",
4406                "-p",
4407                "LoadState,ActiveState,ExecStart",
4408            ],
4409            out(0, &show),
4410        );
4411        let dir = temp_dir("sysd-owned");
4412        let m = systemd_manager(fake, dir.join("my-daemon.service"));
4413        let s = spec("my-daemon.service", "/opt/app/bin", &["--serve"]);
4414        let snap = m.inspect(&s).unwrap();
4415        assert_eq!(snap.ownership, Ownership::Owned);
4416        assert_eq!(snap.state, LifecycleState::Stopped);
4417        let _ = std::fs::remove_dir_all(&dir);
4418    }
4419
4420    #[test]
4421    fn systemd_same_unit_different_executable_is_foreign() {
4422        let fake = FakeExecutor::new();
4423        let show = show_loaded_active("/opt/other/bin", "--serve", "active");
4424        fake.expect(
4425            &[
4426                "systemctl",
4427                "--user",
4428                "show",
4429                "my-daemon.service",
4430                "-p",
4431                "LoadState,ActiveState,ExecStart",
4432            ],
4433            out(0, &show),
4434        );
4435        // Second show for the destructive denial path.
4436        fake.expect(
4437            &[
4438                "systemctl",
4439                "--user",
4440                "show",
4441                "my-daemon.service",
4442                "-p",
4443                "LoadState,ActiveState,ExecStart",
4444            ],
4445            out(0, &show),
4446        );
4447        let dir = temp_dir("sysd-foreign");
4448        let mut m = systemd_manager(fake, dir.join("my-daemon.service"));
4449        let want = spec("my-daemon.service", "/opt/app/bin", &["--serve"]);
4450        assert_eq!(m.inspect(&want).unwrap().ownership, Ownership::Foreign);
4451        assert!(m.stop(&want, Duration::from_secs(1)).is_err());
4452        assert!(m.uninstall(&want).is_err());
4453        let _ = std::fs::remove_dir_all(&dir);
4454    }
4455
4456    #[test]
4457    fn systemd_argv_drift_is_foreign() {
4458        let fake = FakeExecutor::new();
4459        let show = show_loaded_active("/opt/app/bin", "--serve --port=1", "inactive");
4460        for _ in 0..2 {
4461            fake.expect(
4462                &[
4463                    "systemctl",
4464                    "--user",
4465                    "show",
4466                    "my-daemon.service",
4467                    "-p",
4468                    "LoadState,ActiveState,ExecStart",
4469                ],
4470                out(0, &show),
4471            );
4472        }
4473        let dir = temp_dir("sysd-drift");
4474        let mut m = systemd_manager(fake, dir.join("my-daemon.service"));
4475        let want = spec(
4476            "my-daemon.service",
4477            "/opt/app/bin",
4478            &["--serve", "--port=2"],
4479        );
4480        assert_eq!(m.inspect(&want).unwrap().ownership, Ownership::Foreign);
4481        assert!(m.start(&want, Duration::from_secs(1)).is_err());
4482        let _ = std::fs::remove_dir_all(&dir);
4483    }
4484
4485    #[test]
4486    fn systemd_ambiguous_execstart_is_unknown() {
4487        let fake = FakeExecutor::new();
4488        // Two ExecStart blocks: ambiguous.
4489        let show = "LoadState=loaded\nActiveState=active\nExecStart={ path=/a ; argv[]=/a ; ignore_errors=no }\nExecStart={ path=/b ; argv[]=/b ; ignore_errors=no }\n";
4490        for _ in 0..3 {
4491            fake.expect(
4492                &[
4493                    "systemctl",
4494                    "--user",
4495                    "show",
4496                    "my-daemon.service",
4497                    "-p",
4498                    "LoadState,ActiveState,ExecStart",
4499                ],
4500                out(0, show),
4501            );
4502        }
4503        let dir = temp_dir("sysd-ambig");
4504        let mut m = systemd_manager(fake, dir.join("my-daemon.service"));
4505        let s = spec("my-daemon.service", "/opt/app/bin", &[]);
4506        assert_eq!(m.inspect(&s).unwrap().ownership, Ownership::Unknown);
4507        assert!(m.start(&s, Duration::from_secs(1)).is_err());
4508        assert!(m.uninstall(&s).is_err());
4509        // Specifiers also yield Unknown, not Owned.
4510        let _ = std::fs::remove_dir_all(&dir);
4511    }
4512
4513    #[test]
4514    fn systemd_specifier_execstart_is_unknown() {
4515        let text = "LoadState=loaded\nActiveState=active\nExecStart={ path=/opt/app/bin ; argv[]=/opt/app/bin %n ; ignore_errors=no }\n";
4516        let s = spec("my-daemon.service", "/opt/app/bin", &["%n"]);
4517        let (ownership, _, _) = systemd_ownership(text, &s).unwrap();
4518        assert_eq!(ownership, Ownership::Unknown);
4519    }
4520
4521    #[test]
4522    fn systemd_config_identity_requires_one_exact_argv_match() {
4523        let with_config = ServiceSpec::new(
4524            ServiceId::new("my-daemon.service").unwrap(),
4525            absolute("/opt/app/bin"),
4526            vec!["--config".into(), "/etc/app.toml".into()],
4527            Some(absolute("/etc/app.toml")),
4528        )
4529        .unwrap();
4530        let exact = "LoadState=loaded\nActiveState=inactive\nExecStart={ path=/opt/app/bin ; argv[]=/opt/app/bin --config /etc/app.toml ; ignore_errors=no }\n";
4531        assert_eq!(
4532            systemd_ownership(exact, &with_config).unwrap().0,
4533            Ownership::Owned
4534        );
4535        let absent = "LoadState=loaded\nActiveState=inactive\nExecStart={ path=/opt/app/bin ; argv[]=/opt/app/bin --serve ; ignore_errors=no }\n";
4536        assert_eq!(
4537            systemd_ownership(absent, &with_config).unwrap().0,
4538            Ownership::Foreign
4539        );
4540        let ambiguous = "LoadState=loaded\nActiveState=inactive\nExecStart={ path=/opt/app/bin ; argv[]=/opt/app/bin /etc/app.toml /etc/app.toml ; ignore_errors=no }\n";
4541        assert_eq!(
4542            systemd_ownership(ambiguous, &with_config).unwrap().0,
4543            Ownership::Unknown
4544        );
4545    }
4546
4547    #[test]
4548    fn systemd_active_stopped_transitioning_mapped() {
4549        for (active, expect) in [
4550            ("active", LifecycleState::Running),
4551            ("inactive", LifecycleState::Stopped),
4552            ("activating", LifecycleState::Transitioning),
4553            ("deactivating", LifecycleState::Transitioning),
4554            ("failed", LifecycleState::Unknown),
4555        ] {
4556            let text = show_loaded_active("/opt/app/bin", "--serve", active);
4557            let s = spec("my-daemon.service", "/opt/app/bin", &["--serve"]);
4558            let (_, state, _) = systemd_ownership(&text, &s).unwrap();
4559            assert_eq!(state, expect, "{active}");
4560        }
4561    }
4562
4563    fn quiescence_show(active: &str, control_group: &str, main_pid: u32, job: &str) -> String {
4564        format!(
4565            "LoadState=loaded\nActiveState={active}\nSubState={}\nExecStart={{ path=/opt/app/bin ; argv[]=/opt/app/bin --serve ; ignore_errors=no }}\nMainPID={main_pid}\nControlPID=0\nControlGroup={control_group}\nJob={job}\n",
4566            if active == "failed" { "failed" } else { "dead" }
4567        )
4568    }
4569
4570    #[test]
4571    fn systemd_failed_stop_requires_proven_quiescence_and_revalidates_ownership() {
4572        let fake = FakeExecutor::new();
4573        let failed_state = show_loaded_active("/opt/app/bin", "--serve", "failed");
4574        for _ in 0..1 {
4575            fake.expect(
4576                &[
4577                    "systemctl",
4578                    "--user",
4579                    "show",
4580                    "my-daemon.service",
4581                    "-p",
4582                    "LoadState,ActiveState,ExecStart",
4583                ],
4584                out(0, &failed_state),
4585            );
4586        }
4587        let extended_argv = [
4588            "systemctl",
4589            "--user",
4590            "show",
4591            "my-daemon.service",
4592            "-p",
4593            "LoadState,ActiveState,SubState,ExecStart,MainPID,ControlPID,ControlGroup,Job",
4594        ];
4595        fake.expect(
4596            &extended_argv,
4597            out(0, &quiescence_show("failed", "", 0, "")),
4598        );
4599        fake.expect(
4600            &["systemctl", "--user", "stop", "my-daemon.service"],
4601            out(0, ""),
4602        );
4603        fake.expect(
4604            &extended_argv,
4605            out(0, &quiescence_show("failed", "", 0, "")),
4606        );
4607        fake.expect(
4608            &extended_argv,
4609            out(0, &quiescence_show("failed", "", 0, "")),
4610        );
4611        fake.expect(
4612            &["systemctl", "--user", "is-active", "my-daemon.service"],
4613            out(3, "failed\n"),
4614        );
4615        let dir = temp_dir("sysd-failed-stop");
4616        let mut manager = systemd_manager(fake, dir.join("my-daemon.service"));
4617        let want = spec("my-daemon.service", "/opt/app/bin", &["--serve"]);
4618        let result = manager.stop(&want, Duration::from_secs(2)).unwrap();
4619        assert!(result.completed, "{result:?}");
4620        assert_eq!(result.detail, "owned failed unit is quiescent");
4621        assert!(manager.executor().is_exhausted());
4622        let _ = std::fs::remove_dir_all(&dir);
4623    }
4624
4625    #[test]
4626    fn systemd_failed_stop_refuses_changed_identity_or_unknown_state() {
4627        let old_owned = show_loaded_active("/opt/app/bin", "--serve", "failed");
4628        let extended_argv = [
4629            "systemctl",
4630            "--user",
4631            "show",
4632            "my-daemon.service",
4633            "-p",
4634            "LoadState,ActiveState,SubState,ExecStart,MainPID,ControlPID,ControlGroup,Job",
4635        ];
4636
4637        let fake = FakeExecutor::new();
4638        fake.expect(
4639            &[
4640                "systemctl",
4641                "--user",
4642                "show",
4643                "my-daemon.service",
4644                "-p",
4645                "LoadState,ActiveState,ExecStart",
4646            ],
4647            out(0, &old_owned),
4648        );
4649        fake.expect(
4650            &extended_argv,
4651            out(0, &quiescence_show("failed", "", 0, "")),
4652        );
4653        fake.expect(
4654            &["systemctl", "--user", "stop", "my-daemon.service"],
4655            out(0, ""),
4656        );
4657        fake.expect(
4658            &extended_argv,
4659            out(
4660                0,
4661                "LoadState=loaded\nActiveState=failed\nSubState=failed\nExecStart={ path=/opt/other/bin ; argv[]=/opt/other/bin --serve ; ignore_errors=no }\nMainPID=0\nControlPID=0\nControlGroup=\nJob=\n",
4662            ),
4663        );
4664        let dir = temp_dir("sysd-failed-drift");
4665        let mut manager = systemd_manager(fake, dir.join("my-daemon.service"));
4666        let want = spec("my-daemon.service", "/opt/app/bin", &["--serve"]);
4667        let result = manager.stop(&want, Duration::from_secs(2)).unwrap();
4668        assert!(!result.completed, "{result:?}");
4669        assert!(result.detail.contains("ownership"));
4670        assert!(manager.executor().is_exhausted());
4671        let _ = std::fs::remove_dir_all(&dir);
4672
4673        let fake = FakeExecutor::new();
4674        fake.expect(
4675            &[
4676                "systemctl",
4677                "--user",
4678                "show",
4679                "my-daemon.service",
4680                "-p",
4681                "LoadState,ActiveState,ExecStart",
4682            ],
4683            out(0, &old_owned),
4684        );
4685        fake.expect(
4686            &extended_argv,
4687            out(0, &quiescence_show("maintenance", "", 0, "")),
4688        );
4689        let dir = temp_dir("sysd-failed-unknown");
4690        let mut manager = systemd_manager(fake, dir.join("my-daemon.service"));
4691        let result = manager.stop(&want, Duration::from_secs(2)).unwrap();
4692        assert!(!result.completed, "{result:?}");
4693        assert!(result.detail.contains("changed before stop"));
4694        assert!(manager.executor().is_exhausted());
4695        let _ = std::fs::remove_dir_all(&dir);
4696    }
4697
4698    #[test]
4699    fn systemd_failed_stop_fails_closed_on_restart_race_or_conflicting_active_state() {
4700        let old_owned = show_loaded_active("/opt/app/bin", "--serve", "failed");
4701        let ownership_argv = [
4702            "systemctl",
4703            "--user",
4704            "show",
4705            "my-daemon.service",
4706            "-p",
4707            "LoadState,ActiveState,ExecStart",
4708        ];
4709        let extended_argv = [
4710            "systemctl",
4711            "--user",
4712            "show",
4713            "my-daemon.service",
4714            "-p",
4715            "LoadState,ActiveState,SubState,ExecStart,MainPID,ControlPID,ControlGroup,Job",
4716        ];
4717        let stop_argv = ["systemctl", "--user", "stop", "my-daemon.service"];
4718        let want = spec("my-daemon.service", "/opt/app/bin", &["--serve"]);
4719
4720        let fake = FakeExecutor::new();
4721        fake.expect(&ownership_argv, out(0, &old_owned));
4722        fake.expect(
4723            &extended_argv,
4724            out(0, &quiescence_show("failed", "", 0, "")),
4725        );
4726        fake.expect(&stop_argv, out(0, ""));
4727        fake.expect(
4728            &extended_argv,
4729            out(0, &quiescence_show("activating", "", 0, "")),
4730        );
4731        let dir = temp_dir("sysd-failed-restart-race");
4732        let mut manager = systemd_manager(fake, dir.join("my-daemon.service"));
4733        let result = manager.stop(&want, Duration::from_secs(2)).unwrap();
4734        assert!(!result.completed, "{result:?}");
4735        assert!(result.detail.contains("became active or transitioning"));
4736        assert!(manager.executor().is_exhausted());
4737        let _ = std::fs::remove_dir_all(&dir);
4738
4739        let fake = FakeExecutor::new();
4740        fake.expect(&ownership_argv, out(0, &old_owned));
4741        fake.expect(
4742            &extended_argv,
4743            out(0, &quiescence_show("failed", "", 0, "")),
4744        );
4745        fake.expect(&stop_argv, out(0, ""));
4746        fake.expect(
4747            &extended_argv,
4748            out(0, &quiescence_show("failed", "", 0, "")),
4749        );
4750        fake.expect(
4751            &extended_argv,
4752            out(0, &quiescence_show("failed", "", 0, "")),
4753        );
4754        fake.expect(
4755            &["systemctl", "--user", "is-active", "my-daemon.service"],
4756            out(0, "active\n"),
4757        );
4758        let dir = temp_dir("sysd-failed-inconsistent-state");
4759        let mut manager = systemd_manager(fake, dir.join("my-daemon.service"));
4760        let result = manager.stop(&want, Duration::from_secs(2)).unwrap();
4761        assert!(!result.completed, "{result:?}");
4762        assert!(result.detail.contains("observations disagree"));
4763        assert!(manager.executor().is_exhausted());
4764        let _ = std::fs::remove_dir_all(&dir);
4765    }
4766
4767    #[test]
4768    fn systemd_cgroup_quiescence_checks_processes_events_and_path_safety() {
4769        let root = temp_dir("sysd-cgroup-proof");
4770        let group = root.join("system.slice").join("owned.service");
4771        std::fs::create_dir_all(&group).unwrap();
4772        std::fs::write(group.join("cgroup.procs"), b"").unwrap();
4773        std::fs::write(group.join("cgroup.events"), b"populated 0\nfrozen 0\n").unwrap();
4774        let mut observation = SystemdQuiescenceObservation {
4775            ownership: Ownership::Owned,
4776            active_state: "failed".to_string(),
4777            sub_state: "failed".to_string(),
4778            main_pid: 0,
4779            control_pid: 0,
4780            control_group: "/system.slice/owned.service".to_string(),
4781            job: String::new(),
4782        };
4783        assert!(quiescence_proven(&observation, &root));
4784        observation.control_group = "/system.slice/removed.service".to_string();
4785        assert!(quiescence_proven(&observation, &root));
4786        observation.control_group = "/system.slice/owned.service".to_string();
4787        std::fs::write(group.join("cgroup.procs"), b"123\n").unwrap();
4788        assert!(!quiescence_proven(&observation, &root));
4789        std::fs::write(group.join("cgroup.procs"), b"").unwrap();
4790        std::fs::write(group.join("cgroup.events"), b"populated 1\nfrozen 0\n").unwrap();
4791        assert!(!quiescence_proven(&observation, &root));
4792        observation.control_group = "/system.slice/../foreign.service".to_string();
4793        assert!(!quiescence_proven(&observation, &root));
4794        let _ = std::fs::remove_dir_all(&root);
4795    }
4796
4797    #[test]
4798    fn systemd_permission_denial_has_no_sudo() {
4799        let fake = FakeExecutor::new();
4800        let show = show_loaded_active("/opt/app/bin", "--serve", "inactive");
4801        fake.expect(
4802            &[
4803                "systemctl",
4804                "--user",
4805                "show",
4806                "my-daemon.service",
4807                "-p",
4808                "LoadState,ActiveState,ExecStart",
4809            ],
4810            out(0, &show),
4811        );
4812        fake.expect_error(
4813            &["systemctl", "--user", "start", "my-daemon.service"],
4814            ServiceError::manager(ManagerFailureKind::Permission, "permission denied for unit"),
4815        );
4816        let dir = temp_dir("sysd-perm");
4817        let mut m = systemd_manager(fake, dir.join("my-daemon.service"));
4818        let s = spec("my-daemon.service", "/opt/app/bin", &["--serve"]);
4819        let err = m.start(&s, Duration::from_secs(2)).unwrap_err();
4820        assert_eq!(err.manager_kind(), Some(ManagerFailureKind::Permission));
4821        let err = err.to_string();
4822        assert!(!err.to_lowercase().contains("sudo"));
4823        let _ = std::fs::remove_dir_all(&dir);
4824    }
4825
4826    #[test]
4827    fn systemd_atomic_write_fault_preserves_old() {
4828        // Parent is a file, not a directory: write fails without creating.
4829        let dir = temp_dir("sysd-fault");
4830        let notdir = dir.join("notdir");
4831        std::fs::write(&notdir, b"x").unwrap();
4832        let err = atomic_write_definition(&notdir.join("u.service"), b"data", false).unwrap_err();
4833        assert!(matches!(
4834            err,
4835            ServiceError::InvalidInput(_) | ServiceError::Manager { .. }
4836        ));
4837        let _ = std::fs::remove_dir_all(&dir);
4838    }
4839
4840    #[test]
4841    fn systemd_start_stop_restart_confirm_state() {
4842        let fake = FakeExecutor::new();
4843        let stopped = show_loaded_active("/opt/app/bin", "--serve", "inactive");
4844        let running = show_loaded_active("/opt/app/bin", "--serve", "active");
4845        // inspect → stopped
4846        fake.expect(
4847            &[
4848                "systemctl",
4849                "--user",
4850                "show",
4851                "my-daemon.service",
4852                "-p",
4853                "LoadState,ActiveState,ExecStart",
4854            ],
4855            out(0, &stopped),
4856        );
4857        // start
4858        fake.expect(
4859            &["systemctl", "--user", "start", "my-daemon.service"],
4860            out(0, ""),
4861        );
4862        // poll is-active → active
4863        fake.expect(
4864            &["systemctl", "--user", "is-active", "my-daemon.service"],
4865            out(0, "active\n"),
4866        );
4867        // stop: show → running
4868        fake.expect(
4869            &[
4870                "systemctl",
4871                "--user",
4872                "show",
4873                "my-daemon.service",
4874                "-p",
4875                "LoadState,ActiveState,ExecStart",
4876            ],
4877            out(0, &running),
4878        );
4879        fake.expect(
4880            &["systemctl", "--user", "stop", "my-daemon.service"],
4881            out(0, ""),
4882        );
4883        fake.expect(
4884            &["systemctl", "--user", "is-active", "my-daemon.service"],
4885            out(3, "inactive\n"),
4886        );
4887        // restart: show → stopped (owned), restart, poll active
4888        fake.expect(
4889            &[
4890                "systemctl",
4891                "--user",
4892                "show",
4893                "my-daemon.service",
4894                "-p",
4895                "LoadState,ActiveState,ExecStart",
4896            ],
4897            out(0, &stopped),
4898        );
4899        fake.expect(
4900            &["systemctl", "--user", "restart", "my-daemon.service"],
4901            out(0, ""),
4902        );
4903        fake.expect(
4904            &["systemctl", "--user", "is-active", "my-daemon.service"],
4905            out(0, "active\n"),
4906        );
4907        let dir = temp_dir("sysd-trans");
4908        let mut m = systemd_manager(fake, dir.join("my-daemon.service"));
4909        let s = spec("my-daemon.service", "/opt/app/bin", &["--serve"]);
4910        assert!(m.start(&s, Duration::from_secs(5)).unwrap().completed);
4911        assert!(m.stop(&s, Duration::from_secs(5)).unwrap().completed);
4912        assert!(m.restart(&s, Duration::from_secs(5)).unwrap().completed);
4913        assert!(m.executor().is_exhausted());
4914        let _ = std::fs::remove_dir_all(&dir);
4915    }
4916
4917    // ---- launchd ----
4918
4919    fn plist(exe: &str, args: &[&str]) -> Vec<u8> {
4920        let mut strings = format!("    <string>{exe}</string>\n");
4921        for a in args {
4922            strings.push_str(&format!("    <string>{a}</string>\n"));
4923        }
4924        format!(
4925            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<plist version=\"1.0\">\n<dict>\n  <key>Label</key>\n  <string>com.example.daemon</string>\n  <key>ProgramArguments</key>\n  <array>\n{strings}  </array>\n</dict>\n</plist>\n"
4926        )
4927        .into_bytes()
4928    }
4929
4930    fn launchd_manager(fake: FakeExecutor, plist_path: PathBuf) -> LaunchdManager<FakeExecutor> {
4931        let install = LaunchdInstall::new(
4932            "com.example.daemon".to_string(),
4933            LaunchdDomain::UserAgent,
4934            "gui/501".to_string(),
4935            plist_path,
4936            plist("/opt/app/bin", &["--serve"]),
4937            false,
4938            Duration::from_secs(5),
4939        )
4940        .unwrap();
4941        LaunchdManager::new(fake, install)
4942    }
4943
4944    #[test]
4945    fn launchd_absent_exact_foreign_unknown() {
4946        // Absent: no plist file, list fails.
4947        let fake = FakeExecutor::new();
4948        fake.expect(&["launchctl", "list", "com.example.daemon"], out(1, ""));
4949        let dir = temp_dir("ld-absent");
4950        let m = launchd_manager(fake, dir.join("com.example.daemon.plist"));
4951        let s = spec("com.example.daemon", "/opt/app/bin", &["--serve"]);
4952        assert_eq!(m.inspect(&s).unwrap().ownership, Ownership::Absent);
4953
4954        // Exact: plist matches, loaded with PID → Owned + Running.
4955        let fake = FakeExecutor::new();
4956        fake.expect(
4957            &["launchctl", "list", "com.example.daemon"],
4958            out(0, "\"PID\" = 123;\n"),
4959        );
4960        let dir = temp_dir("ld-exact");
4961        let plist_path = dir.join("com.example.daemon.plist");
4962        std::fs::write(&plist_path, plist("/opt/app/bin", &["--serve"])).unwrap();
4963        let m = launchd_manager(fake, plist_path);
4964        let snap = m.inspect(&s).unwrap();
4965        assert_eq!(snap.ownership, Ownership::Owned);
4966        assert_eq!(snap.state, LifecycleState::Running);
4967
4968        // Foreign: same label, different program.
4969        let fake = FakeExecutor::new();
4970        let dir = temp_dir("ld-foreign");
4971        let plist_path = dir.join("com.example.daemon.plist");
4972        std::fs::write(&plist_path, plist("/opt/other/bin", &["--serve"])).unwrap();
4973        let m = launchd_manager(fake, plist_path);
4974        assert_eq!(m.inspect(&s).unwrap().ownership, Ownership::Foreign);
4975
4976        // Unknown: malformed plist.
4977        let fake = FakeExecutor::new();
4978        let dir = temp_dir("ld-unknown");
4979        let plist_path = dir.join("com.example.daemon.plist");
4980        std::fs::write(&plist_path, b"<plist><dict><key>Label</key></dict>").unwrap();
4981        let m = launchd_manager(fake, plist_path);
4982        assert_eq!(m.inspect(&s).unwrap().ownership, Ownership::Unknown);
4983    }
4984
4985    #[test]
4986    fn launchd_user_vs_system_domain_distinct() {
4987        let user = LaunchdInstall::new(
4988            "com.example.daemon".to_string(),
4989            LaunchdDomain::UserAgent,
4990            "gui/501".to_string(),
4991            absolute("/tmp/com.example.daemon.plist"),
4992            plist("/opt/app/bin", &[]),
4993            false,
4994            Duration::from_secs(5),
4995        )
4996        .unwrap();
4997        let system = LaunchdInstall::new(
4998            "com.example.daemon".to_string(),
4999            LaunchdDomain::SystemDaemon,
5000            "system".to_string(),
5001            absolute("/Library/LaunchDaemons/com.example.daemon.plist"),
5002            plist("/opt/app/bin", &[]),
5003            false,
5004            Duration::from_secs(5),
5005        )
5006        .unwrap();
5007        assert_ne!(user.target, system.target);
5008        // Wrong target for domain is rejected (no silent domain choice).
5009        assert!(LaunchdInstall::new(
5010            "com.example.daemon".to_string(),
5011            LaunchdDomain::UserAgent,
5012            "system".to_string(),
5013            absolute("/tmp/x.plist"),
5014            plist("/opt/app/bin", &[]),
5015            false,
5016            Duration::from_secs(5),
5017        )
5018        .is_err());
5019    }
5020
5021    #[test]
5022    fn launchd_malformed_plist_is_unknown_and_denies_mutation() {
5023        let fake = FakeExecutor::new();
5024        let dir = temp_dir("ld-malformed");
5025        let plist_path = dir.join("com.example.daemon.plist");
5026        std::fs::write(&plist_path, b"not xml at all").unwrap();
5027        let mut m = launchd_manager(fake, plist_path);
5028        let s = spec("com.example.daemon", "/opt/app/bin", &["--serve"]);
5029        assert_eq!(m.inspect(&s).unwrap().ownership, Ownership::Unknown);
5030        assert!(m.stop(&s, Duration::from_secs(1)).is_err());
5031        assert!(m.uninstall(&s).is_err());
5032    }
5033
5034    #[test]
5035    fn launchd_bootstrap_bootout_kickstart_flow() {
5036        let fake = FakeExecutor::new();
5037        // inspect for start: plist owned, list → loaded but stopped (no PID).
5038        // ownership_of calls loaded_and_running once.
5039        // start calls ownership_of (list #1), then kickstart, then confirm (list #2).
5040        // Use a plist file so ownership is Owned.
5041        // Sequence: list(stopped) [ownership in start], kickstart, list(running) [confirm].
5042        // Note: start's ownership_of does one list; confirm does another.
5043        fake.expect(
5044            &["launchctl", "list", "com.example.daemon"],
5045            out(0, "\"PID\" = -;\n"),
5046        );
5047        fake.expect(
5048            &["launchctl", "kickstart", "-k", "gui/501/com.example.daemon"],
5049            out(0, ""),
5050        );
5051        fake.expect(
5052            &["launchctl", "list", "com.example.daemon"],
5053            out(0, "\"PID\" = 42;\n"),
5054        );
5055        let dir = temp_dir("ld-flow");
5056        let plist_path = dir.join("com.example.daemon.plist");
5057        std::fs::write(&plist_path, plist("/opt/app/bin", &["--serve"])).unwrap();
5058        let mut m = launchd_manager(fake, plist_path);
5059        let s = spec("com.example.daemon", "/opt/app/bin", &["--serve"]);
5060        let r = m.start(&s, Duration::from_secs(5)).unwrap();
5061        assert!(r.completed);
5062        assert!(m.executor().is_exhausted());
5063        let _ = std::fs::remove_dir_all(&dir);
5064    }
5065
5066    #[test]
5067    fn launchd_restart_does_not_start_after_incomplete_stop() {
5068        #[derive(Debug, Default)]
5069        struct StaysRunning {
5070            calls: std::sync::Arc<Mutex<Vec<Vec<String>>>>,
5071        }
5072        impl CommandExecutor for StaysRunning {
5073            fn run(
5074                &self,
5075                argv: &[String],
5076                _stdin: Option<&[u8]>,
5077                timeout: Duration,
5078            ) -> Result<ManagerCommandOutput, ServiceError> {
5079                self.calls.lock().unwrap().push(argv.to_vec());
5080                if argv.first().is_some_and(|arg| arg == "launchctl")
5081                    && argv.get(1).is_some_and(|arg| arg == "list")
5082                {
5083                    std::thread::sleep(Duration::from_millis(2).min(timeout));
5084                    return Ok(out(0, "\"PID\" = 42;\n"));
5085                }
5086                if argv.get(1).is_some_and(|arg| arg == "stop") {
5087                    return Ok(out(0, ""));
5088                }
5089                Err(ServiceError::manager(
5090                    ManagerFailureKind::Protocol,
5091                    "unexpected launchctl command",
5092                ))
5093            }
5094        }
5095
5096        let executor = StaysRunning::default();
5097        let observed_calls = executor.calls.clone();
5098        let dir = temp_dir("ld-restart-incomplete");
5099        let plist_path = dir.join("com.example.daemon.plist");
5100        std::fs::write(&plist_path, plist("/opt/app/bin", &["--serve"])).unwrap();
5101        let install = LaunchdInstall::new(
5102            "com.example.daemon".into(),
5103            LaunchdDomain::UserAgent,
5104            "gui/501".into(),
5105            plist_path,
5106            plist("/opt/app/bin", &["--serve"]),
5107            false,
5108            Duration::from_secs(1),
5109        )
5110        .unwrap();
5111        let mut manager = LaunchdManager::new(executor, install);
5112        let service = spec("com.example.daemon", "/opt/app/bin", &["--serve"]);
5113        let started_at = Instant::now();
5114        let result = manager.restart(&service, Duration::from_millis(35));
5115        assert!(match result {
5116            Ok(result) => !result.completed,
5117            Err(e) => e.manager_kind() == Some(ManagerFailureKind::Timeout),
5118        });
5119        assert!(started_at.elapsed() < Duration::from_millis(150));
5120        let calls = observed_calls.lock().unwrap();
5121        assert!(calls
5122            .iter()
5123            .any(|argv| argv.get(1).is_some_and(|arg| arg == "stop")));
5124        assert!(!calls.iter().any(|argv| {
5125            argv.get(1)
5126                .is_some_and(|arg| arg == "bootstrap" || arg == "kickstart")
5127        }));
5128        let _ = std::fs::remove_dir_all(&dir);
5129    }
5130
5131    #[test]
5132    fn launchd_no_label_only_ownership() {
5133        // Even when `launchctl list` reports loaded, a missing plist file is
5134        // Absent (label alone never proves ownership).
5135        let fake = FakeExecutor::new();
5136        fake.expect(
5137            &["launchctl", "list", "com.example.daemon"],
5138            out(0, "\"PID\" = 1;\n"),
5139        );
5140        let dir = temp_dir("ld-nolabel");
5141        let m = launchd_manager(fake, dir.join("missing.plist"));
5142        let s = spec("com.example.daemon", "/opt/app/bin", &[]);
5143        // No file → Absent, regardless of list output (file gates ownership).
5144        assert_eq!(m.inspect(&s).unwrap().ownership, Ownership::Absent);
5145    }
5146
5147    #[test]
5148    fn launchd_config_identity_reconciles_exact_missing_and_ambiguous_argv() {
5149        let service = ServiceSpec::new(
5150            ServiceId::new("com.example.daemon").unwrap(),
5151            absolute("/opt/app/bin"),
5152            vec!["--settings".into(), "/etc/app.toml".into()],
5153            Some(absolute("/etc/app.toml")),
5154        )
5155        .unwrap();
5156        let observed = |args: &[&str]| {
5157            reconcile_config_identity(
5158                RegistrationSnapshot {
5159                    present: true,
5160                    executable: Some(absolute("/opt/app/bin")),
5161                    args: args.iter().map(|arg| (*arg).to_string()).collect(),
5162                    config: None,
5163                    malformed: false,
5164                },
5165                &service,
5166            )
5167            .ownership(&service)
5168        };
5169        assert_eq!(observed(&["--settings", "/etc/app.toml"]), Ownership::Owned);
5170        assert_eq!(observed(&["--serve"]), Ownership::Foreign);
5171        assert_eq!(
5172            observed(&["/etc/app.toml", "/etc/app.toml"]),
5173            Ownership::Unknown
5174        );
5175    }
5176
5177    #[test]
5178    fn mutation_status_requires_zero_exit() {
5179        assert!(ensure_mutation_success(&out(0, ""), "mutation").is_ok());
5180        let err = ensure_mutation_success(&out(7, ""), "mutation").unwrap_err();
5181        assert!(matches!(err, ServiceError::Manager { .. }));
5182        assert!(err.to_string().contains("exited 7"));
5183    }
5184
5185    // ---- cron ----
5186
5187    const MARKER: &str = "eggup-test-block-001";
5188    const DESIRED: &str = "*/5 * * * * /opt/app/bin --serve";
5189
5190    #[test]
5191    fn cron_empty_absent_then_install() {
5192        assert_eq!(cron_classify("", MARKER, DESIRED), CronOwnership::Absent);
5193        let (merged, changed) = cron_merge("", MARKER, DESIRED).unwrap();
5194        assert!(changed);
5195        assert!(merged.contains("# BEGIN eggup-test-block-001"));
5196        assert!(merged.contains(DESIRED));
5197        assert_eq!(
5198            cron_classify(&merged, MARKER, DESIRED),
5199            CronOwnership::Owned
5200        );
5201    }
5202
5203    #[test]
5204    fn cron_preserves_unrelated_entries_byte_for_byte() {
5205        let existing = "# mypersonal\n0 0 * * * /usr/bin/backup\n";
5206        let (merged, _) = cron_merge(existing, MARKER, DESIRED).unwrap();
5207        assert!(merged.starts_with(existing));
5208        assert!(merged.contains(DESIRED));
5209        // Removing restores the exact original bytes.
5210        let (removed, _) = cron_remove(&merged, MARKER, DESIRED).unwrap();
5211        assert_eq!(removed, existing);
5212    }
5213
5214    #[test]
5215    fn cron_exact_block_is_idempotent() {
5216        let (merged, _) = cron_merge("", MARKER, DESIRED).unwrap();
5217        let (merged2, changed) = cron_merge(&merged, MARKER, DESIRED).unwrap();
5218        assert!(!changed);
5219        assert_eq!(merged, merged2);
5220    }
5221
5222    #[test]
5223    fn cron_duplicate_marker_is_unknown_conflict() {
5224        let dup = format!(
5225            "# BEGIN {MARKER}\n{DESIRED}\n# END {MARKER}\n# BEGIN {MARKER}\n{DESIRED}\n# END {MARKER}\n"
5226        );
5227        assert_eq!(cron_classify(&dup, MARKER, DESIRED), CronOwnership::Unknown);
5228        assert!(cron_merge(&dup, MARKER, DESIRED).is_err());
5229        assert!(cron_remove(&dup, MARKER, DESIRED).is_err());
5230    }
5231
5232    #[test]
5233    fn cron_modified_block_is_foreign_no_overwrite() {
5234        let other = format!("# BEGIN {MARKER}\n0 0 * * * /opt/evil/bin\n# END {MARKER}\n");
5235        assert_eq!(
5236            cron_classify(&other, MARKER, DESIRED),
5237            CronOwnership::Foreign
5238        );
5239        assert!(cron_merge(&other, MARKER, DESIRED).is_err());
5240        // Original bytes untouched by the failed merge.
5241        assert!(other.contains("/opt/evil/bin"));
5242    }
5243
5244    #[test]
5245    fn cron_uninstall_only_owned_block() {
5246        let (merged, _) = cron_merge("", MARKER, DESIRED).unwrap();
5247        let (removed, changed) = cron_remove(&merged, MARKER, DESIRED).unwrap();
5248        assert!(changed);
5249        assert!(!removed.contains(MARKER));
5250        // No-op uninstall does not rewrite.
5251        let (removed2, changed2) = cron_remove(&removed, MARKER, DESIRED).unwrap();
5252        assert!(!changed2);
5253        assert_eq!(removed, removed2);
5254    }
5255
5256    #[test]
5257    fn cron_command_adapter_skips_redundant_write() {
5258        let fake = FakeExecutor::new();
5259        // inspect list
5260        fake.expect(&["crontab", "-l"], out(0, ""));
5261        // install: list, then write (list #2 for merge, list #3 for race check).
5262        // Our install does list → merge → list (race check) → write.
5263        // Script: list(empty) [cron_ownership? no, install lists once for merge
5264        // input, once for race check]. Actually install calls list twice total
5265        // (once for merge input via `current`, once for `fresh`). Plus inspect
5266        // in the test calls list once more. Total: inspect(1) + install(2).
5267        let _ = fake;
5268        // Simpler: test pure idempotency (no executor) plus adapter no-op path.
5269        let fake = FakeExecutor::new();
5270        let installed = format!("# BEGIN {MARKER}\n{DESIRED}\n# END {MARKER}\n");
5271        // inspect
5272        fake.expect(&["crontab", "-l"], out(0, &installed));
5273        // install: current
5274        fake.expect(&["crontab", "-l"], out(0, &installed));
5275        let mut m = CronManager::new(
5276            fake,
5277            MARKER.to_string(),
5278            DESIRED.to_string(),
5279            Duration::from_secs(5),
5280        )
5281        .unwrap();
5282        let s = spec("cron-job", "/opt/app/bin", &["--serve"]);
5283        // Install is idempotent: no `crontab -` call (only two `-l` calls).
5284        let r = m.install(&s).unwrap();
5285        assert!(r.completed);
5286        assert_eq!(r.detail, "cron block already installed");
5287    }
5288
5289    #[test]
5290    fn cron_command_timeout_and_missing_binary() {
5291        // Timeout surfaces as Manager, never assumed state.
5292        let fake = FakeExecutor::new();
5293        fake.expect_error(
5294            &["crontab", "-l"],
5295            ServiceError::manager(
5296                ManagerFailureKind::Timeout,
5297                "manager command timed out for crontab",
5298            ),
5299        );
5300        let m = CronManager::new(
5301            fake,
5302            MARKER.to_string(),
5303            DESIRED.to_string(),
5304            Duration::from_secs(5),
5305        )
5306        .unwrap();
5307        let s = spec("cron-job", "/opt/app/bin", &[]);
5308        assert_eq!(m.inspect(&s).unwrap().ownership, Ownership::Unknown);
5309
5310        // Missing binary is Manager (not installed), distinguishable.
5311        let fake = FakeExecutor::new();
5312        fake.expect_error(
5313            &["crontab", "-l"],
5314            ServiceError::manager(
5315                ManagerFailureKind::NotFound,
5316                "manager binary missing: crontab",
5317            ),
5318        );
5319        let m = CronManager::new(
5320            fake,
5321            MARKER.to_string(),
5322            DESIRED.to_string(),
5323            Duration::from_secs(5),
5324        )
5325        .unwrap();
5326        assert_eq!(m.inspect(&s).unwrap().ownership, Ownership::Unknown);
5327    }
5328
5329    #[test]
5330    fn cron_has_no_start_stop_semantics() {
5331        let fake = FakeExecutor::new();
5332        let mut m = CronManager::new(
5333            fake,
5334            MARKER.to_string(),
5335            DESIRED.to_string(),
5336            Duration::from_secs(5),
5337        )
5338        .unwrap();
5339        let s = spec("cron-job", "/opt/app/bin", &[]);
5340        assert!(m.start(&s, Duration::from_secs(1)).is_err());
5341        assert!(m.stop(&s, Duration::from_secs(1)).is_err());
5342        assert!(m.restart(&s, Duration::from_secs(1)).is_err());
5343    }
5344
5345    // ---- definition file safety ----
5346
5347    #[test]
5348    fn definition_write_is_atomic_private_and_no_clobber() {
5349        let dir = temp_dir("def-safe");
5350        let dest = dir.join("unit.service");
5351        atomic_write_definition(&dest, b"[Unit]\n", false).unwrap();
5352        #[cfg(unix)]
5353        {
5354            use std::os::unix::fs::PermissionsExt;
5355            let mode = std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777;
5356            assert_eq!(mode, 0o644);
5357        }
5358        // No-clobber: second create fails.
5359        assert!(atomic_write_definition(&dest, b"[Unit]\n", false).is_err());
5360        // Overwrite allowed for owned refresh.
5361        atomic_write_definition(&dest, b"[Unit]\n# v2\n", true).unwrap();
5362        assert!(std::fs::read(&dest).unwrap().ends_with(b"# v2\n"));
5363        // No stray temps.
5364        let leftovers: Vec<_> = std::fs::read_dir(&dir)
5365            .unwrap()
5366            .filter_map(|e| e.ok())
5367            .filter(|e| e.file_name().to_string_lossy().starts_with(".eggup-def-"))
5368            .collect();
5369        assert!(leftovers.is_empty());
5370        let _ = std::fs::remove_dir_all(&dir);
5371    }
5372
5373    #[test]
5374    fn definition_write_rejects_missing_parent() {
5375        let dir = temp_dir("def-noparent");
5376        let dest = dir.join("no-such-dir/unit.service");
5377        let err = atomic_write_definition(&dest, b"[Unit]\n", false).unwrap_err();
5378        assert!(matches!(
5379            err,
5380            ServiceError::InvalidInput(_) | ServiceError::Manager { .. }
5381        ));
5382        assert!(!dir.join("no-such-dir").exists());
5383        let _ = std::fs::remove_dir_all(&dir);
5384    }
5385
5386    // ---- host detection ----
5387
5388    #[test]
5389    fn host_detection_distinguishes_unavailable_from_failure() {
5390        // Script probes according to the host OS gate used by `inspect_host`.
5391        let fake = FakeExecutor::new();
5392        if std::env::consts::OS == "linux" {
5393            fake.expect(&["systemctl", "--version"], out(0, "systemd 255\n"));
5394        }
5395        if std::env::consts::OS == "macos" {
5396            fake.expect(&["launchctl", "version"], out(0, "launchctl 1.0\n"));
5397        }
5398        fake.expect(&["crontab", "-l"], out(1, "no crontab for user\n"));
5399        let facts = inspect_host(&fake);
5400        assert!(facts.is_ok());
5401        let facts = facts.unwrap();
5402        // Detection failure (Err) stays distinct from "not installed" (false).
5403        assert!(!facts.systemd_available || std::env::consts::OS == "linux");
5404    }
5405
5406    #[test]
5407    fn host_detection_failure_is_distinguishable() {
5408        let fake = FakeExecutor::new();
5409        fake.expect_error(
5410            &["systemctl", "--version"],
5411            ServiceError::manager(
5412                ManagerFailureKind::Timeout,
5413                "manager command timed out for systemctl",
5414            ),
5415        );
5416        // On Linux this propagates as Err (detection failure, not "absent").
5417        // On macOS the systemctl probe is skipped (OS gate) so no error.
5418        // Assert the helper never panics and distinguishes via Result.
5419        let _ = inspect_host(&fake);
5420    }
5421
5422    #[test]
5423    fn candidate_policy_prefers_native_then_cron() {
5424        let facts = HostFacts {
5425            os: "linux".to_string(),
5426            systemd_available: true,
5427            launchd_available: false,
5428            crontab_available: true,
5429        };
5430        assert_eq!(
5431            candidate_managers(&facts),
5432            vec![
5433                CandidateManager::Systemd(SystemdScope::System),
5434                CandidateManager::Cron
5435            ]
5436        );
5437        let facts = HostFacts {
5438            os: "macos".to_string(),
5439            systemd_available: false,
5440            launchd_available: true,
5441            crontab_available: false,
5442        };
5443        assert_eq!(
5444            candidate_managers(&facts),
5445            vec![CandidateManager::Launchd(LaunchdDomain::UserAgent)]
5446        );
5447        let facts = HostFacts {
5448            os: "linux".to_string(),
5449            systemd_available: false,
5450            launchd_available: false,
5451            crontab_available: true,
5452        };
5453        assert_eq!(candidate_managers(&facts), vec![CandidateManager::Cron]);
5454    }
5455
5456    // ---- native smoke (skipped when unsafe) ----
5457
5458    #[test]
5459    fn native_systemctl_parsing_smoke_where_booted() {
5460        if !std::path::Path::new("/run/systemd/system").exists() {
5461            eprintln!("skipping: not booted with systemd");
5462            return;
5463        }
5464        let ex = SystemExecutor::new();
5465        let out = ex.run(
5466            &["systemctl".to_string(), "--version".to_string()],
5467            None,
5468            Duration::from_secs(5),
5469        );
5470        // Must not panic; either Ok or missing-binary Manager.
5471        let _ = out;
5472    }
5473
5474    #[test]
5475    fn native_launchd_smoke_on_macos_only() {
5476        if std::env::consts::OS != "macos" {
5477            eprintln!("skipping: launchd smoke requires macOS");
5478            return;
5479        }
5480        let ex = SystemExecutor::new();
5481        let out = ex.run(
5482            &["launchctl".to_string(), "version".to_string()],
5483            None,
5484            Duration::from_secs(5),
5485        );
5486        let _ = out;
5487    }
5488
5489    #[test]
5490    fn native_crontab_list_only_never_mutates() {
5491        let ex = SystemExecutor::new();
5492        // List-only smoke: never runs `crontab -` here.
5493        let out = ex.run(
5494            &["crontab".to_string(), "-l".to_string()],
5495            None,
5496            Duration::from_secs(5),
5497        );
5498        match out {
5499            Ok(_) => {}
5500            Err(e) if e.manager_kind() == Some(ManagerFailureKind::NotFound) => {
5501                eprintln!("skipping: crontab not installed");
5502            }
5503            Err(_) => {}
5504        }
5505    }
5506
5507    // ---- consumer-specific rejection proof ----
5508
5509    #[test]
5510    fn adapter_rejects_consumer_specific_constants() {
5511        // The adapters must not know product names, daemon users, or
5512        // hardening directives. Prove by construction: install descriptors
5513        // carry only mechanics + caller bytes; no defaults embed products.
5514        let install = SystemdInstall::new(
5515            "my-daemon.service".to_string(),
5516            SystemdScope::User,
5517            absolute("/tmp/my-daemon.service"),
5518            b"[Unit]\n".to_vec(),
5519            false,
5520            false,
5521            Duration::from_secs(5),
5522        )
5523        .unwrap();
5524        assert!(!String::from_utf8_lossy(&install.definition).contains("eggsact"));
5525        assert!(!install.unit_name.contains("eggsearch"));
5526        // Cron marker/block are caller-owned; the manager adds no content.
5527        let m = CronManager::new(
5528            FakeExecutor::new(),
5529            "caller-marker-xyz".to_string(),
5530            "*/5 * * * * /caller/bin".to_string(),
5531            Duration::from_secs(5),
5532        )
5533        .unwrap();
5534        assert_eq!(m.marker(), "caller-marker-xyz");
5535    }
5536}