pitchfork-cli 2.6.0

Daemons with DX
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! Structured daemon ID type that separates namespace and name.
//!
//! This module provides a type-safe representation of daemon IDs that
//! eliminates the need for repeated parsing and formatting operations.

use crate::Result;
use crate::error::DaemonIdError;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt::{self, Display};
use std::hash::Hash;

/// A structured daemon identifier consisting of a namespace and a name.
///
/// All daemons have a namespace - global daemons use "global" as their namespace.
/// This type eliminates the need to repeatedly parse and format daemon IDs.
///
/// # Formats
///
/// - **Qualified format**: `namespace/name` (e.g., `project-a/api`, `global/web`)
/// - **Safe path format**: `namespace--name` (for filesystem paths)
///
/// # Examples
///
/// ```
/// use pitchfork_cli::daemon_id::DaemonId;
///
/// let id = DaemonId::try_new("project-a", "api").unwrap();
/// assert_eq!(id.namespace(), "project-a");
/// assert_eq!(id.name(), "api");
/// assert_eq!(id.qualified(), "project-a/api");
/// assert_eq!(id.safe_path(), "project-a--api");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DaemonId {
    namespace: String,
    name: String,
}

impl Default for DaemonId {
    fn default() -> Self {
        Self {
            namespace: "global".to_string(),
            name: "unknown".to_string(),
        }
    }
}

impl DaemonId {
    /// Creates a new DaemonId from namespace and name.
    ///
    /// # Panics
    ///
    /// Panics if either the namespace or name is invalid (contains invalid characters,
    /// is empty, contains `--`, etc.). Use `try_new()` for a non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use pitchfork_cli::daemon_id::DaemonId;
    ///
    /// let id = DaemonId::new("global", "api");
    /// ```
    #[cfg(test)]
    pub fn new(namespace: impl Into<String>, name: impl Into<String>) -> Self {
        let namespace = namespace.into();
        let name = name.into();

        // Validate inputs - panic on invalid values
        if let Err(e) = validate_component(&namespace, "namespace") {
            panic!("Invalid namespace '{namespace}': {e}");
        }
        if let Err(e) = validate_component(&name, "name") {
            panic!("Invalid name '{name}': {e}");
        }

        Self { namespace, name }
    }

    /// Creates a new DaemonId without validation.
    ///
    /// # Safety
    ///
    /// This function does not validate the inputs. Use it only when you are certain
    /// the namespace and name are valid (e.g., when reading from a trusted source
    /// like a parsed safe_path with "--" in the namespace component).
    ///
    /// For user-provided input, use `new()` or `try_new()` instead.
    pub(crate) fn new_unchecked(namespace: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            namespace: namespace.into(),
            name: name.into(),
        }
    }

    /// Creates a new DaemonId with validation.
    ///
    /// Returns an error if either the namespace or name is invalid.
    pub fn try_new(namespace: impl Into<String>, name: impl Into<String>) -> Result<Self> {
        let namespace = namespace.into();
        let name = name.into();

        validate_component(&namespace, "namespace")?;
        validate_component(&name, "name")?;

        Ok(Self { namespace, name })
    }

    /// Parses a qualified daemon ID string into a DaemonId.
    ///
    /// The input must be in the format `namespace/name`.
    ///
    /// # Examples
    ///
    /// ```
    /// use pitchfork_cli::daemon_id::DaemonId;
    ///
    /// let id = DaemonId::parse("project-a/api").unwrap();
    /// assert_eq!(id.namespace(), "project-a");
    /// assert_eq!(id.name(), "api");
    /// ```
    pub fn parse(s: &str) -> Result<Self> {
        validate_qualified_id(s)?;

        // validate_qualified_id ensures exactly one '/' is present, so this unwrap is safe.
        let (ns, name) = s
            .split_once('/')
            .expect("validate_qualified_id ensures '/' is present");
        Ok(Self {
            namespace: ns.to_string(),
            name: name.to_string(),
        })
    }

    /// Creates a DaemonId from a filesystem-safe path component.
    ///
    /// Converts `namespace--name` format back to a DaemonId.
    /// Both components are validated with the same rules as `try_new()`,
    /// ensuring that the result can always be serialized and deserialized
    /// through the qualified (`namespace/name`) format without error.
    ///
    /// # Examples
    ///
    /// ```
    /// use pitchfork_cli::daemon_id::DaemonId;
    ///
    /// let id = DaemonId::from_safe_path("project-a--api").unwrap();
    /// assert_eq!(id.qualified(), "project-a/api");
    /// assert_eq!(DaemonId::parse(&id.qualified()).unwrap(), id);
    ///
    /// // Empty namespace or name fails validation
    /// assert!(DaemonId::from_safe_path("--api").is_err());
    /// assert!(DaemonId::from_safe_path("namespace--").is_err());
    /// // Namespace containing "--" is rejected to preserve roundtrip
    /// assert!(DaemonId::from_safe_path("my--project--api").is_err());
    /// ```
    pub fn from_safe_path(s: &str) -> Result<Self> {
        if let Some((ns, name)) = s.split_once("--") {
            // Validate both components with the same rules as try_new().
            // This guarantees that qualified() output can always be re-parsed,
            // preserving the Serialize <-> Deserialize roundtrip contract.
            validate_component(ns, "namespace")?;
            validate_component(name, "name")?;
            Ok(Self {
                namespace: ns.to_string(),
                name: name.to_string(),
            })
        } else {
            Err(DaemonIdError::InvalidSafePath {
                path: s.to_string(),
            }
            .into())
        }
    }

    /// Returns the namespace portion of the daemon ID.
    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    /// Returns a DaemonId for the pitchfork supervisor itself.
    ///
    /// This is a convenience method to avoid repeated `DaemonId::new("global", "pitchfork")` calls.
    pub fn pitchfork() -> Self {
        // Use new_unchecked for this constant value to avoid redundant validation
        Self::new_unchecked("global", "pitchfork")
    }

    /// Returns the name (short ID) portion of the daemon ID.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the qualified format: `namespace/name`.
    pub fn qualified(&self) -> String {
        format!("{}/{}", self.namespace, self.name)
    }

    /// Returns the filesystem-safe format: `namespace--name`.
    pub fn safe_path(&self) -> String {
        format!("{}--{}", self.namespace, self.name)
    }

    /// Returns the main log file path for this daemon.
    pub fn log_path(&self) -> std::path::PathBuf {
        let safe = self.safe_path();
        crate::env::PITCHFORK_LOGS_DIR
            .join(&safe)
            .join(format!("{safe}.log"))
    }

    /// Returns a styled display name for terminal output (stdout).
    ///
    /// The namespace part is displayed in dim color, followed by `/` and the name.
    /// If `all_ids` is provided and the name is unique, only the name is shown.
    pub fn styled_display_name<'a, I>(&self, all_ids: Option<I>) -> String
    where
        I: Iterator<Item = &'a DaemonId>,
    {
        let show_full = match all_ids {
            Some(ids) => ids.filter(|other| other.name == self.name).count() > 1,
            None => true,
        };

        if show_full {
            self.styled_qualified()
        } else {
            self.name.clone()
        }
    }

    /// Returns the qualified format with dim namespace for terminal output (stdout).
    ///
    /// Format: `<dim>namespace</dim>/name`
    pub fn styled_qualified(&self) -> String {
        use crate::ui::style::ndim;
        format!("{}/{}", ndim(&self.namespace), self.name)
    }
}

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

// NOTE: AsRef<str> and Borrow<str> implementations were intentionally removed.
// The Borrow trait has a contract that if T: Borrow<U>, then T's Hash/Eq/Ord
// must be consistent with U's. DaemonId derives Hash and Eq on both namespace
// and name, so implementing Borrow<str> would violate this contract and cause
// HashMap/HashSet lookups via &str to silently break due to hash mismatches.

/// Serialize as qualified string "namespace/name"
impl Serialize for DaemonId {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.qualified())
    }
}

/// Deserialize from qualified string "namespace/name"
impl<'de> Deserialize<'de> for DaemonId {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        DaemonId::parse(&s).map_err(serde::de::Error::custom)
    }
}

/// JSON Schema implementation for DaemonId
///
/// In `pitchfork.toml`, users write **short names** (e.g. `api`) for daemon
/// keys under `[daemons]` and for same-namespace `depends` entries.  Fully
/// qualified `namespace/name` format is only required for cross-namespace
/// dependency references.  The pattern therefore accepts both forms.
impl schemars::JsonSchema for DaemonId {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "DaemonId".into()
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        concat!(module_path!(), "::DaemonId").into()
    }

    fn json_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "type": "string",
            "description": "Daemon name (e.g. 'api') or qualified ID ('namespace/name') for cross-namespace references",
            "pattern": r"^[\w.-]+(/[\w.-]+)?$"
        })
    }
}

/// Validates a single component (namespace or name) of a daemon ID.
fn validate_component(s: &str, component_name: &str) -> Result<()> {
    if s.is_empty() {
        return Err(DaemonIdError::EmptyComponent {
            component: component_name.to_string(),
        }
        .into());
    }
    if s.contains('/') {
        return Err(DaemonIdError::PathSeparator {
            id: s.to_string(),
            sep: '/',
        }
        .into());
    }
    if s.contains('\\') {
        return Err(DaemonIdError::PathSeparator {
            id: s.to_string(),
            sep: '\\',
        }
        .into());
    }
    if s.contains("..") {
        return Err(DaemonIdError::ParentDirRef { id: s.to_string() }.into());
    }
    if s.contains("--") {
        return Err(DaemonIdError::ReservedSequence { id: s.to_string() }.into());
    }
    if s.starts_with('-') || s.ends_with('-') {
        return Err(DaemonIdError::LeadingTrailingDash { id: s.to_string() }.into());
    }
    if s.contains(' ') {
        return Err(DaemonIdError::ContainsSpace { id: s.to_string() }.into());
    }
    if s == "." {
        return Err(DaemonIdError::CurrentDir.into());
    }
    if !s
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
    {
        return Err(DaemonIdError::InvalidChars { id: s.to_string() }.into());
    }
    Ok(())
}

/// Validates a qualified daemon ID string.
fn validate_qualified_id(s: &str) -> Result<()> {
    if s.is_empty() {
        return Err(DaemonIdError::Empty.into());
    }
    if s.contains('\\') {
        return Err(DaemonIdError::PathSeparator {
            id: s.to_string(),
            sep: '\\',
        }
        .into());
    }
    if s.contains(' ') {
        return Err(DaemonIdError::ContainsSpace { id: s.to_string() }.into());
    }
    if !s.chars().all(|c| c.is_ascii() && !c.is_ascii_control()) {
        return Err(DaemonIdError::InvalidChars { id: s.to_string() }.into());
    }

    // Check slash count
    let slash_count = s.chars().filter(|&c| c == '/').count();
    if slash_count == 0 {
        return Err(DaemonIdError::MissingNamespace { id: s.to_string() }.into());
    }
    if slash_count > 1 {
        return Err(DaemonIdError::PathSeparator {
            id: s.to_string(),
            sep: '/',
        }
        .into());
    }

    // Check both parts are non-empty
    let (ns, name) = s.split_once('/').unwrap();
    if ns.is_empty() || name.is_empty() {
        return Err(DaemonIdError::PathSeparator {
            id: s.to_string(),
            sep: '/',
        }
        .into());
    }

    // Validate each component individually
    // This ensures parse("./api") fails just like try_new(".", "api")
    validate_component(ns, "namespace")?;
    validate_component(name, "name")?;

    Ok(())
}

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

    #[test]
    fn test_daemon_id_new() {
        let id = DaemonId::new("global", "api");
        assert_eq!(id.namespace(), "global");
        assert_eq!(id.name(), "api");
        assert_eq!(id.qualified(), "global/api");
        assert_eq!(id.safe_path(), "global--api");
    }

    #[test]
    fn test_daemon_id_parse() {
        let id = DaemonId::parse("project-a/api").unwrap();
        assert_eq!(id.namespace(), "project-a");
        assert_eq!(id.name(), "api");

        // Missing namespace should fail
        assert!(DaemonId::parse("api").is_err());

        // Empty parts should fail
        assert!(DaemonId::parse("/api").is_err());
        assert!(DaemonId::parse("project/").is_err());

        // Multiple slashes should fail
        assert!(DaemonId::parse("a/b/c").is_err());
    }

    #[test]
    fn test_daemon_id_from_safe_path() {
        let id = DaemonId::from_safe_path("project-a--api").unwrap();
        assert_eq!(id.namespace(), "project-a");
        assert_eq!(id.name(), "api");

        // No separator should fail
        assert!(DaemonId::from_safe_path("projectapi").is_err());
    }

    #[test]
    fn test_daemon_id_roundtrip() {
        let original = DaemonId::new("my-project", "my-daemon");
        let safe = original.safe_path();
        let recovered = DaemonId::from_safe_path(&safe).unwrap();
        assert_eq!(original, recovered);
    }

    #[test]
    fn test_daemon_id_display() {
        let id = DaemonId::new("global", "api");
        assert_eq!(format!("{id}"), "global/api");
    }

    #[test]
    fn test_daemon_id_serialize() {
        let id = DaemonId::new("global", "api");
        let json = serde_json::to_string(&id).unwrap();
        assert_eq!(json, "\"global/api\"");

        let deserialized: DaemonId = serde_json::from_str(&json).unwrap();
        assert_eq!(id, deserialized);
    }

    #[test]
    fn test_daemon_id_validation() {
        // Valid IDs
        assert!(DaemonId::try_new("global", "api").is_ok());
        assert!(DaemonId::try_new("my-project", "my-daemon").is_ok());
        assert!(DaemonId::try_new("project_a", "daemon_1").is_ok());

        // Invalid - contains reserved sequences
        assert!(DaemonId::try_new("my--project", "api").is_err());
        assert!(DaemonId::try_new("project", "my--daemon").is_err());

        // Invalid - contains path separators
        assert!(DaemonId::try_new("my/project", "api").is_err());
        assert!(DaemonId::try_new("project", "my/daemon").is_err());

        // Invalid - empty
        assert!(DaemonId::try_new("", "api").is_err());
        assert!(DaemonId::try_new("project", "").is_err());
    }

    #[test]
    fn test_daemon_id_styled_display_name() {
        let id1 = DaemonId::new("project-a", "api");
        let id2 = DaemonId::new("project-b", "api");
        let id3 = DaemonId::new("global", "worker");

        let all_ids = [&id1, &id2, &id3];

        // "api" is ambiguous → full qualified ID must appear in the output
        let out1 = id1.styled_display_name(Some(all_ids.iter().copied()));
        let out2 = id2.styled_display_name(Some(all_ids.iter().copied()));
        assert!(
            out1.contains("project-a") && out1.contains("api"),
            "ambiguous id1 should show namespace: {out1}"
        );
        assert!(
            out2.contains("project-b") && out2.contains("api"),
            "ambiguous id2 should show namespace: {out2}"
        );

        // "worker" is unique → only the short name
        let out3 = id3.styled_display_name(Some(all_ids.iter().copied()));
        assert_eq!(out3, "worker", "unique id3 should show only short name");
    }

    #[test]
    fn test_daemon_id_ordering() {
        let id1 = DaemonId::new("a", "x");
        let id2 = DaemonId::new("a", "y");
        let id3 = DaemonId::new("b", "x");

        assert!(id1 < id2);
        assert!(id2 < id3);
        assert!(id1 < id3);
    }

    // Edge case tests for from_safe_path
    #[test]
    fn test_from_safe_path_double_dash_in_namespace_rejected() {
        // Namespaces containing "--" are rejected to preserve the Serialize <->
        // Deserialize roundtrip: qualified() output must always be re-parseable.
        // namespace_from_path() already sanitizes "--" -> "-" before reaching here.
        assert!(DaemonId::from_safe_path("my--project--api").is_err());
        assert!(DaemonId::from_safe_path("a--b--c--daemon").is_err());
    }

    #[test]
    fn test_from_safe_path_roundtrip_via_qualified() {
        // Standard case - single "--" separator, full roundtrip via qualified()
        let id = DaemonId::from_safe_path("global--api").unwrap();
        assert_eq!(id.namespace(), "global");
        assert_eq!(id.name(), "api");
        // Must roundtrip through qualified format (Serialize <-> Deserialize)
        let recovered = DaemonId::parse(&id.qualified()).unwrap();
        assert_eq!(recovered, id);
    }

    #[test]
    fn test_from_safe_path_no_separator() {
        // No "--" at all - should fail
        assert!(DaemonId::from_safe_path("globalapi").is_err());
        assert!(DaemonId::from_safe_path("api").is_err());
    }

    #[test]
    fn test_from_safe_path_empty_parts() {
        // Empty namespace (starts with --) - should fail validation
        let result = DaemonId::from_safe_path("--api");
        assert!(result.is_err());

        // Empty name (ends with --) - should fail validation
        let result = DaemonId::from_safe_path("namespace--");
        assert!(result.is_err());
    }

    // Cross-namespace dependency parsing tests
    #[test]
    fn test_parse_cross_namespace_dependency() {
        // Can parse fully qualified dependency reference
        let id = DaemonId::parse("other-project/postgres").unwrap();
        assert_eq!(id.namespace(), "other-project");
        assert_eq!(id.name(), "postgres");
    }

    // Test for directory names containing -- (namespace sanitization)
    #[test]
    fn test_directory_with_double_dash_in_name() {
        // Directory names like "my--project" are invalid for try_new because -- is reserved
        let result = DaemonId::try_new("my--project", "api");
        assert!(result.is_err());

        // from_safe_path also rejects "--" in namespace to preserve Serialize <->
        // Deserialize roundtrip. namespace_from_path() sanitizes "--" to "-" before
        // writing to the filesystem, so this case never arises in practice.
        let result = DaemonId::from_safe_path("my--project--api");
        assert!(
            result.is_err(),
            "from_safe_path must reject '--' in namespace to guarantee roundtrip via qualified()"
        );
    }

    #[test]
    fn test_parse_dot_namespace_rejected() {
        // parse("./api") should fail because "." is invalid as namespace
        // This ensures consistency with try_new(".", "api") which also fails
        let result = DaemonId::parse("./api");
        assert!(result.is_err());

        // Also test ".." as namespace
        let result = DaemonId::parse("../api");
        assert!(result.is_err());
    }

    // Serialization roundtrip tests
    #[test]
    fn test_daemon_id_toml_roundtrip() {
        #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
        struct TestConfig {
            daemon_id: DaemonId,
        }

        let config = TestConfig {
            daemon_id: DaemonId::new("my-project", "api"),
        };

        let toml_str = toml::to_string(&config).unwrap();
        assert!(toml_str.contains("daemon_id = \"my-project/api\""));

        let recovered: TestConfig = toml::from_str(&toml_str).unwrap();
        assert_eq!(config, recovered);
    }

    #[test]
    fn test_daemon_id_json_roundtrip_in_map() {
        use std::collections::HashMap;

        let mut map: HashMap<String, DaemonId> = HashMap::new();
        map.insert("primary".to_string(), DaemonId::new("global", "api"));
        map.insert("secondary".to_string(), DaemonId::new("project", "worker"));

        let json = serde_json::to_string(&map).unwrap();
        let recovered: HashMap<String, DaemonId> = serde_json::from_str(&json).unwrap();
        assert_eq!(map, recovered);
    }

    // Pitchfork special ID test
    #[test]
    fn test_pitchfork_id() {
        let id = DaemonId::pitchfork();
        assert_eq!(id.namespace(), "global");
        assert_eq!(id.name(), "pitchfork");
        assert_eq!(id.qualified(), "global/pitchfork");
    }

    // Unicode and special character tests
    #[test]
    fn test_daemon_id_rejects_unicode() {
        assert!(DaemonId::try_new("プロジェクト", "api").is_err());
        assert!(DaemonId::try_new("project", "工作者").is_err());
    }

    #[test]
    fn test_daemon_id_rejects_control_chars() {
        assert!(DaemonId::try_new("project\x00", "api").is_err());
        assert!(DaemonId::try_new("project", "api\x1b").is_err());
    }

    #[test]
    fn test_daemon_id_rejects_spaces() {
        assert!(DaemonId::try_new("my project", "api").is_err());
        assert!(DaemonId::try_new("project", "my api").is_err());
        assert!(DaemonId::parse("my project/api").is_err());
    }

    #[test]
    fn test_daemon_id_rejects_chars_outside_schema_pattern() {
        // Schema only allows [A-Za-z0-9_.-] for each component.
        assert!(DaemonId::try_new("project+alpha", "api").is_err());
        assert!(DaemonId::try_new("project", "api@v1").is_err());
    }

    #[test]
    fn test_daemon_id_rejects_leading_trailing_dash() {
        // Leading dash in namespace or name
        assert!(DaemonId::try_new("-project", "api").is_err());
        assert!(DaemonId::try_new("project", "-api").is_err());
        // Trailing dash in namespace or name
        assert!(DaemonId::try_new("project-", "api").is_err());
        assert!(DaemonId::try_new("project", "api-").is_err());
        // Verify the safe_path roundtrip invariant holds for names with internal dashes
        let id = DaemonId::try_new("a", "b").unwrap();
        let recovered = DaemonId::from_safe_path(&id.safe_path()).unwrap();
        assert_eq!(id, recovered);
        // from_safe_path must also reject names produced by invalid components
        assert!(DaemonId::from_safe_path("a---b").is_err()); // came from "a-"/"b" or "a"/"-b"
    }

    #[test]
    fn test_daemon_id_rejects_parent_dir_traversal() {
        assert!(DaemonId::try_new("project", "..").is_err());
        assert!(DaemonId::try_new("..", "api").is_err());
        assert!(DaemonId::parse("../api").is_err());
        assert!(DaemonId::parse("project/..").is_err());
    }

    #[test]
    fn test_daemon_id_rejects_current_dir() {
        assert!(DaemonId::try_new(".", "api").is_err());
        assert!(DaemonId::try_new("project", ".").is_err());
    }

    // Hash and equality tests for HashMap usage
    #[test]
    fn test_daemon_id_hash_consistency() {
        use std::collections::HashSet;

        let id1 = DaemonId::new("project", "api");
        let id2 = DaemonId::new("project", "api");
        let id3 = DaemonId::parse("project/api").unwrap();

        let mut set = HashSet::new();
        set.insert(id1.clone());

        // Same ID constructed differently should be found
        assert!(set.contains(&id2));
        assert!(set.contains(&id3));

        // Verify they're all equal
        assert_eq!(id1, id2);
        assert_eq!(id2, id3);
    }
}