Skip to main content

pitchfork_cli/
error.rs

1//! Custom diagnostic error types for rich error reporting via miette.
2//!
3//! This module provides structured error types that leverage miette's diagnostic
4//! features including error codes, help text, source code highlighting, and suggestions.
5
6// False positive: fields are used in #[error] format strings and miette derive macros
7#![allow(unused_assignments)]
8
9use miette::{Diagnostic, NamedSource, SourceSpan};
10use std::io;
11use std::path::PathBuf;
12use thiserror::Error;
13
14/// Errors related to daemon ID validation.
15#[derive(Debug, Error, Diagnostic)]
16pub enum DaemonIdError {
17    #[error("daemon ID cannot be empty")]
18    #[diagnostic(
19        code(pitchfork::daemon::empty_id),
20        url("https://pitchfork.jdx.dev/configuration"),
21        help("provide a non-empty identifier for the daemon")
22    )]
23    Empty,
24
25    #[error("daemon ID {component} cannot be empty")]
26    #[diagnostic(
27        code(pitchfork::daemon::empty_component),
28        url("https://pitchfork.jdx.dev/configuration"),
29        help("both namespace and name must be non-empty")
30    )]
31    EmptyComponent { component: String },
32
33    #[error("daemon ID '{id}' contains path separator '{sep}'")]
34    #[diagnostic(
35        code(pitchfork::daemon::path_separator),
36        url("https://pitchfork.jdx.dev/configuration"),
37        help("daemon IDs cannot contain '/' or '\\' to prevent path traversal")
38    )]
39    PathSeparator { id: String, sep: char },
40
41    #[error("daemon ID '{id}' contains parent directory reference '..'")]
42    #[diagnostic(
43        code(pitchfork::daemon::parent_dir_ref),
44        url("https://pitchfork.jdx.dev/configuration"),
45        help("daemon IDs cannot contain '..' to prevent path traversal")
46    )]
47    ParentDirRef { id: String },
48
49    #[error("daemon ID '{id}' contains reserved sequence '--'")]
50    #[diagnostic(
51        code(pitchfork::daemon::reserved_sequence),
52        url("https://pitchfork.jdx.dev/configuration"),
53        help("'--' is reserved for internal path encoding; use single dashes instead")
54    )]
55    ReservedSequence { id: String },
56
57    #[error("daemon ID component '{id}' starts or ends with a dash '-'")]
58    #[diagnostic(
59        code(pitchfork::daemon::leading_trailing_dash),
60        url("https://pitchfork.jdx.dev/configuration"),
61        help(
62            "remove the leading or trailing dash (e.g. 'my-daemon' not '-my-daemon' or 'my-daemon-')"
63        )
64    )]
65    LeadingTrailingDash { id: String },
66
67    #[error("daemon ID '{id}' contains spaces")]
68    #[diagnostic(
69        code(pitchfork::daemon::contains_space),
70        url("https://pitchfork.jdx.dev/configuration"),
71        help("use hyphens or underscores instead of spaces (e.g., 'my-daemon' or 'my_daemon')")
72    )]
73    ContainsSpace { id: String },
74
75    #[error("daemon ID cannot be '.'")]
76    #[diagnostic(
77        code(pitchfork::daemon::current_dir),
78        url("https://pitchfork.jdx.dev/configuration"),
79        help("'.' refers to the current directory; use a descriptive name instead")
80    )]
81    CurrentDir,
82
83    #[error("daemon ID '{id}' contains non-printable or non-ASCII character")]
84    #[diagnostic(
85        code(pitchfork::daemon::invalid_chars),
86        url("https://pitchfork.jdx.dev/configuration"),
87        help(
88            "daemon IDs must contain only printable ASCII characters (letters, numbers, hyphens, underscores, dots)"
89        )
90    )]
91    InvalidChars { id: String },
92
93    #[error("daemon ID '{id}' is missing namespace (expected format: namespace/name)")]
94    #[diagnostic(
95        code(pitchfork::daemon::missing_namespace),
96        url("https://pitchfork.jdx.dev/configuration"),
97        help("use qualified format like 'global/myapp' or 'project-name/daemon'")
98    )]
99    MissingNamespace { id: String },
100
101    #[error("invalid safe path format '{path}' (expected namespace--name)")]
102    #[diagnostic(
103        code(pitchfork::daemon::invalid_safe_path),
104        help("safe paths use '--' to separate namespace and name")
105    )]
106    InvalidSafePath { path: String },
107}
108
109/// Errors related to daemon operations.
110#[derive(Debug, Error, Diagnostic)]
111pub enum DaemonError {
112    #[error("failed to stop daemon '{id}': {error}")]
113    #[diagnostic(
114        code(pitchfork::daemon::stop_failed),
115        help("the process may be stuck or require manual intervention. Try: kill -9 <pid>")
116    )]
117    StopFailed { id: String, error: String },
118}
119
120/// Errors related to dependency resolution.
121#[derive(Debug, Error, Diagnostic)]
122pub enum DependencyError {
123    #[error("daemon '{name}' not found in configuration")]
124    #[diagnostic(
125        code(pitchfork::deps::not_found),
126        url("https://pitchfork.jdx.dev/configuration#depends")
127    )]
128    DaemonNotFound {
129        name: String,
130        #[help]
131        suggestion: Option<String>,
132    },
133
134    #[error("daemon '{daemon}' depends on '{dependency}' which is not defined")]
135    #[diagnostic(
136        code(pitchfork::deps::missing_dependency),
137        url("https://pitchfork.jdx.dev/configuration#depends"),
138        help("add the missing daemon to your pitchfork.toml or remove it from the depends list")
139    )]
140    MissingDependency { daemon: String, dependency: String },
141
142    #[error("circular dependency detected involving: {}", involved.join(", "))]
143    #[diagnostic(
144        code(pitchfork::deps::circular),
145        url("https://pitchfork.jdx.dev/configuration#depends"),
146        help("break the cycle by removing one of the dependencies")
147    )]
148    CircularDependency {
149        /// The daemons involved in the cycle
150        involved: Vec<String>,
151    },
152}
153
154/// The message for a port found in use: on which local address, and by which
155/// process. `pid` 0 means no process holding the port could be found, which
156/// happens when it belongs to another user, whose sockets cannot be read, or
157/// when no process owns the socket any more, as with a connection that was
158/// never accepted or is still closing.
159pub fn port_in_use_message(port: u16, address: Option<&str>, process: &str, pid: u32) -> String {
160    let on = address.map(|a| format!(" on {a}")).unwrap_or_default();
161    if pid == 0 {
162        format!(
163            "port {port} is already in use{on}, but no process holding it could be found; \
164             it may belong to another user, or be a connection no process owns any more"
165        )
166    } else {
167        format!("port {port} is already in use{on} by process '{process}' (PID: {pid})")
168    }
169}
170
171/// Errors related to port binding and availability.
172#[derive(Debug, Error, Diagnostic)]
173pub enum PortError {
174    #[error("{}", port_in_use_message(*port, address.as_deref(), process, *pid))]
175    #[diagnostic(
176        code(pitchfork::port::in_use),
177        url("https://pitchfork.jdx.dev/configuration#port"),
178        help(
179            "choose a different port, stop the existing process, or enable auto_bump_port to automatically find an available port"
180        )
181    )]
182    InUse {
183        port: u16,
184        /// The local address whose bind found the port taken.
185        address: Option<String>,
186        process: String,
187        pid: u32,
188    },
189
190    #[error(
191        "could not find an available port after {attempts} attempts starting from {start_port}"
192    )]
193    #[diagnostic(
194        code(pitchfork::port::no_available_port),
195        url("https://pitchfork.jdx.dev/configuration#port"),
196        help("manually specify an available port or reduce the number of concurrent services")
197    )]
198    NoAvailablePort { start_port: u16, attempts: u32 },
199
200    #[error("port {port} is reserved by daemon {daemon}")]
201    #[diagnostic(
202        code(pitchfork::port::claimed),
203        url("https://pitchfork.jdx.dev/configuration#port"),
204        help(
205            "choose a different port or enable auto_bump_port to automatically find an available port"
206        )
207    )]
208    Claimed { port: u16, daemon: String },
209}
210
211/// Error for TOML configuration parse failures with source code highlighting.
212#[derive(Debug, Error, Diagnostic)]
213pub enum ConfigParseError {
214    #[error("failed to parse configuration")]
215    #[diagnostic(code(pitchfork::config::parse_error))]
216    TomlError {
217        /// The source file contents for display
218        #[source_code]
219        src: NamedSource<String>,
220
221        /// The location of the error in the source
222        #[label("{message}")]
223        span: SourceSpan,
224
225        /// The error message from the TOML parser
226        message: String,
227
228        /// Additional help text
229        #[help]
230        help: Option<String>,
231    },
232
233    #[error("invalid daemon name '{name}' in {}", path.display())]
234    #[diagnostic(
235        code(pitchfork::config::invalid_daemon_name),
236        url("https://pitchfork.jdx.dev/configuration"),
237        help("daemon names must be valid identifiers without spaces, '--', or special characters")
238    )]
239    InvalidDaemonName {
240        name: String,
241        path: PathBuf,
242        reason: String,
243    },
244
245    #[error(
246        "daemon '{daemon}' in {} sets proxy_tls = \"passthrough\" but has no port",
247        path.display()
248    )]
249    #[diagnostic(
250        code(pitchfork::config::passthrough_without_port),
251        url("https://pitchfork.jdx.dev/guides/port-management#tls-passthrough"),
252        help(
253            "TLS passthrough splices the raw stream to a port on 127.0.0.1, so the daemon's port must be known up front; add `port = <number>` to the daemon, or remove proxy_tls"
254        )
255    )]
256    PassthroughWithoutPort { daemon: String, path: PathBuf },
257
258    #[error("daemon '{daemon}' in {} has an empty run array", path.display())]
259    #[diagnostic(
260        code(pitchfork::config::empty_run),
261        url("https://pitchfork.jdx.dev/reference/configuration#run-required"),
262        help("the first element of `run` is the program to start; give it one, or use a string")
263    )]
264    EmptyRunArgv { daemon: String, path: PathBuf },
265
266    #[error(
267        "daemon '{daemon}' in {} starts its run array with \"exec\"",
268        path.display()
269    )]
270    #[diagnostic(
271        code(pitchfork::config::exec_in_run_array),
272        url("https://pitchfork.jdx.dev/reference/configuration#run-required"),
273        help(
274            "a run array starts the program directly, without a shell, so there is no shell for `exec` to replace; remove \"exec\" and start the array with the program"
275        )
276    )]
277    ExecInRunArgv { daemon: String, path: PathBuf },
278
279    #[error(
280        "daemon '{daemon}' in {} has no program in its ready_cmd array",
281        path.display()
282    )]
283    #[diagnostic(
284        code(pitchfork::config::empty_ready_cmd),
285        url("https://pitchfork.jdx.dev/reference/configuration#ready-cmd"),
286        help(
287            "the first element of a `ready_cmd` array is the program to run; give it one, or use a string"
288        )
289    )]
290    EmptyReadyCmdArgv { daemon: String, path: PathBuf },
291
292    #[error(
293        "daemon '{daemon}' in {} starts its ready_cmd array with \"exec\"",
294        path.display()
295    )]
296    #[diagnostic(
297        code(pitchfork::config::exec_in_ready_cmd_array),
298        url("https://pitchfork.jdx.dev/reference/configuration#ready-cmd"),
299        help(
300            "a ready_cmd array runs the program directly, without a shell, so there is no shell for `exec` to replace; remove \"exec\" and start the array with the program"
301        )
302    )]
303    ExecInReadyCmdArgv { daemon: String, path: PathBuf },
304
305    #[error(
306        "daemon '{daemon}' in {} has no program in its health_cmd array",
307        path.display()
308    )]
309    #[diagnostic(
310        code(pitchfork::config::empty_health_cmd),
311        url("https://pitchfork.jdx.dev/reference/configuration#health-cmd"),
312        help(
313            "the first element of a `health_cmd` array is the program to run; give it one, or use a string"
314        )
315    )]
316    EmptyHealthCmdArgv { daemon: String, path: PathBuf },
317
318    #[error(
319        "daemon '{daemon}' in {} starts its health_cmd array with \"exec\"",
320        path.display()
321    )]
322    #[diagnostic(
323        code(pitchfork::config::exec_in_health_cmd_array),
324        url("https://pitchfork.jdx.dev/reference/configuration#health-cmd"),
325        help(
326            "a health_cmd array runs the program directly, without a shell, so there is no shell for `exec` to replace; remove \"exec\" and start the array with the program"
327        )
328    )]
329    ExecInHealthCmdArgv { daemon: String, path: PathBuf },
330
331    #[error(
332        "daemon '{daemon}' in {} sets proxy_tls_port = {port}, which is not one of its ports {declared:?}",
333        path.display()
334    )]
335    #[diagnostic(
336        code(pitchfork::config::proxy_port_not_declared),
337        url(
338            "https://pitchfork.jdx.dev/guides/port-management#choosing-a-port-on-a-multi-port-daemon"
339        ),
340        help(
341            "the proxy hostname maps to one of the daemon's own ports, so name a port from `port`, or add this one to it"
342        )
343    )]
344    ProxyPortNotDeclared {
345        daemon: String,
346        port: u16,
347        declared: Vec<u16>,
348        path: PathBuf,
349    },
350
351    #[error(
352        "daemon '{daemon}' in {} sets {key} = 0, which is not a port a hostname can be routed to",
353        path.display()
354    )]
355    #[diagnostic(
356        code(pitchfork::config::proxy_port_zero),
357        url(
358            "https://pitchfork.jdx.dev/guides/port-management#choosing-a-port-on-a-multi-port-daemon"
359        ),
360        help(
361            "port 0 asks the operating system to pick a port, so there is no fixed port for the proxy to send a hostname to; name the port the daemon actually listens on"
362        )
363    )]
364    ProxyPortZero {
365        daemon: String,
366        key: &'static str,
367        path: PathBuf,
368    },
369
370    #[error(
371        "invalid dependency '{dependency}' in daemon '{daemon}' ({}): {reason}",
372        path.display()
373    )]
374    #[diagnostic(
375        code(pitchfork::config::invalid_dependency),
376        url("https://pitchfork.jdx.dev/configuration#depends"),
377        help(
378            "dependency IDs must be valid daemon IDs; use 'name' for same namespace or 'namespace/name' for cross-namespace"
379        )
380    )]
381    InvalidDependency {
382        daemon: String,
383        dependency: String,
384        path: PathBuf,
385        reason: String,
386    },
387
388    #[error(
389        "daemon '{daemon}' in {} sets oneshot = true together with {}",
390        path.display(),
391        conflicts.join(", ")
392    )]
393    #[diagnostic(
394        code(pitchfork::config::oneshot_conflict),
395        url("https://pitchfork.jdx.dev/guides/ready-checks#oneshot-tasks"),
396        help(
397            "a oneshot daemon is ready when its process exits 0, so readiness and health checks do not apply; remove them or drop oneshot = true"
398        )
399    )]
400    OneshotConflict {
401        daemon: String,
402        path: PathBuf,
403        conflicts: Vec<String>,
404    },
405
406    #[error(
407        "namespace collision: '{}' and '{}' both resolve to namespace '{ns}'",
408        path_a.display(),
409        path_b.display()
410    )]
411    #[diagnostic(
412        code(pitchfork::config::namespace_collision),
413        url("https://pitchfork.jdx.dev/concepts/namespaces"),
414        help(
415            "rename one of the directories so that no two project configs share the same namespace"
416        )
417    )]
418    NamespaceCollision {
419        path_a: PathBuf,
420        path_b: PathBuf,
421        ns: String,
422    },
423
424    #[error(
425        "invalid namespace '{namespace}' in {}: {reason}",
426        path.display()
427    )]
428    #[diagnostic(
429        code(pitchfork::config::invalid_namespace),
430        url("https://pitchfork.jdx.dev/concepts/namespaces"),
431        help(
432            "set a valid top-level namespace in your pitchfork.toml, e.g. namespace = \"my-project\""
433        )
434    )]
435    InvalidNamespace {
436        path: PathBuf,
437        namespace: String,
438        reason: String,
439    },
440}
441
442impl ConfigParseError {
443    /// Create a new ConfigParseError from a toml parse error
444    pub fn from_toml_error(path: &std::path::Path, contents: String, err: toml::de::Error) -> Self {
445        let message = err.message().to_string();
446
447        // Try to get span information from the TOML error
448        let span = err
449            .span()
450            .map(|r| SourceSpan::from(r.start..r.end))
451            .unwrap_or_else(|| SourceSpan::from(0..0));
452
453        Self::TomlError {
454            src: NamedSource::new(path.display().to_string(), contents),
455            span,
456            message,
457            help: Some("check TOML syntax at https://toml.io".to_string()),
458        }
459    }
460}
461
462/// Errors related to file operations (config and state files).
463#[derive(Debug, Error, Diagnostic)]
464pub enum FileError {
465    #[error("failed to read file: {}", path.display())]
466    #[diagnostic(code(pitchfork::file::read_error))]
467    ReadError {
468        path: PathBuf,
469        #[source]
470        source: io::Error,
471    },
472
473    #[error("failed to write file: {}", path.display())]
474    #[diagnostic(code(pitchfork::file::write_error))]
475    WriteError {
476        path: PathBuf,
477        #[help]
478        details: Option<String>,
479    },
480
481    #[error("failed to serialize data for file: {}", path.display())]
482    #[diagnostic(
483        code(pitchfork::file::serialize_error),
484        help("this is likely an internal error; please report it")
485    )]
486    SerializeError {
487        path: PathBuf,
488        #[source]
489        source: toml::ser::Error,
490    },
491
492    #[error("no file path specified")]
493    #[diagnostic(
494        code(pitchfork::file::no_path),
495        help("ensure a pitchfork.toml file exists in your project or specify a path")
496    )]
497    NoPath,
498}
499
500/// Errors related to IPC communication with the supervisor.
501#[derive(Debug, Error, Diagnostic)]
502pub enum IpcError {
503    #[error("failed to connect to supervisor after {attempts} attempts")]
504    #[diagnostic(
505        code(pitchfork::ipc::connection_failed),
506        url("https://pitchfork.jdx.dev/supervisor")
507    )]
508    ConnectionFailed {
509        attempts: u32,
510        #[source]
511        source: Option<io::Error>,
512        #[help]
513        help: String,
514    },
515
516    /// The socket path does not fit in `sockaddr_un.sun_path`.
517    #[cfg(unix)]
518    #[error(
519        "the supervisor socket path is too long: {len} bytes, but this platform allows {limit}"
520    )]
521    #[diagnostic(
522        code(pitchfork::ipc::socket_path_too_long),
523        url("https://pitchfork.jdx.dev/reference/file-locations"),
524        help("{help}")
525    )]
526    SocketPathTooLong {
527        path: PathBuf,
528        len: usize,
529        limit: usize,
530        help: String,
531    },
532
533    #[error("IPC request timed out after {seconds}s")]
534    #[diagnostic(
535        code(pitchfork::ipc::timeout),
536        url("https://pitchfork.jdx.dev/supervisor"),
537        help(
538            "the supervisor may be unresponsive or overloaded.\nCheck supervisor status: pitchfork supervisor status\nView logs: pitchfork logs"
539        )
540    )]
541    Timeout { seconds: u64 },
542
543    #[error("IPC connection closed unexpectedly")]
544    #[diagnostic(
545        code(pitchfork::ipc::connection_closed),
546        url("https://pitchfork.jdx.dev/supervisor"),
547        help(
548            "the supervisor may have crashed or been stopped.\nRestart with: pitchfork supervisor start"
549        )
550    )]
551    ConnectionClosed,
552
553    #[error("failed to read IPC response")]
554    #[diagnostic(code(pitchfork::ipc::read_failed))]
555    ReadFailed {
556        #[source]
557        source: io::Error,
558    },
559
560    #[error("failed to send IPC request")]
561    #[diagnostic(code(pitchfork::ipc::send_failed))]
562    SendFailed {
563        #[source]
564        source: io::Error,
565    },
566
567    #[error("unexpected response from supervisor: expected {expected}, got {actual}")]
568    #[diagnostic(
569        code(pitchfork::ipc::unexpected_response),
570        help("this may indicate a version mismatch between the CLI and supervisor")
571    )]
572    UnexpectedResponse { expected: String, actual: String },
573
574    #[error("IPC message is invalid: {reason}")]
575    #[diagnostic(code(pitchfork::ipc::invalid_message))]
576    InvalidMessage { reason: String },
577}
578
579/// A collection of multiple errors that occurred during validation or processing.
580///
581/// This is useful when you want to collect and report all validation errors at once
582/// instead of failing on the first error.
583#[derive(Debug, Error, Diagnostic)]
584#[error("multiple errors occurred ({} total)", errors.len())]
585#[diagnostic(code(pitchfork::multiple_errors))]
586#[allow(dead_code)]
587pub struct MultipleErrors {
588    #[related]
589    pub errors: Vec<Box<dyn Diagnostic + Send + Sync + 'static>>,
590}
591
592#[allow(dead_code)]
593impl MultipleErrors {
594    /// Create a new MultipleErrors from a vector of diagnostics
595    pub fn new(errors: Vec<Box<dyn Diagnostic + Send + Sync + 'static>>) -> Self {
596        Self { errors }
597    }
598
599    /// Returns true if there are no errors
600    pub fn is_empty(&self) -> bool {
601        self.errors.is_empty()
602    }
603
604    /// Returns the number of errors
605    pub fn len(&self) -> usize {
606        self.errors.len()
607    }
608}
609
610/// Find the most similar daemon name for suggestions.
611pub fn find_similar_daemon<'a>(
612    name: &str,
613    available: impl Iterator<Item = &'a str>,
614) -> Option<String> {
615    use fuzzy_matcher::FuzzyMatcher;
616    use fuzzy_matcher::skim::SkimMatcherV2;
617
618    let matcher = SkimMatcherV2::default();
619    available
620        .filter_map(|candidate| {
621            matcher
622                .fuzzy_match(candidate, name)
623                .map(|score| (candidate, score))
624        })
625        .max_by_key(|(_, score)| *score)
626        .filter(|(_, score)| *score > 0)
627        .map(|(candidate, _)| format!("did you mean '{candidate}'?"))
628}
629
630#[cfg(test)]
631mod tests {
632    #[test]
633    fn port_in_use_message_names_the_address_and_the_holder() {
634        assert_eq!(
635            port_in_use_message(3000, Some("127.0.0.1"), "node", 42),
636            "port 3000 is already in use on 127.0.0.1 by process 'node' (PID: 42)"
637        );
638        // No listening process found: say so instead of naming "unknown".
639        let message = port_in_use_message(3000, Some("0.0.0.0"), "unknown", 0);
640        assert!(message.starts_with("port 3000 is already in use on 0.0.0.0, but no process"));
641        assert!(!message.contains("unknown"));
642        // A supervisor that does not report the address.
643        assert_eq!(
644            port_in_use_message(3000, None, "node", 42),
645            "port 3000 is already in use by process 'node' (PID: 42)"
646        );
647    }
648
649    use super::*;
650
651    #[test]
652    fn test_daemon_id_error_display() {
653        let err = DaemonIdError::Empty;
654        assert_eq!(err.to_string(), "daemon ID cannot be empty");
655
656        let err = DaemonIdError::PathSeparator {
657            id: "foo/bar".to_string(),
658            sep: '/',
659        };
660        assert_eq!(
661            err.to_string(),
662            "daemon ID 'foo/bar' contains path separator '/'"
663        );
664
665        let err = DaemonIdError::ContainsSpace {
666            id: "my app".to_string(),
667        };
668        assert_eq!(err.to_string(), "daemon ID 'my app' contains spaces");
669    }
670
671    #[test]
672    fn test_dependency_error_display() {
673        let err = DependencyError::DaemonNotFound {
674            name: "postgres".to_string(),
675            suggestion: None,
676        };
677        assert_eq!(
678            err.to_string(),
679            "daemon 'postgres' not found in configuration"
680        );
681
682        let err = DependencyError::MissingDependency {
683            daemon: "api".to_string(),
684            dependency: "db".to_string(),
685        };
686        assert_eq!(
687            err.to_string(),
688            "daemon 'api' depends on 'db' which is not defined"
689        );
690
691        let err = DependencyError::CircularDependency {
692            involved: vec!["a".to_string(), "b".to_string(), "c".to_string()],
693        };
694        assert!(err.to_string().contains("circular dependency"));
695        assert!(err.to_string().contains("a, b, c"));
696    }
697
698    #[test]
699    fn test_find_similar_daemon() {
700        let daemons = ["postgres", "redis", "api", "worker"];
701
702        // Close match
703        let suggestion = find_similar_daemon("postgre", daemons.iter().copied());
704        assert_eq!(suggestion, Some("did you mean 'postgres'?".to_string()));
705
706        // No reasonable match
707        let suggestion = find_similar_daemon("xyz123", daemons.iter().copied());
708        assert!(suggestion.is_none());
709    }
710
711    #[test]
712    fn test_file_error_display() {
713        let err = FileError::ReadError {
714            path: PathBuf::from("/path/to/config.toml"),
715            source: io::Error::new(io::ErrorKind::NotFound, "file not found"),
716        };
717        assert!(err.to_string().contains("failed to read file"));
718        assert!(err.to_string().contains("config.toml"));
719
720        let err = FileError::NoPath;
721        assert!(err.to_string().contains("no file path"));
722    }
723
724    #[test]
725    fn test_ipc_error_display() {
726        let err = IpcError::ConnectionFailed {
727            attempts: 5,
728            source: None,
729            help: "ensure the supervisor is running".to_string(),
730        };
731        assert!(err.to_string().contains("failed to connect"));
732        assert!(err.to_string().contains("5 attempts"));
733
734        let err = IpcError::Timeout { seconds: 30 };
735        assert!(err.to_string().contains("timed out"));
736        assert!(err.to_string().contains("30s"));
737
738        let err = IpcError::UnexpectedResponse {
739            expected: "Ok".to_string(),
740            actual: "Error".to_string(),
741        };
742        assert!(err.to_string().contains("unexpected response"));
743        assert!(err.to_string().contains("Ok"));
744        assert!(err.to_string().contains("Error"));
745    }
746
747    #[test]
748    fn test_config_parse_error() {
749        let contents = "[daemons.test]\nrun = ".to_string();
750        let err = toml::from_str::<toml::Value>(&contents).unwrap_err();
751        let parse_err =
752            ConfigParseError::from_toml_error(std::path::Path::new("test.toml"), contents, err);
753
754        assert!(parse_err.to_string().contains("failed to parse"));
755    }
756
757    #[test]
758    fn test_multiple_errors() {
759        let errors: Vec<Box<dyn Diagnostic + Send + Sync>> = vec![
760            Box::new(DaemonIdError::Empty),
761            Box::new(DaemonIdError::CurrentDir),
762        ];
763        let multi = MultipleErrors::new(errors);
764
765        assert_eq!(multi.len(), 2);
766        assert!(!multi.is_empty());
767        assert!(multi.to_string().contains("2 total"));
768    }
769}