Skip to main content

pitchfork_cli/
daemon.rs

1use crate::config_types::OneshotWait;
2use crate::daemon_id::DaemonId;
3use crate::daemon_status::DaemonStatus;
4use crate::pitchfork_toml::{
5    CpuLimit, CronRetrigger, Dir, HealthCmd, HealthHttp, HealthPort, MemoryLimit, PortConfig,
6    ReadyCmd, ReadyHttp, ReadyOutput, ReadyPort, Retry, StopConfig, WatchMode,
7};
8use indexmap::IndexMap;
9use std::fmt::Display;
10use std::path::PathBuf;
11
12/// Validates a daemon ID to ensure it's safe for use in file paths and IPC.
13///
14/// A valid daemon ID:
15/// - Is not empty
16/// - Does not contain backslashes (`\`)
17/// - Does not contain parent directory references (`..`)
18/// - Does not contain spaces
19/// - Does not contain `--` (reserved for path encoding of `/`)
20/// - Is not `.` (current directory)
21/// - Contains only printable ASCII characters
22/// - If qualified (contains `/`), has exactly one `/` separating namespace and short ID
23///
24/// Format: `[namespace/]short_id`
25/// - Qualified: `project/api`, `global/web`
26/// - Short: `api`, `web`
27///
28/// This validation prevents path traversal attacks when daemon IDs are used
29/// to construct log file paths or other filesystem operations.
30pub fn is_valid_daemon_id(id: &str) -> bool {
31    if id.contains('/') {
32        DaemonId::parse(id).is_ok()
33    } else {
34        DaemonId::try_new("global", id).is_ok()
35    }
36}
37
38#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
39pub struct Daemon {
40    pub id: DaemonId,
41    pub title: Option<String>,
42    pub pid: Option<u32>,
43    /// High-resolution kernel start token recorded at spawn. Together with
44    /// `pid` this identifies the process across a supervisor crash: a recycled
45    /// PID has a different token, so orphan cleanup can tell a genuine orphan
46    /// from an unrelated process.
47    #[serde(skip_serializing_if = "Option::is_none", default)]
48    pub start_time: Option<u64>,
49    /// System boot time (seconds since epoch) recorded at spawn. Lets orphan
50    /// reconciliation tell a daemon that died under a crashed supervisor
51    /// during this boot from one whose process died with the machine, which
52    /// need different terminal states. Unlike `start_time` this is a
53    /// wall-clock value comparable across processes and platforms.
54    #[serde(skip_serializing_if = "Option::is_none", default)]
55    pub boot_time: Option<u64>,
56    pub shell_pid: Option<u32>,
57    pub status: DaemonStatus,
58    pub dir: Option<PathBuf>,
59    #[serde(skip_serializing_if = "Option::is_none", default)]
60    pub cmd: Option<Vec<String>>,
61    /// Original shell command string, persisted for retry/watch restarts.
62    #[serde(skip_serializing_if = "Option::is_none", default)]
63    pub run: Option<String>,
64    pub autostop: bool,
65    #[serde(skip_serializing_if = "Option::is_none", default)]
66    pub cron_schedule: Option<String>,
67    #[serde(skip_serializing_if = "Option::is_none", default)]
68    pub cron_retrigger: Option<CronRetrigger>,
69    #[serde(skip_serializing_if = "Option::is_none", default)]
70    pub cron_immediate: Option<bool>,
71    #[serde(skip_serializing_if = "Option::is_none", default)]
72    pub last_cron_triggered: Option<chrono::DateTime<chrono::Local>>,
73    #[serde(skip_serializing_if = "Option::is_none", default)]
74    pub last_exit_success: Option<bool>,
75    #[serde(default)]
76    pub retry: Retry,
77    #[serde(default)]
78    pub retry_count: u32,
79    #[serde(skip_serializing_if = "Option::is_none", default)]
80    pub ready_delay: Option<u64>,
81    #[serde(skip_serializing_if = "Option::is_none", default)]
82    pub ready_output: Option<ReadyOutput>,
83    #[serde(skip_serializing_if = "Option::is_none", default)]
84    pub ready_http: Option<ReadyHttp>,
85    #[serde(skip_serializing_if = "Option::is_none", default)]
86    pub ready_port: Option<ReadyPort>,
87    #[serde(skip_serializing_if = "Option::is_none", default)]
88    pub ready_cmd: Option<ReadyCmd>,
89    #[serde(skip_serializing_if = "Option::is_none", default)]
90    pub health_cmd: Option<HealthCmd>,
91    #[serde(skip_serializing_if = "Option::is_none", default)]
92    pub health_http: Option<HealthHttp>,
93    #[serde(skip_serializing_if = "Option::is_none", default)]
94    pub health_port: Option<HealthPort>,
95    /// Port configuration (expected ports and auto-bump settings)
96    #[serde(skip_serializing_if = "Option::is_none", default)]
97    pub port: Option<PortConfig>,
98    /// Resolved ports actually used after auto-bump (may differ from expected)
99    #[serde(skip_serializing_if = "Vec::is_empty", default)]
100    pub resolved_port: Vec<u16>,
101    /// The first port the process is actually listening on (detected at runtime via listeners crate).
102    /// This is the source of truth for the reverse proxy. Cleared when the daemon stops.
103    #[serde(skip_serializing_if = "Option::is_none", default)]
104    pub active_port: Option<u16>,
105    /// Optional stable slug alias for this daemon (used in proxy URLs and CLI commands).
106    #[serde(skip_serializing_if = "Option::is_none", default)]
107    pub slug: Option<String>,
108    /// Whether to proxy this daemon (None = inherit global proxy.enable setting).
109    #[serde(skip_serializing_if = "Option::is_none", default)]
110    pub proxy: Option<bool>,
111    #[serde(skip_serializing_if = "Vec::is_empty", default)]
112    pub depends: Vec<DaemonId>,
113    #[serde(skip_serializing_if = "Option::is_none", default)]
114    pub env: Option<IndexMap<String, String>>,
115    #[serde(skip_serializing_if = "Vec::is_empty", default)]
116    pub watch: Vec<String>,
117    #[serde(default)]
118    pub watch_mode: WatchMode,
119    #[serde(skip_serializing_if = "Option::is_none", default)]
120    pub watch_base_dir: Option<PathBuf>,
121    /// Whether to use mise for this daemon (None = inherit global general.mise setting).
122    ///
123    /// # Schema compatibility note
124    /// This field changed from `bool` to `Option<bool>` with `skip_serializing_if = "Option::is_none"`.
125    /// - **Upgrade (old → new):** safe — old files contain `mise = true/false`, which deserialize
126    ///   correctly as `Some(true)` / `Some(false)`.
127    /// - **Downgrade (new → old):** if `mise` is `None` (inherit global), the key is omitted from
128    ///   the state file. An old binary reads the missing key as `false`, ignoring `general.mise = true`.
129    ///   Any daemon that relied on the global setting would silently stop using mise after a downgrade.
130    #[serde(skip_serializing_if = "Option::is_none", default)]
131    pub mise: Option<bool>,
132    /// Unix user to run this daemon as.
133    #[serde(skip_serializing_if = "Option::is_none", default)]
134    pub user: Option<String>,
135    /// Memory limit for the daemon process (e.g. "50MB", "1GiB")
136    #[serde(skip_serializing_if = "Option::is_none", default)]
137    pub memory_limit: Option<MemoryLimit>,
138    /// CPU usage limit as a percentage (e.g. 80 for 80%, 200 for 2 cores)
139    #[serde(skip_serializing_if = "Option::is_none", default)]
140    pub cpu_limit: Option<CpuLimit>,
141    /// Unix signal to send for graceful shutdown (default: SIGTERM)
142    #[serde(skip_serializing_if = "Option::is_none", default)]
143    pub stop_signal: Option<StopConfig>,
144    /// Archive hook command invoked before retention prunes this daemon's logs.
145    #[serde(skip_serializing_if = "Option::is_none", default)]
146    pub archive_hook: Option<String>,
147    /// Log format for this daemon.
148    #[serde(skip_serializing_if = "Option::is_none", default)]
149    pub log_format: Option<String>,
150    /// Allocate a pseudo-terminal for the daemon process.
151    #[serde(skip_serializing_if = "Option::is_none", default)]
152    pub pty: Option<bool>,
153    /// True for daemons auto-registered from config by the cron watcher,
154    /// not yet started. Treated as "available" by list/status/stats.
155    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
156    pub config_registered: bool,
157    /// Run-to-completion task rather than a long-running service. Readiness is
158    /// a zero exit code, and the terminal state is `completed` instead of
159    /// `stopped`. See `DaemonStatus::Completed`.
160    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
161    pub oneshot: bool,
162    /// Set when the proxy started this run and it may be stopped for
163    /// inactivity: how long, in milliseconds, it may go without proxy
164    /// activity. `None` for a daemon started any other way, or claimed since
165    /// by an explicit start.
166    #[serde(default)]
167    pub proxy_idle_timeout_ms: Option<u64>,
168    /// When the cron watcher last actually started this daemon.
169    ///
170    /// Distinct from `last_cron_triggered`, which advances on every scheduled
171    /// tick the watcher observes -- including the anchoring tick that
172    /// `immediate = false` uses to skip the first window, and ticks where the
173    /// `retrigger` policy declines to run. Only this field means "it ran",
174    /// which is what `last_exit_success` describes the outcome of.
175    #[serde(skip_serializing_if = "Option::is_none", default)]
176    pub last_cron_run: Option<chrono::DateTime<chrono::Local>>,
177    /// Start `cmd` directly, without a shell. See `RunOptions::no_shell`.
178    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
179    pub no_shell: bool,
180    /// Registered from config by the cron watcher and only ever started by
181    /// its schedule since, so each scheduled run is built from the current
182    /// config, templates rendered, rather than from what was stored at
183    /// registration. Cleared once a client starts the daemon: a run it asked
184    /// for carries its own options, which the schedule then keeps.
185    ///
186    /// Appended after `no_shell` for the positional IPC encoding.
187    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
188    pub scheduled_from_config: bool,
189}
190
191#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Default)]
192pub struct RunOptions {
193    pub id: DaemonId,
194    pub cmd: Vec<String>,
195    /// Original shell command string (from config `run`), passed verbatim to the shell.
196    /// Falls back to joining `cmd` when None (e.g. ad-hoc `pitchfork run -- cmd args`).
197    #[serde(skip_serializing_if = "Option::is_none", default)]
198    pub run: Option<String>,
199    pub force: bool,
200    pub shell_pid: Option<u32>,
201    pub dir: Dir,
202    pub autostop: bool,
203    pub cron_schedule: Option<String>,
204    pub cron_retrigger: Option<CronRetrigger>,
205    pub cron_immediate: Option<bool>,
206    pub retry: Retry,
207    pub retry_count: u32,
208    pub ready_delay: Option<u64>,
209    pub ready_output: Option<ReadyOutput>,
210    pub ready_http: Option<ReadyHttp>,
211    pub ready_port: Option<ReadyPort>,
212    pub ready_cmd: Option<ReadyCmd>,
213    pub health_cmd: Option<HealthCmd>,
214    pub health_http: Option<HealthHttp>,
215    pub health_port: Option<HealthPort>,
216    pub port: Option<PortConfig>,
217    pub wait_ready: bool,
218    #[serde(skip_serializing_if = "Vec::is_empty", default)]
219    pub depends: Vec<DaemonId>,
220    #[serde(skip_serializing_if = "Option::is_none", default)]
221    pub env: Option<IndexMap<String, String>>,
222    #[serde(skip_serializing_if = "Vec::is_empty", default)]
223    pub watch: Vec<String>,
224    #[serde(default)]
225    pub watch_mode: WatchMode,
226    #[serde(skip_serializing_if = "Option::is_none", default)]
227    pub watch_base_dir: Option<PathBuf>,
228    /// Whether to use mise for this daemon (None = inherit global general.mise setting).
229    ///
230    /// # Schema compatibility note
231    /// See `Daemon::mise` for downgrade implications when this field is `None`.
232    #[serde(skip_serializing_if = "Option::is_none", default)]
233    pub mise: Option<bool>,
234    /// Optional stable slug alias for this daemon.
235    #[serde(skip_serializing_if = "Option::is_none", default)]
236    pub slug: Option<String>,
237    /// Whether to proxy this daemon (None = inherit global proxy.enable setting).
238    #[serde(skip_serializing_if = "Option::is_none", default)]
239    pub proxy: Option<bool>,
240    /// Unix user to run this daemon as.
241    #[serde(skip_serializing_if = "Option::is_none", default)]
242    pub user: Option<String>,
243    /// Memory limit for the daemon process (e.g. "50MB", "1GiB")
244    #[serde(skip_serializing_if = "Option::is_none", default)]
245    pub memory_limit: Option<MemoryLimit>,
246    /// CPU usage limit as a percentage (e.g. 80 for 80%, 200 for 2 cores)
247    #[serde(skip_serializing_if = "Option::is_none", default)]
248    pub cpu_limit: Option<CpuLimit>,
249    /// Unix signal to send for graceful shutdown (default: SIGTERM)
250    #[serde(skip_serializing_if = "Option::is_none", default)]
251    pub stop_signal: Option<StopConfig>,
252    /// Archive hook command invoked before retention prunes this daemon's logs.
253    #[serde(skip_serializing_if = "Option::is_none", default)]
254    pub archive_hook: Option<String>,
255    /// Log format for this daemon: `json`, `logfmt`, `auto`, or `text`.
256    #[serde(skip_serializing_if = "Option::is_none", default)]
257    pub log_format: Option<String>,
258    /// Hook triggered when the daemon produces matching output
259    #[serde(skip_serializing_if = "Option::is_none", default)]
260    pub on_output_hook: Option<crate::pitchfork_toml::OnOutputHook>,
261    /// Allocate a pseudo-terminal for the daemon process.
262    #[serde(skip_serializing_if = "Option::is_none", default)]
263    pub pty: Option<bool>,
264    /// Run-to-completion task rather than a long-running service.
265    #[serde(default)]
266    pub oneshot: bool,
267    /// How long to wait for a oneshot to finish, already resolved from the
268    /// project's `supervisor.oneshot_timeout`.
269    ///
270    /// Resolved by the client and carried on the request because the
271    /// supervisor is long-lived and may have started in another directory, so
272    /// its own `settings()` would not see the project's value. `None` leaves
273    /// the supervisor to fall back to whatever it can resolve.
274    #[serde(skip_serializing_if = "Option::is_none", default)]
275    pub oneshot_wait: Option<OneshotWait>,
276    /// This start came from entering a directory rather than from a person
277    /// asking for it, so a completed `oneshot` is left alone. Decided by the
278    /// supervisor because only it holds authoritative state: the state file
279    /// lags it by up to the flush interval, which is exactly the window a
280    /// second directory entry lands in.
281    #[serde(default)]
282    pub on_directory_enter: bool,
283    /// The proxy is starting this daemon, and it may be stopped after this
284    /// many milliseconds without proxy activity. `None` for every other start,
285    /// which is what makes such a start explicit. Carried over by restarts
286    /// (retry, file watch), which continue the same ownership.
287    #[serde(default)]
288    pub proxy_idle_timeout_ms: Option<u64>,
289    /// The cron watcher is starting this run, so a successful spawn is what
290    /// `Daemon::last_cron_run` records.
291    ///
292    /// Set only by the watcher's own call. A retry, file-watch or manual
293    /// restart of a scheduled daemon carries the daemon's `cron_schedule` but
294    /// not this, because the schedule did not ask for it.
295    #[serde(default)]
296    pub cron_started: bool,
297    /// Start `cmd` directly, without a shell: the config's `run` was an
298    /// array. `run` is `None` then, since there is no command line.
299    #[serde(default)]
300    pub no_shell: bool,
301    /// Set by the supervisor on a start a client asked for over IPC; never
302    /// sent. See `Daemon::scheduled_from_config`.
303    #[serde(skip)]
304    pub requested_by_client: bool,
305}
306
307impl Daemon {
308    /// The next time the cron watcher will consider this daemon due, or
309    /// `None` when it has no schedule or the schedule does not parse.
310    ///
311    /// Anchored exactly the way `check_cron_schedules` anchors itself, so the
312    /// answer is what the watcher will actually do rather than an independent
313    /// reading of the schedule. That includes the case where the supervisor
314    /// was down across a window: the anchor is still the old tick, so the
315    /// result is a time in the past -- the overdue run the watcher takes on
316    /// its next check.
317    pub fn next_cron_run(
318        &self,
319        now: chrono::DateTime<chrono::Local>,
320    ) -> Option<chrono::DateTime<chrono::Local>> {
321        use std::str::FromStr;
322        let schedule = cron::Schedule::from_str(self.cron_schedule.as_ref()?).ok()?;
323        let anchor = match self.last_cron_triggered {
324            Some(t) => t,
325            // Mirrors the watcher's first-sighting branch: `immediate` looks
326            // back ten seconds, the default anchors to now.
327            None if self.cron_immediate.unwrap_or(false) => now - chrono::Duration::seconds(10),
328            None => now,
329        };
330        schedule.after(&anchor).next()
331    }
332
333    /// Build RunOptions from persisted daemon state.
334    ///
335    /// Carries over all configuration fields from the daemon state.
336    /// Callers can override specific fields on the returned value.
337    pub fn to_run_options(&self, cmd: Vec<String>) -> RunOptions {
338        // Re-read on_output_hook from fresh config so restarts (retry, watch,
339        // cron) always pick up the current hook configuration.
340        // Use daemon.dir if available to handle daemons started via slugs
341        // whose project directory is not in the supervisor's cwd ancestry.
342        let on_output_hook = self
343            .dir
344            .as_deref()
345            .and_then(|dir| crate::pitchfork_toml::PitchforkToml::all_merged_from(dir).ok())
346            .or_else(|| crate::pitchfork_toml::PitchforkToml::all_merged_all_namespaces().ok())
347            .and_then(|pt| {
348                pt.daemons
349                    .get(&self.id)
350                    .and_then(|d| d.hooks.as_ref())
351                    .and_then(|h| h.on_output.clone())
352            });
353
354        RunOptions {
355            id: self.id.clone(),
356            cmd,
357            run: self.run.clone(),
358            force: false,
359            shell_pid: self.shell_pid,
360            dir: Dir(self.dir.clone().unwrap_or_else(|| crate::env::CWD.clone())),
361            autostop: self.autostop,
362            oneshot: self.oneshot,
363            // Re-resolved by the client on the paths that have a project to
364            // resolve it from; a supervisor-internal restart keeps None and
365            // falls back.
366            oneshot_wait: None,
367            on_directory_enter: false,
368            // A restart continues whatever ownership the run it replaces had.
369            proxy_idle_timeout_ms: self.proxy_idle_timeout_ms,
370            // A restart of a scheduled daemon is not the schedule starting a
371            // run; only the cron watcher's own call sets this.
372            cron_started: false,
373            no_shell: self.no_shell,
374            // Set by the IPC handler for a client's own request.
375            requested_by_client: false,
376            cron_schedule: self.cron_schedule.clone(),
377            cron_retrigger: self.cron_retrigger,
378            cron_immediate: self.cron_immediate,
379            retry: self.retry,
380            retry_count: self.retry_count,
381            ready_delay: self.ready_delay,
382            ready_output: self.ready_output.clone(),
383            ready_http: self.ready_http.clone(),
384            ready_port: self.ready_port.clone(),
385            ready_cmd: self.ready_cmd.clone(),
386            health_cmd: self.health_cmd.clone(),
387            health_http: self.health_http.clone(),
388            health_port: self.health_port.clone(),
389            port: self.port.clone(),
390            wait_ready: false,
391            depends: self.depends.clone(),
392            env: self.env.clone(),
393            watch: self.watch.clone(),
394            watch_mode: self.watch_mode,
395            watch_base_dir: self.watch_base_dir.clone(),
396            mise: self.mise,
397            slug: self.slug.clone(),
398            proxy: self.proxy,
399            user: self.user.clone(),
400            memory_limit: self.memory_limit,
401            cpu_limit: self.cpu_limit,
402            stop_signal: self.stop_signal,
403            archive_hook: self.archive_hook.clone(),
404            log_format: self.log_format.clone(),
405            on_output_hook,
406            pty: self.pty,
407        }
408    }
409}
410
411impl Display for Daemon {
412    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
413        write!(f, "{}", self.id.qualified())
414    }
415}
416
417#[cfg(test)]
418mod tests {
419    use super::*;
420    use chrono::TimeZone;
421
422    fn at(h: u32, m: u32, sec: u32) -> chrono::DateTime<chrono::Local> {
423        chrono::Local
424            .with_ymd_and_hms(2026, 9, 21, h, m, sec)
425            .unwrap()
426    }
427
428    /// Daily at 03:00, the schedule from the report that asked for this.
429    fn daily_3am(last_triggered: Option<chrono::DateTime<chrono::Local>>) -> Daemon {
430        Daemon {
431            cron_schedule: Some("0 0 3 * * *".to_string()),
432            last_cron_triggered: last_triggered,
433            ..Daemon::default()
434        }
435    }
436
437    #[test]
438    fn next_cron_run_is_none_without_a_schedule() {
439        assert!(Daemon::default().next_cron_run(at(7, 0, 0)).is_none());
440    }
441
442    /// The watcher warns and skips an expression it cannot parse; there is no
443    /// next run to report for one.
444    #[test]
445    fn next_cron_run_is_none_for_an_invalid_schedule() {
446        let d = Daemon {
447            cron_schedule: Some("not a cron expression".to_string()),
448            ..Daemon::default()
449        };
450        assert!(d.next_cron_run(at(7, 0, 0)).is_none());
451    }
452
453    #[test]
454    fn next_cron_run_follows_the_last_tick() {
455        let d = daily_3am(Some(at(3, 0, 4)));
456        assert_eq!(
457            d.next_cron_run(at(7, 0, 0)),
458            Some(
459                chrono::Local
460                    .with_ymd_and_hms(2026, 9, 22, 3, 0, 0)
461                    .unwrap()
462            )
463        );
464    }
465
466    /// A supervisor that was down across 03:00 has a stale anchor, so the next
467    /// run is in the past: the window it still owes, which is what the watcher
468    /// will take on its next check.
469    #[test]
470    fn next_cron_run_reports_a_missed_window_as_past() {
471        let d = daily_3am(Some(
472            chrono::Local
473                .with_ymd_and_hms(2026, 9, 20, 3, 0, 0)
474                .unwrap(),
475        ));
476        let next = d.next_cron_run(at(7, 0, 0)).unwrap();
477        assert_eq!(next, at(3, 0, 0));
478        assert!(next < at(7, 0, 0));
479    }
480
481    /// Never triggered, `immediate = false`: the watcher will anchor to now
482    /// and skip the current window, so the answer is the next one.
483    #[test]
484    fn next_cron_run_skips_the_current_window_without_immediate() {
485        let d = daily_3am(None);
486        assert_eq!(
487            d.next_cron_run(at(2, 59, 0)),
488            Some(at(3, 0, 0)),
489            "a window still ahead of now is reported as-is"
490        );
491        assert_eq!(
492            d.next_cron_run(at(3, 0, 30)),
493            Some(
494                chrono::Local
495                    .with_ymd_and_hms(2026, 9, 22, 3, 0, 0)
496                    .unwrap()
497            ),
498            "a window that just passed is not claimed: immediate=false skips it"
499        );
500    }
501
502    /// `immediate = true` keeps the watcher's ten-second look-back, so a
503    /// window that just passed is still due.
504    #[test]
505    fn next_cron_run_honors_the_immediate_lookback() {
506        let d = Daemon {
507            cron_immediate: Some(true),
508            ..daily_3am(None)
509        };
510        assert_eq!(d.next_cron_run(at(3, 0, 5)), Some(at(3, 0, 0)));
511    }
512
513    #[test]
514    fn test_valid_daemon_ids() {
515        // Short IDs
516        assert!(is_valid_daemon_id("myapp"));
517        assert!(is_valid_daemon_id("my-app"));
518        assert!(is_valid_daemon_id("my_app"));
519        assert!(is_valid_daemon_id("my.app"));
520        assert!(is_valid_daemon_id("MyApp123"));
521
522        // Qualified IDs (namespace/short_id)
523        assert!(is_valid_daemon_id("project/api"));
524        assert!(is_valid_daemon_id("global/web"));
525        assert!(is_valid_daemon_id("my-project/my-app"));
526    }
527
528    #[test]
529    fn test_invalid_daemon_ids() {
530        // Empty
531        assert!(!is_valid_daemon_id(""));
532
533        // Multiple slashes (invalid qualified format)
534        assert!(!is_valid_daemon_id("a/b/c"));
535        assert!(!is_valid_daemon_id("../etc/passwd"));
536
537        // Invalid qualified format (empty parts)
538        assert!(!is_valid_daemon_id("/api"));
539        assert!(!is_valid_daemon_id("project/"));
540
541        // Backslashes
542        assert!(!is_valid_daemon_id("foo\\bar"));
543
544        // Parent directory reference
545        assert!(!is_valid_daemon_id(".."));
546        assert!(!is_valid_daemon_id("foo..bar"));
547
548        // Double dash (reserved for path encoding)
549        assert!(!is_valid_daemon_id("my--app"));
550        assert!(!is_valid_daemon_id("project--api"));
551        assert!(!is_valid_daemon_id("--app"));
552        assert!(!is_valid_daemon_id("app--"));
553
554        // Spaces
555        assert!(!is_valid_daemon_id("my app"));
556        assert!(!is_valid_daemon_id(" myapp"));
557        assert!(!is_valid_daemon_id("myapp "));
558
559        // Current directory
560        assert!(!is_valid_daemon_id("."));
561
562        // Control characters
563        assert!(!is_valid_daemon_id("my\x00app"));
564        assert!(!is_valid_daemon_id("my\napp"));
565        assert!(!is_valid_daemon_id("my\tapp"));
566
567        // Non-ASCII
568        assert!(!is_valid_daemon_id("myäpp"));
569        assert!(!is_valid_daemon_id("приложение"));
570
571        // Unsupported punctuation under DaemonId rules
572        assert!(!is_valid_daemon_id("app@host"));
573        assert!(!is_valid_daemon_id("app:8080"));
574    }
575}